three.webgpu.nodes.js 1.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760
  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, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, 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, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, 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, ClampToEdgeWrapping, 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. /**
  468. * Computes a cache key for the given node.
  469. *
  470. * @private
  471. * @method
  472. * @param {Object|Node} object - The object to be hashed.
  473. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  474. * @return {number} The hash.
  475. */
  476. function getCacheKey$1( object, force = false ) {
  477. const values = [];
  478. if ( object.isNode === true ) {
  479. values.push( object.id );
  480. }
  481. for ( const { property, childNode } of getNodeChildren( object ) ) {
  482. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  483. }
  484. return cyrb53( values );
  485. }
  486. /**
  487. * This generator function can be used to iterate over the node children
  488. * of the given object.
  489. *
  490. * @private
  491. * @generator
  492. * @param {Object} node - The object to be hashed.
  493. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  494. * @yields {Object} A result node holding the property, index (if available) and the child node.
  495. */
  496. function* getNodeChildren( node, toJSON = false ) {
  497. for ( const property of Object.getOwnPropertyNames( node ) ) {
  498. // Ignore private properties.
  499. if ( property.startsWith( '_' ) === true ) continue;
  500. const object = node[ property ];
  501. if ( Array.isArray( object ) === true ) {
  502. for ( let i = 0; i < object.length; i ++ ) {
  503. const child = object[ i ];
  504. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  505. yield { property, index: i, childNode: child };
  506. }
  507. }
  508. } else if ( object && object.isNode === true ) {
  509. yield { property, childNode: object };
  510. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  511. for ( const subProperty in object ) {
  512. // Ignore private properties.
  513. if ( subProperty.startsWith( '_' ) === true ) continue;
  514. const child = object[ subProperty ];
  515. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  516. yield { property, index: subProperty, childNode: child };
  517. }
  518. }
  519. }
  520. }
  521. }
  522. const typeFromLength = /*@__PURE__*/ new Map( [
  523. [ 1, 'float' ],
  524. [ 2, 'vec2' ],
  525. [ 3, 'vec3' ],
  526. [ 4, 'vec4' ],
  527. [ 9, 'mat3' ],
  528. [ 16, 'mat4' ]
  529. ] );
  530. const dataFromObject = /*@__PURE__*/ new WeakMap();
  531. /**
  532. * Returns the data type for the given the length.
  533. *
  534. * @private
  535. * @method
  536. * @param {number} length - The length.
  537. * @return {string} The data type.
  538. */
  539. function getTypeFromLength( length ) {
  540. return typeFromLength.get( length );
  541. }
  542. /**
  543. * Returns the typed array for the given data type.
  544. *
  545. * @private
  546. * @method
  547. * @param {string} type - The data type.
  548. * @return {TypedArray} The typed array.
  549. */
  550. function getTypedArrayFromType( type ) {
  551. // Handle component type for vectors and matrices
  552. if ( /[iu]?vec\d/.test( type ) ) {
  553. // Handle int vectors
  554. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  555. // Handle uint vectors
  556. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  557. // Default to float vectors
  558. return Float32Array;
  559. }
  560. // Handle matrices (always float)
  561. if ( /mat\d/.test( type ) ) return Float32Array;
  562. // Basic types
  563. if ( /float/.test( type ) ) return Float32Array;
  564. if ( /uint/.test( type ) ) return Uint32Array;
  565. if ( /int/.test( type ) ) return Int32Array;
  566. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  567. }
  568. /**
  569. * Returns the length for the given data type.
  570. *
  571. * @private
  572. * @method
  573. * @param {string} type - The data type.
  574. * @return {number} The length.
  575. */
  576. function getLengthFromType( type ) {
  577. if ( /float|int|uint/.test( type ) ) return 1;
  578. if ( /vec2/.test( type ) ) return 2;
  579. if ( /vec3/.test( type ) ) return 3;
  580. if ( /vec4/.test( type ) ) return 4;
  581. if ( /mat2/.test( type ) ) return 4;
  582. if ( /mat3/.test( type ) ) return 9;
  583. if ( /mat4/.test( type ) ) return 16;
  584. error( 'TSL: Unsupported type:', type );
  585. }
  586. /**
  587. * Returns the gpu memory length for the given data type.
  588. *
  589. * @private
  590. * @method
  591. * @param {string} type - The data type.
  592. * @return {number} The length.
  593. */
  594. function getMemoryLengthFromType( type ) {
  595. if ( /float|int|uint/.test( type ) ) return 1;
  596. if ( /vec2/.test( type ) ) return 2;
  597. if ( /vec3/.test( type ) ) return 3;
  598. if ( /vec4/.test( type ) ) return 4;
  599. if ( /mat2/.test( type ) ) return 4;
  600. if ( /mat3/.test( type ) ) return 12;
  601. if ( /mat4/.test( type ) ) return 16;
  602. error( 'TSL: Unsupported type:', type );
  603. }
  604. /**
  605. * Returns the byte boundary for the given data type.
  606. *
  607. * @private
  608. * @method
  609. * @param {string} type - The data type.
  610. * @return {number} The byte boundary.
  611. */
  612. function getByteBoundaryFromType( type ) {
  613. if ( /float|int|uint/.test( type ) ) return 4;
  614. if ( /vec2/.test( type ) ) return 8;
  615. if ( /vec3/.test( type ) ) return 16;
  616. if ( /vec4/.test( type ) ) return 16;
  617. if ( /mat2/.test( type ) ) return 8;
  618. if ( /mat3/.test( type ) ) return 48;
  619. if ( /mat4/.test( type ) ) return 64;
  620. error( 'TSL: Unsupported type:', type );
  621. }
  622. /**
  623. * Returns the data type for the given value.
  624. *
  625. * @private
  626. * @method
  627. * @param {any} value - The value.
  628. * @return {?string} The data type.
  629. */
  630. function getValueType( value ) {
  631. if ( value === undefined || value === null ) return null;
  632. const typeOf = typeof value;
  633. if ( value.isNode === true ) {
  634. return 'node';
  635. } else if ( typeOf === 'number' ) {
  636. return 'float';
  637. } else if ( typeOf === 'boolean' ) {
  638. return 'bool';
  639. } else if ( typeOf === 'string' ) {
  640. return 'string';
  641. } else if ( typeOf === 'function' ) {
  642. return 'shader';
  643. } else if ( value.isVector2 === true ) {
  644. return 'vec2';
  645. } else if ( value.isVector3 === true ) {
  646. return 'vec3';
  647. } else if ( value.isVector4 === true ) {
  648. return 'vec4';
  649. } else if ( value.isMatrix2 === true ) {
  650. return 'mat2';
  651. } else if ( value.isMatrix3 === true ) {
  652. return 'mat3';
  653. } else if ( value.isMatrix4 === true ) {
  654. return 'mat4';
  655. } else if ( value.isColor === true ) {
  656. return 'color';
  657. } else if ( value instanceof ArrayBuffer ) {
  658. return 'ArrayBuffer';
  659. }
  660. return null;
  661. }
  662. /**
  663. * Returns the value/object for the given data type and parameters.
  664. *
  665. * @private
  666. * @method
  667. * @param {string} type - The given type.
  668. * @param {...any} params - A parameter list.
  669. * @return {any} The value/object.
  670. */
  671. function getValueFromType( type, ...params ) {
  672. const last4 = type ? type.slice( -4 ) : undefined;
  673. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  674. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  675. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  676. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  677. }
  678. if ( type === 'color' ) {
  679. return new Color( ...params );
  680. } else if ( last4 === 'vec2' ) {
  681. return new Vector2( ...params );
  682. } else if ( last4 === 'vec3' ) {
  683. return new Vector3( ...params );
  684. } else if ( last4 === 'vec4' ) {
  685. return new Vector4( ...params );
  686. } else if ( last4 === 'mat2' ) {
  687. return new Matrix2( ...params );
  688. } else if ( last4 === 'mat3' ) {
  689. return new Matrix3( ...params );
  690. } else if ( last4 === 'mat4' ) {
  691. return new Matrix4( ...params );
  692. } else if ( type === 'bool' ) {
  693. return params[ 0 ] || false;
  694. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  695. return params[ 0 ] || 0;
  696. } else if ( type === 'string' ) {
  697. return params[ 0 ] || '';
  698. } else if ( type === 'ArrayBuffer' ) {
  699. return base64ToArrayBuffer( params[ 0 ] );
  700. }
  701. return null;
  702. }
  703. /**
  704. * Gets the object data that can be shared between different rendering steps.
  705. *
  706. * @private
  707. * @param {Object} object - The object to get the data for.
  708. * @return {Object} The object data.
  709. */
  710. function getDataFromObject( object ) {
  711. let data = dataFromObject.get( object );
  712. if ( data === undefined ) {
  713. data = {};
  714. dataFromObject.set( object, data );
  715. }
  716. return data;
  717. }
  718. /**
  719. * Converts the given array buffer to a Base64 string.
  720. *
  721. * @private
  722. * @method
  723. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  724. * @return {string} The Base64 string.
  725. */
  726. function arrayBufferToBase64( arrayBuffer ) {
  727. let chars = '';
  728. const array = new Uint8Array( arrayBuffer );
  729. for ( let i = 0; i < array.length; i ++ ) {
  730. chars += String.fromCharCode( array[ i ] );
  731. }
  732. return btoa( chars );
  733. }
  734. /**
  735. * Converts the given Base64 string to an array buffer.
  736. *
  737. * @private
  738. * @method
  739. * @param {string} base64 - The Base64 string.
  740. * @return {ArrayBuffer} The array buffer.
  741. */
  742. function base64ToArrayBuffer( base64 ) {
  743. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  744. }
  745. var NodeUtils = /*#__PURE__*/Object.freeze({
  746. __proto__: null,
  747. arrayBufferToBase64: arrayBufferToBase64,
  748. base64ToArrayBuffer: base64ToArrayBuffer,
  749. getByteBoundaryFromType: getByteBoundaryFromType,
  750. getCacheKey: getCacheKey$1,
  751. getDataFromObject: getDataFromObject,
  752. getLengthFromType: getLengthFromType,
  753. getMemoryLengthFromType: getMemoryLengthFromType,
  754. getNodeChildren: getNodeChildren,
  755. getTypeFromLength: getTypeFromLength,
  756. getTypedArrayFromType: getTypedArrayFromType,
  757. getValueFromType: getValueFromType,
  758. getValueType: getValueType,
  759. hash: hash$1,
  760. hashArray: hashArray,
  761. hashString: hashString
  762. });
  763. /**
  764. * Possible shader stages.
  765. *
  766. * @property {string} VERTEX The vertex shader stage.
  767. * @property {string} FRAGMENT The fragment shader stage.
  768. */
  769. const NodeShaderStage = {
  770. VERTEX: 'vertex',
  771. FRAGMENT: 'fragment'
  772. };
  773. /**
  774. * Update types of a node.
  775. *
  776. * @property {string} NONE The update method is not executed.
  777. * @property {string} FRAME The update method is executed per frame.
  778. * @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.
  779. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  780. */
  781. const NodeUpdateType = {
  782. NONE: 'none',
  783. FRAME: 'frame',
  784. RENDER: 'render',
  785. OBJECT: 'object'
  786. };
  787. /**
  788. * Data types of a node.
  789. *
  790. * @property {string} BOOLEAN Boolean type.
  791. * @property {string} INTEGER Integer type.
  792. * @property {string} FLOAT Float type.
  793. * @property {string} VECTOR2 Two-dimensional vector type.
  794. * @property {string} VECTOR3 Three-dimensional vector type.
  795. * @property {string} VECTOR4 Four-dimensional vector type.
  796. * @property {string} MATRIX2 2x2 matrix type.
  797. * @property {string} MATRIX3 3x3 matrix type.
  798. * @property {string} MATRIX4 4x4 matrix type.
  799. */
  800. const NodeType = {
  801. BOOLEAN: 'bool',
  802. INTEGER: 'int',
  803. FLOAT: 'float',
  804. VECTOR2: 'vec2',
  805. VECTOR3: 'vec3',
  806. VECTOR4: 'vec4',
  807. MATRIX2: 'mat2',
  808. MATRIX3: 'mat3',
  809. MATRIX4: 'mat4'
  810. };
  811. /**
  812. * Access types of a node. These are relevant for compute and storage usage.
  813. *
  814. * @property {string} READ_ONLY Read-only access
  815. * @property {string} WRITE_ONLY Write-only access.
  816. * @property {string} READ_WRITE Read and write access.
  817. */
  818. const NodeAccess = {
  819. READ_ONLY: 'readOnly',
  820. WRITE_ONLY: 'writeOnly',
  821. READ_WRITE: 'readWrite',
  822. };
  823. const defaultShaderStages = [ 'fragment', 'vertex' ];
  824. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  825. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  826. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  827. const _parentBuildStage = {
  828. analyze: 'setup',
  829. generate: 'analyze'
  830. };
  831. let _nodeId = 0;
  832. /**
  833. * Base class for all nodes.
  834. *
  835. * @augments EventDispatcher
  836. */
  837. class Node extends EventDispatcher {
  838. static get type() {
  839. return 'Node';
  840. }
  841. /**
  842. * Constructs a new node.
  843. *
  844. * @param {?string} nodeType - The node type.
  845. */
  846. constructor( nodeType = null ) {
  847. super();
  848. /**
  849. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  850. *
  851. * @type {?string}
  852. * @default null
  853. */
  854. this.nodeType = nodeType;
  855. /**
  856. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  857. *
  858. * @type {string}
  859. * @default 'none'
  860. */
  861. this.updateType = NodeUpdateType.NONE;
  862. /**
  863. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  864. *
  865. * @type {string}
  866. * @default 'none'
  867. */
  868. this.updateBeforeType = NodeUpdateType.NONE;
  869. /**
  870. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  871. *
  872. * @type {string}
  873. * @default 'none'
  874. */
  875. this.updateAfterType = NodeUpdateType.NONE;
  876. /**
  877. * The UUID of the node.
  878. *
  879. * @type {string}
  880. * @readonly
  881. */
  882. this.uuid = MathUtils.generateUUID();
  883. /**
  884. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  885. *
  886. * @type {number}
  887. * @readonly
  888. * @default 0
  889. */
  890. this.version = 0;
  891. /**
  892. * The name of the node.
  893. *
  894. * @type {string}
  895. * @default ''
  896. */
  897. this.name = '';
  898. /**
  899. * Whether this node is global or not. This property is relevant for the internal
  900. * node caching system. All nodes which should be declared just once should
  901. * set this flag to `true` (a typical example is {@link AttributeNode}).
  902. *
  903. * @type {boolean}
  904. * @default false
  905. */
  906. this.global = false;
  907. /**
  908. * Create a list of parents for this node during the build process.
  909. *
  910. * @type {boolean}
  911. * @default false
  912. */
  913. this.parents = false;
  914. /**
  915. * This flag can be used for type testing.
  916. *
  917. * @type {boolean}
  918. * @readonly
  919. * @default true
  920. */
  921. this.isNode = true;
  922. // private
  923. this._beforeNodes = null;
  924. /**
  925. * The cache key of this node.
  926. *
  927. * @private
  928. * @type {?number}
  929. * @default null
  930. */
  931. this._cacheKey = null;
  932. /**
  933. * The cache key 's version.
  934. *
  935. * @private
  936. * @type {number}
  937. * @default 0
  938. */
  939. this._cacheKeyVersion = 0;
  940. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  941. }
  942. /**
  943. * Set this property to `true` when the node should be regenerated.
  944. *
  945. * @type {boolean}
  946. * @default false
  947. * @param {boolean} value
  948. */
  949. set needsUpdate( value ) {
  950. if ( value === true ) {
  951. this.version ++;
  952. }
  953. }
  954. /**
  955. * The type of the class. The value is usually the constructor name.
  956. *
  957. * @type {string}
  958. * @readonly
  959. */
  960. get type() {
  961. return this.constructor.type;
  962. }
  963. /**
  964. * Convenient method for defining {@link Node#update}.
  965. *
  966. * @param {Function} callback - The update method.
  967. * @param {string} updateType - The update type.
  968. * @return {Node} A reference to this node.
  969. */
  970. onUpdate( callback, updateType ) {
  971. this.updateType = updateType;
  972. this.update = callback.bind( this );
  973. return this;
  974. }
  975. /**
  976. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  977. * this method automatically sets the update type to `FRAME`.
  978. *
  979. * @param {Function} callback - The update method.
  980. * @return {Node} A reference to this node.
  981. */
  982. onFrameUpdate( callback ) {
  983. return this.onUpdate( callback, NodeUpdateType.FRAME );
  984. }
  985. /**
  986. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  987. * this method automatically sets the update type to `RENDER`.
  988. *
  989. * @param {Function} callback - The update method.
  990. * @return {Node} A reference to this node.
  991. */
  992. onRenderUpdate( callback ) {
  993. return this.onUpdate( callback, NodeUpdateType.RENDER );
  994. }
  995. /**
  996. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  997. * this method automatically sets the update type to `OBJECT`.
  998. *
  999. * @param {Function} callback - The update method.
  1000. * @return {Node} A reference to this node.
  1001. */
  1002. onObjectUpdate( callback ) {
  1003. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1004. }
  1005. /**
  1006. * Convenient method for defining {@link Node#updateReference}.
  1007. *
  1008. * @param {Function} callback - The update method.
  1009. * @return {Node} A reference to this node.
  1010. */
  1011. onReference( callback ) {
  1012. this.updateReference = callback.bind( this );
  1013. return this;
  1014. }
  1015. /**
  1016. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1017. * to such objects based on a given state (e.g. the current node frame or builder).
  1018. *
  1019. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1020. * @return {any} The updated reference.
  1021. */
  1022. updateReference( /*state*/ ) {
  1023. return this;
  1024. }
  1025. /**
  1026. * By default this method returns the value of the {@link Node#global} flag. This method
  1027. * can be overwritten in derived classes if an analytical way is required to determine the
  1028. * global cache referring to the current shader-stage.
  1029. *
  1030. * @param {NodeBuilder} builder - The current node builder.
  1031. * @return {boolean} Whether this node is global or not.
  1032. */
  1033. isGlobal( /*builder*/ ) {
  1034. return this.global;
  1035. }
  1036. /**
  1037. * Generator function that can be used to iterate over the child nodes.
  1038. *
  1039. * @generator
  1040. * @yields {Node} A child node.
  1041. */
  1042. * getChildren() {
  1043. for ( const { childNode } of getNodeChildren( this ) ) {
  1044. yield childNode;
  1045. }
  1046. }
  1047. /**
  1048. * Calling this method dispatches the `dispose` event. This event can be used
  1049. * to register event listeners for clean up tasks.
  1050. */
  1051. dispose() {
  1052. this.dispatchEvent( { type: 'dispose' } );
  1053. }
  1054. /**
  1055. * Callback for {@link Node#traverse}.
  1056. *
  1057. * @callback traverseCallback
  1058. * @param {Node} node - The current node.
  1059. */
  1060. /**
  1061. * Can be used to traverse through the node's hierarchy.
  1062. *
  1063. * @param {traverseCallback} callback - A callback that is executed per node.
  1064. */
  1065. traverse( callback ) {
  1066. callback( this );
  1067. for ( const childNode of this.getChildren() ) {
  1068. childNode.traverse( callback );
  1069. }
  1070. }
  1071. /**
  1072. * Returns the cache key for this node.
  1073. *
  1074. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1075. * @return {number} The cache key of the node.
  1076. */
  1077. getCacheKey( force = false ) {
  1078. force = force || this.version !== this._cacheKeyVersion;
  1079. if ( force === true || this._cacheKey === null ) {
  1080. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1081. this._cacheKeyVersion = this.version;
  1082. }
  1083. return this._cacheKey;
  1084. }
  1085. /**
  1086. * Generate a custom cache key for this node.
  1087. *
  1088. * @return {number} The cache key of the node.
  1089. */
  1090. customCacheKey() {
  1091. return 0;
  1092. }
  1093. /**
  1094. * Returns the references to this node which is by default `this`.
  1095. *
  1096. * @return {Node} A reference to this node.
  1097. */
  1098. getScope() {
  1099. return this;
  1100. }
  1101. /**
  1102. * Returns the hash of the node which is used to identify the node. By default it's
  1103. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1104. * depending on their implementation.
  1105. *
  1106. * @param {NodeBuilder} builder - The current node builder.
  1107. * @return {string} The hash.
  1108. */
  1109. getHash( /*builder*/ ) {
  1110. return this.uuid;
  1111. }
  1112. /**
  1113. * Returns the update type of {@link Node#update}.
  1114. *
  1115. * @return {NodeUpdateType} The update type.
  1116. */
  1117. getUpdateType() {
  1118. return this.updateType;
  1119. }
  1120. /**
  1121. * Returns the update type of {@link Node#updateBefore}.
  1122. *
  1123. * @return {NodeUpdateType} The update type.
  1124. */
  1125. getUpdateBeforeType() {
  1126. return this.updateBeforeType;
  1127. }
  1128. /**
  1129. * Returns the update type of {@link Node#updateAfter}.
  1130. *
  1131. * @return {NodeUpdateType} The update type.
  1132. */
  1133. getUpdateAfterType() {
  1134. return this.updateAfterType;
  1135. }
  1136. /**
  1137. * Certain types are composed of multiple elements. For example a `vec3`
  1138. * is composed of three `float` values. This method returns the type of
  1139. * these elements.
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @return {string} The type of the node.
  1143. */
  1144. getElementType( builder ) {
  1145. const type = this.getNodeType( builder );
  1146. const elementType = builder.getElementType( type );
  1147. return elementType;
  1148. }
  1149. /**
  1150. * Returns the node member type for the given name.
  1151. *
  1152. * @param {NodeBuilder} builder - The current node builder.
  1153. * @param {string} name - The name of the member.
  1154. * @return {string} The type of the node.
  1155. */
  1156. getMemberType( /*builder, name*/ ) {
  1157. return 'void';
  1158. }
  1159. /**
  1160. * Returns the node's type.
  1161. *
  1162. * @param {NodeBuilder} builder - The current node builder.
  1163. * @return {string} The type of the node.
  1164. */
  1165. getNodeType( builder ) {
  1166. const nodeProperties = builder.getNodeProperties( this );
  1167. if ( nodeProperties.outputNode ) {
  1168. return nodeProperties.outputNode.getNodeType( builder );
  1169. }
  1170. return this.nodeType;
  1171. }
  1172. /**
  1173. * This method is used during the build process of a node and ensures
  1174. * equal nodes are not built multiple times but just once. For example if
  1175. * `attribute( 'uv' )` is used multiple times by the user, the build
  1176. * process makes sure to process just the first node.
  1177. *
  1178. * @param {NodeBuilder} builder - The current node builder.
  1179. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1180. */
  1181. getShared( builder ) {
  1182. const hash = this.getHash( builder );
  1183. const nodeFromHash = builder.getNodeFromHash( hash );
  1184. return nodeFromHash || this;
  1185. }
  1186. /**
  1187. * Returns the number of elements in the node array.
  1188. *
  1189. * @param {NodeBuilder} builder - The current node builder.
  1190. * @return {?number} The number of elements in the node array.
  1191. */
  1192. getArrayCount( /*builder*/ ) {
  1193. return null;
  1194. }
  1195. /**
  1196. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1197. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1198. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1199. *
  1200. * @param {NodeBuilder} builder - The current node builder.
  1201. * @return {?Node} The output node.
  1202. */
  1203. setup( builder ) {
  1204. const nodeProperties = builder.getNodeProperties( this );
  1205. let index = 0;
  1206. for ( const childNode of this.getChildren() ) {
  1207. nodeProperties[ 'node' + index ++ ] = childNode;
  1208. }
  1209. // return a outputNode if exists or null
  1210. return nodeProperties.outputNode || null;
  1211. }
  1212. /**
  1213. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1214. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1215. *
  1216. * @param {NodeBuilder} builder - The current node builder.
  1217. * @param {?Node} output - The target output node.
  1218. */
  1219. analyze( builder, output = null ) {
  1220. const usageCount = builder.increaseUsage( this );
  1221. if ( this.parents === true ) {
  1222. const nodeData = builder.getDataFromNode( this, 'any' );
  1223. nodeData.stages = nodeData.stages || {};
  1224. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1225. nodeData.stages[ builder.shaderStage ].push( output );
  1226. }
  1227. if ( usageCount === 1 ) {
  1228. // node flow children
  1229. const nodeProperties = builder.getNodeProperties( this );
  1230. for ( const childNode of Object.values( nodeProperties ) ) {
  1231. if ( childNode && childNode.isNode === true ) {
  1232. childNode.build( builder, this );
  1233. }
  1234. }
  1235. }
  1236. }
  1237. /**
  1238. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1239. * This state builds the output node and returns the resulting shader string.
  1240. *
  1241. * @param {NodeBuilder} builder - The current node builder.
  1242. * @param {?string} [output] - Can be used to define the output type.
  1243. * @return {?string} The generated shader string.
  1244. */
  1245. generate( builder, output ) {
  1246. const { outputNode } = builder.getNodeProperties( this );
  1247. if ( outputNode && outputNode.isNode === true ) {
  1248. return outputNode.build( builder, output );
  1249. }
  1250. }
  1251. /**
  1252. * The method can be implemented to update the node's internal state before it is used to render an object.
  1253. * The {@link Node#updateBeforeType} 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. updateBefore( /*frame*/ ) {
  1260. warn( 'Abstract function.' );
  1261. }
  1262. /**
  1263. * The method can be implemented to update the node's internal state after it was used to render an object.
  1264. * The {@link Node#updateAfterType} 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. updateAfter( /*frame*/ ) {
  1271. warn( 'Abstract function.' );
  1272. }
  1273. /**
  1274. * The method can be implemented to update the node's internal state when it is used to render an object.
  1275. * The {@link Node#updateType} property defines how often the update is executed.
  1276. *
  1277. * @abstract
  1278. * @param {NodeFrame} frame - A reference to the current node frame.
  1279. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1280. */
  1281. update( /*frame*/ ) {
  1282. warn( 'Abstract function.' );
  1283. }
  1284. before( node ) {
  1285. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1286. this._beforeNodes.push( node );
  1287. return this;
  1288. }
  1289. /**
  1290. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1291. * - **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.
  1292. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1293. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1294. *
  1295. * @param {NodeBuilder} builder - The current node builder.
  1296. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1297. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1298. */
  1299. build( builder, output = null ) {
  1300. const refNode = this.getShared( builder );
  1301. if ( this !== refNode ) {
  1302. return refNode.build( builder, output );
  1303. }
  1304. //
  1305. if ( this._beforeNodes !== null ) {
  1306. const currentBeforeNodes = this._beforeNodes;
  1307. this._beforeNodes = null;
  1308. for ( const beforeNode of currentBeforeNodes ) {
  1309. beforeNode.build( builder, output );
  1310. }
  1311. this._beforeNodes = currentBeforeNodes;
  1312. }
  1313. //
  1314. const nodeData = builder.getDataFromNode( this );
  1315. nodeData.buildStages = nodeData.buildStages || {};
  1316. nodeData.buildStages[ builder.buildStage ] = true;
  1317. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1318. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1319. // force parent build stage (setup or analyze)
  1320. const previousBuildStage = builder.getBuildStage();
  1321. builder.setBuildStage( parentBuildStage );
  1322. this.build( builder );
  1323. builder.setBuildStage( previousBuildStage );
  1324. }
  1325. //
  1326. builder.addNode( this );
  1327. builder.addChain( this );
  1328. /* Build stages expected results:
  1329. - "setup" -> Node
  1330. - "analyze" -> null
  1331. - "generate" -> String
  1332. */
  1333. let result = null;
  1334. const buildStage = builder.getBuildStage();
  1335. if ( buildStage === 'setup' ) {
  1336. this.updateReference( builder );
  1337. const properties = builder.getNodeProperties( this );
  1338. if ( properties.initialized !== true ) {
  1339. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1340. properties.initialized = true;
  1341. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1342. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1343. // !! no outputNode !!
  1344. //outputNode = builder.stack;
  1345. }*/
  1346. for ( const childNode of Object.values( properties ) ) {
  1347. if ( childNode && childNode.isNode === true ) {
  1348. if ( childNode.parents === true ) {
  1349. const childProperties = builder.getNodeProperties( childNode );
  1350. childProperties.parents = childProperties.parents || [];
  1351. childProperties.parents.push( this );
  1352. }
  1353. childNode.build( builder );
  1354. }
  1355. }
  1356. }
  1357. result = properties.outputNode;
  1358. } else if ( buildStage === 'analyze' ) {
  1359. this.analyze( builder, output );
  1360. } else if ( buildStage === 'generate' ) {
  1361. // If generate has just one argument, it means the output type is not required.
  1362. // This means that the node does not handle output conversions internally,
  1363. // so the value is stored in a cache and the builder handles the conversion
  1364. // for all requested output types.
  1365. const isGenerateOnce = this.generate.length < 2;
  1366. if ( isGenerateOnce ) {
  1367. const type = this.getNodeType( builder );
  1368. const nodeData = builder.getDataFromNode( this );
  1369. result = nodeData.snippet;
  1370. if ( result === undefined ) {
  1371. if ( nodeData.generated === undefined ) {
  1372. nodeData.generated = true;
  1373. result = this.generate( builder ) || '';
  1374. nodeData.snippet = result;
  1375. } else {
  1376. warn( 'Node: Recursion detected.', this );
  1377. result = '/* Recursion detected. */';
  1378. }
  1379. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1380. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1381. }
  1382. result = builder.format( result, type, output );
  1383. } else {
  1384. result = this.generate( builder, output ) || '';
  1385. }
  1386. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1387. // if no snippet is generated, return a default value
  1388. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1389. result = builder.generateConst( output );
  1390. }
  1391. }
  1392. builder.removeChain( this );
  1393. builder.addSequentialNode( this );
  1394. return result;
  1395. }
  1396. /**
  1397. * Returns the child nodes as a JSON object.
  1398. *
  1399. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1400. */
  1401. getSerializeChildren() {
  1402. return getNodeChildren( this );
  1403. }
  1404. /**
  1405. * Serializes the node to JSON.
  1406. *
  1407. * @param {Object} json - The output JSON object.
  1408. */
  1409. serialize( json ) {
  1410. const nodeChildren = this.getSerializeChildren();
  1411. const inputNodes = {};
  1412. for ( const { property, index, childNode } of nodeChildren ) {
  1413. if ( index !== undefined ) {
  1414. if ( inputNodes[ property ] === undefined ) {
  1415. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1416. }
  1417. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1418. } else {
  1419. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1420. }
  1421. }
  1422. if ( Object.keys( inputNodes ).length > 0 ) {
  1423. json.inputNodes = inputNodes;
  1424. }
  1425. }
  1426. /**
  1427. * Deserializes the node from the given JSON.
  1428. *
  1429. * @param {Object} json - The JSON object.
  1430. */
  1431. deserialize( json ) {
  1432. if ( json.inputNodes !== undefined ) {
  1433. const nodes = json.meta.nodes;
  1434. for ( const property in json.inputNodes ) {
  1435. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1436. const inputArray = [];
  1437. for ( const uuid of json.inputNodes[ property ] ) {
  1438. inputArray.push( nodes[ uuid ] );
  1439. }
  1440. this[ property ] = inputArray;
  1441. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1442. const inputObject = {};
  1443. for ( const subProperty in json.inputNodes[ property ] ) {
  1444. const uuid = json.inputNodes[ property ][ subProperty ];
  1445. inputObject[ subProperty ] = nodes[ uuid ];
  1446. }
  1447. this[ property ] = inputObject;
  1448. } else {
  1449. const uuid = json.inputNodes[ property ];
  1450. this[ property ] = nodes[ uuid ];
  1451. }
  1452. }
  1453. }
  1454. }
  1455. /**
  1456. * Serializes the node into the three.js JSON Object/Scene format.
  1457. *
  1458. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1459. * @return {Object} The serialized node.
  1460. */
  1461. toJSON( meta ) {
  1462. const { uuid, type } = this;
  1463. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1464. if ( isRoot ) {
  1465. meta = {
  1466. textures: {},
  1467. images: {},
  1468. nodes: {}
  1469. };
  1470. }
  1471. // serialize
  1472. let data = meta.nodes[ uuid ];
  1473. if ( data === undefined ) {
  1474. data = {
  1475. uuid,
  1476. type,
  1477. meta,
  1478. metadata: {
  1479. version: 4.7,
  1480. type: 'Node',
  1481. generator: 'Node.toJSON'
  1482. }
  1483. };
  1484. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1485. this.serialize( data );
  1486. delete data.meta;
  1487. }
  1488. // TODO: Copied from Object3D.toJSON
  1489. function extractFromCache( cache ) {
  1490. const values = [];
  1491. for ( const key in cache ) {
  1492. const data = cache[ key ];
  1493. delete data.metadata;
  1494. values.push( data );
  1495. }
  1496. return values;
  1497. }
  1498. if ( isRoot ) {
  1499. const textures = extractFromCache( meta.textures );
  1500. const images = extractFromCache( meta.images );
  1501. const nodes = extractFromCache( meta.nodes );
  1502. if ( textures.length > 0 ) data.textures = textures;
  1503. if ( images.length > 0 ) data.images = images;
  1504. if ( nodes.length > 0 ) data.nodes = nodes;
  1505. }
  1506. return data;
  1507. }
  1508. }
  1509. /**
  1510. * Base class for representing element access on an array-like
  1511. * node data structures.
  1512. *
  1513. * @augments Node
  1514. */
  1515. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1516. static get type() {
  1517. return 'ArrayElementNode';
  1518. }
  1519. /**
  1520. * Constructs an array element node.
  1521. *
  1522. * @param {Node} node - The array-like node.
  1523. * @param {Node} indexNode - The index node that defines the element access.
  1524. */
  1525. constructor( node, indexNode ) {
  1526. super();
  1527. /**
  1528. * The array-like node.
  1529. *
  1530. * @type {Node}
  1531. */
  1532. this.node = node;
  1533. /**
  1534. * The index node that defines the element access.
  1535. *
  1536. * @type {Node}
  1537. */
  1538. this.indexNode = indexNode;
  1539. /**
  1540. * This flag can be used for type testing.
  1541. *
  1542. * @type {boolean}
  1543. * @readonly
  1544. * @default true
  1545. */
  1546. this.isArrayElementNode = true;
  1547. }
  1548. /**
  1549. * This method is overwritten since the node type is inferred from the array-like node.
  1550. *
  1551. * @param {NodeBuilder} builder - The current node builder.
  1552. * @return {string} The node type.
  1553. */
  1554. getNodeType( builder ) {
  1555. return this.node.getElementType( builder );
  1556. }
  1557. generate( builder ) {
  1558. const indexType = this.indexNode.getNodeType( builder );
  1559. const nodeSnippet = this.node.build( builder );
  1560. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1561. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1562. }
  1563. }
  1564. /**
  1565. * This module is part of the TSL core and usually not used in app level code.
  1566. * It represents a convert operation during the shader generation process
  1567. * meaning it converts the data type of a node to a target data type.
  1568. *
  1569. * @augments Node
  1570. */
  1571. class ConvertNode extends Node {
  1572. static get type() {
  1573. return 'ConvertNode';
  1574. }
  1575. /**
  1576. * Constructs a new convert node.
  1577. *
  1578. * @param {Node} node - The node which type should be converted.
  1579. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1580. */
  1581. constructor( node, convertTo ) {
  1582. super();
  1583. /**
  1584. * The node which type should be converted.
  1585. *
  1586. * @type {Node}
  1587. */
  1588. this.node = node;
  1589. /**
  1590. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1591. *
  1592. * @type {string}
  1593. */
  1594. this.convertTo = convertTo;
  1595. }
  1596. /**
  1597. * This method is overwritten since the implementation tries to infer the best
  1598. * matching type from the {@link ConvertNode#convertTo} property.
  1599. *
  1600. * @param {NodeBuilder} builder - The current node builder.
  1601. * @return {string} The node type.
  1602. */
  1603. getNodeType( builder ) {
  1604. const requestType = this.node.getNodeType( builder );
  1605. let convertTo = null;
  1606. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1607. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1608. convertTo = overloadingType;
  1609. }
  1610. }
  1611. return convertTo;
  1612. }
  1613. serialize( data ) {
  1614. super.serialize( data );
  1615. data.convertTo = this.convertTo;
  1616. }
  1617. deserialize( data ) {
  1618. super.deserialize( data );
  1619. this.convertTo = data.convertTo;
  1620. }
  1621. generate( builder, output ) {
  1622. const node = this.node;
  1623. const type = this.getNodeType( builder );
  1624. const snippet = node.build( builder, type );
  1625. return builder.format( snippet, type, output );
  1626. }
  1627. }
  1628. /**
  1629. * This module uses cache management to create temporary variables
  1630. * if the node is used more than once to prevent duplicate calculations.
  1631. *
  1632. * The class acts as a base class for many other nodes types.
  1633. *
  1634. * @augments Node
  1635. */
  1636. class TempNode extends Node {
  1637. static get type() {
  1638. return 'TempNode';
  1639. }
  1640. /**
  1641. * Constructs a temp node.
  1642. *
  1643. * @param {?string} nodeType - The node type.
  1644. */
  1645. constructor( nodeType = null ) {
  1646. super( nodeType );
  1647. /**
  1648. * This flag can be used for type testing.
  1649. *
  1650. * @type {boolean}
  1651. * @readonly
  1652. * @default true
  1653. */
  1654. this.isTempNode = true;
  1655. }
  1656. /**
  1657. * Whether this node is used more than once in context of other nodes.
  1658. *
  1659. * @param {NodeBuilder} builder - The node builder.
  1660. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1661. */
  1662. hasDependencies( builder ) {
  1663. return builder.getDataFromNode( this ).usageCount > 1;
  1664. }
  1665. build( builder, output ) {
  1666. const buildStage = builder.getBuildStage();
  1667. if ( buildStage === 'generate' ) {
  1668. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1669. const nodeData = builder.getDataFromNode( this );
  1670. if ( nodeData.propertyName !== undefined ) {
  1671. return builder.format( nodeData.propertyName, type, output );
  1672. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1673. const snippet = super.build( builder, type );
  1674. const nodeVar = builder.getVarFromNode( this, null, type );
  1675. const propertyName = builder.getPropertyName( nodeVar );
  1676. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1677. nodeData.snippet = snippet;
  1678. nodeData.propertyName = propertyName;
  1679. return builder.format( nodeData.propertyName, type, output );
  1680. }
  1681. }
  1682. return super.build( builder, output );
  1683. }
  1684. }
  1685. /**
  1686. * This module is part of the TSL core and usually not used in app level code.
  1687. * It represents a join operation during the shader generation process.
  1688. * For example in can compose/join two single floats into a `vec2` type.
  1689. *
  1690. * @augments TempNode
  1691. */
  1692. class JoinNode extends TempNode {
  1693. static get type() {
  1694. return 'JoinNode';
  1695. }
  1696. /**
  1697. * Constructs a new join node.
  1698. *
  1699. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1700. * @param {?string} [nodeType=null] - The node type.
  1701. */
  1702. constructor( nodes = [], nodeType = null ) {
  1703. super( nodeType );
  1704. /**
  1705. * An array of nodes that should be joined.
  1706. *
  1707. * @type {Array<Node>}
  1708. */
  1709. this.nodes = nodes;
  1710. }
  1711. /**
  1712. * This method is overwritten since the node type must be inferred from the
  1713. * joined data length if not explicitly defined.
  1714. *
  1715. * @param {NodeBuilder} builder - The current node builder.
  1716. * @return {string} The node type.
  1717. */
  1718. getNodeType( builder ) {
  1719. if ( this.nodeType !== null ) {
  1720. return builder.getVectorType( this.nodeType );
  1721. }
  1722. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1723. }
  1724. generate( builder, output ) {
  1725. const type = this.getNodeType( builder );
  1726. const maxLength = builder.getTypeLength( type );
  1727. const nodes = this.nodes;
  1728. const primitiveType = builder.getComponentType( type );
  1729. const snippetValues = [];
  1730. let length = 0;
  1731. for ( const input of nodes ) {
  1732. if ( length >= maxLength ) {
  1733. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1734. break;
  1735. }
  1736. let inputType = input.getNodeType( builder );
  1737. let inputTypeLength = builder.getTypeLength( inputType );
  1738. let inputSnippet;
  1739. if ( length + inputTypeLength > maxLength ) {
  1740. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1741. inputTypeLength = maxLength - length;
  1742. inputType = builder.getTypeFromLength( inputTypeLength );
  1743. }
  1744. length += inputTypeLength;
  1745. inputSnippet = input.build( builder, inputType );
  1746. const inputPrimitiveType = builder.getComponentType( inputType );
  1747. if ( inputPrimitiveType !== primitiveType ) {
  1748. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1749. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1750. }
  1751. snippetValues.push( inputSnippet );
  1752. }
  1753. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1754. return builder.format( snippet, type, output );
  1755. }
  1756. }
  1757. const _stringVectorComponents = vectorComponents.join( '' );
  1758. /**
  1759. * This module is part of the TSL core and usually not used in app level code.
  1760. * `SplitNode` represents a property access operation which means it is
  1761. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1762. * For example:
  1763. * ```js
  1764. * const redValue = color.r;
  1765. * ```
  1766. *
  1767. * @augments Node
  1768. */
  1769. class SplitNode extends Node {
  1770. static get type() {
  1771. return 'SplitNode';
  1772. }
  1773. /**
  1774. * Constructs a new split node.
  1775. *
  1776. * @param {Node} node - The node that should be accessed.
  1777. * @param {string} [components='x'] - The components that should be accessed.
  1778. */
  1779. constructor( node, components = 'x' ) {
  1780. super();
  1781. /**
  1782. * The node that should be accessed.
  1783. *
  1784. * @type {Node}
  1785. */
  1786. this.node = node;
  1787. /**
  1788. * The components that should be accessed.
  1789. *
  1790. * @type {string}
  1791. */
  1792. this.components = components;
  1793. /**
  1794. * This flag can be used for type testing.
  1795. *
  1796. * @type {boolean}
  1797. * @readonly
  1798. * @default true
  1799. */
  1800. this.isSplitNode = true;
  1801. }
  1802. /**
  1803. * Returns the vector length which is computed based on the requested components.
  1804. *
  1805. * @return {number} The vector length.
  1806. */
  1807. getVectorLength() {
  1808. let vectorLength = this.components.length;
  1809. for ( const c of this.components ) {
  1810. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1811. }
  1812. return vectorLength;
  1813. }
  1814. /**
  1815. * Returns the component type of the node's type.
  1816. *
  1817. * @param {NodeBuilder} builder - The current node builder.
  1818. * @return {string} The component type.
  1819. */
  1820. getComponentType( builder ) {
  1821. return builder.getComponentType( this.node.getNodeType( builder ) );
  1822. }
  1823. /**
  1824. * This method is overwritten since the node type is inferred from requested components.
  1825. *
  1826. * @param {NodeBuilder} builder - The current node builder.
  1827. * @return {string} The node type.
  1828. */
  1829. getNodeType( builder ) {
  1830. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1831. }
  1832. /**
  1833. * Returns the scope of the node.
  1834. *
  1835. * @return {Node} The scope of the node.
  1836. */
  1837. getScope() {
  1838. return this.node.getScope();
  1839. }
  1840. generate( builder, output ) {
  1841. const node = this.node;
  1842. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1843. let snippet = null;
  1844. if ( nodeTypeLength > 1 ) {
  1845. let type = null;
  1846. const componentsLength = this.getVectorLength();
  1847. if ( componentsLength >= nodeTypeLength ) {
  1848. // needed expand the input node
  1849. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1850. }
  1851. const nodeSnippet = node.build( builder, type );
  1852. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1853. // unnecessary swizzle
  1854. snippet = builder.format( nodeSnippet, type, output );
  1855. } else {
  1856. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1857. }
  1858. } else {
  1859. // ignore .components if .node returns float/integer
  1860. snippet = node.build( builder, output );
  1861. }
  1862. return snippet;
  1863. }
  1864. serialize( data ) {
  1865. super.serialize( data );
  1866. data.components = this.components;
  1867. }
  1868. deserialize( data ) {
  1869. super.deserialize( data );
  1870. this.components = data.components;
  1871. }
  1872. }
  1873. /**
  1874. * This module is part of the TSL core and usually not used in app level code.
  1875. * `SetNode` represents a set operation which means it is used to implement any
  1876. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1877. * For example:
  1878. * ```js
  1879. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1880. * ```
  1881. *
  1882. * @augments TempNode
  1883. */
  1884. class SetNode extends TempNode {
  1885. static get type() {
  1886. return 'SetNode';
  1887. }
  1888. /**
  1889. * Constructs a new set node.
  1890. *
  1891. * @param {Node} sourceNode - The node that should be updated.
  1892. * @param {string} components - The components that should be updated.
  1893. * @param {Node} targetNode - The value node.
  1894. */
  1895. constructor( sourceNode, components, targetNode ) {
  1896. super();
  1897. /**
  1898. * The node that should be updated.
  1899. *
  1900. * @type {Node}
  1901. */
  1902. this.sourceNode = sourceNode;
  1903. /**
  1904. * The components that should be updated.
  1905. *
  1906. * @type {string}
  1907. */
  1908. this.components = components;
  1909. /**
  1910. * The value node.
  1911. *
  1912. * @type {Node}
  1913. */
  1914. this.targetNode = targetNode;
  1915. }
  1916. /**
  1917. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1918. *
  1919. * @param {NodeBuilder} builder - The current node builder.
  1920. * @return {string} The node type.
  1921. */
  1922. getNodeType( builder ) {
  1923. return this.sourceNode.getNodeType( builder );
  1924. }
  1925. generate( builder ) {
  1926. const { sourceNode, components, targetNode } = this;
  1927. const sourceType = this.getNodeType( builder );
  1928. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1929. const targetType = builder.getTypeFromLength( components.length, componentType );
  1930. const targetSnippet = targetNode.build( builder, targetType );
  1931. const sourceSnippet = sourceNode.build( builder, sourceType );
  1932. const length = builder.getTypeLength( sourceType );
  1933. const snippetValues = [];
  1934. for ( let i = 0; i < length; i ++ ) {
  1935. const component = vectorComponents[ i ];
  1936. if ( component === components[ 0 ] ) {
  1937. snippetValues.push( targetSnippet );
  1938. i += components.length - 1;
  1939. } else {
  1940. snippetValues.push( sourceSnippet + '.' + component );
  1941. }
  1942. }
  1943. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1944. }
  1945. }
  1946. /**
  1947. * This module is part of the TSL core and usually not used in app level code.
  1948. * It represents a flip operation during the shader generation process
  1949. * meaning it flips normalized values with the following formula:
  1950. * ```
  1951. * x = 1 - x;
  1952. * ```
  1953. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1954. * `flipSTPQ()` method invocations on node objects. For example:
  1955. * ```js
  1956. * uvNode = uvNode.flipY();
  1957. * ```
  1958. *
  1959. * @augments TempNode
  1960. */
  1961. class FlipNode extends TempNode {
  1962. static get type() {
  1963. return 'FlipNode';
  1964. }
  1965. /**
  1966. * Constructs a new flip node.
  1967. *
  1968. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1969. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1970. */
  1971. constructor( sourceNode, components ) {
  1972. super();
  1973. /**
  1974. * The node which component(s) should be flipped.
  1975. *
  1976. * @type {Node}
  1977. */
  1978. this.sourceNode = sourceNode;
  1979. /**
  1980. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1981. *
  1982. * @type {string}
  1983. */
  1984. this.components = components;
  1985. }
  1986. /**
  1987. * This method is overwritten since the node type is inferred from the source node.
  1988. *
  1989. * @param {NodeBuilder} builder - The current node builder.
  1990. * @return {string} The node type.
  1991. */
  1992. getNodeType( builder ) {
  1993. return this.sourceNode.getNodeType( builder );
  1994. }
  1995. generate( builder ) {
  1996. const { components, sourceNode } = this;
  1997. const sourceType = this.getNodeType( builder );
  1998. const sourceSnippet = sourceNode.build( builder );
  1999. const sourceCache = builder.getVarFromNode( this );
  2000. const sourceProperty = builder.getPropertyName( sourceCache );
  2001. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2002. const length = builder.getTypeLength( sourceType );
  2003. const snippetValues = [];
  2004. let componentIndex = 0;
  2005. for ( let i = 0; i < length; i ++ ) {
  2006. const component = vectorComponents[ i ];
  2007. if ( component === components[ componentIndex ] ) {
  2008. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2009. componentIndex ++;
  2010. } else {
  2011. snippetValues.push( sourceProperty + '.' + component );
  2012. }
  2013. }
  2014. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2015. }
  2016. }
  2017. /**
  2018. * Base class for representing data input nodes.
  2019. *
  2020. * @augments Node
  2021. */
  2022. class InputNode extends Node {
  2023. static get type() {
  2024. return 'InputNode';
  2025. }
  2026. /**
  2027. * Constructs a new input node.
  2028. *
  2029. * @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).
  2030. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2031. */
  2032. constructor( value, nodeType = null ) {
  2033. super( nodeType );
  2034. /**
  2035. * This flag can be used for type testing.
  2036. *
  2037. * @type {boolean}
  2038. * @readonly
  2039. * @default true
  2040. */
  2041. this.isInputNode = true;
  2042. /**
  2043. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2044. *
  2045. * @type {any}
  2046. */
  2047. this.value = value;
  2048. /**
  2049. * The precision of the value in the shader.
  2050. *
  2051. * @type {?('low'|'medium'|'high')}
  2052. * @default null
  2053. */
  2054. this.precision = null;
  2055. }
  2056. getNodeType( /*builder*/ ) {
  2057. if ( this.nodeType === null ) {
  2058. return getValueType( this.value );
  2059. }
  2060. return this.nodeType;
  2061. }
  2062. /**
  2063. * Returns the input type of the node which is by default the node type. Derived modules
  2064. * might overwrite this method and use a fixed type or compute one analytically.
  2065. *
  2066. * A typical example for different input and node types are textures. The input type of a
  2067. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2068. *
  2069. * @param {NodeBuilder} builder - The current node builder.
  2070. * @return {string} The input type.
  2071. */
  2072. getInputType( builder ) {
  2073. return this.getNodeType( builder );
  2074. }
  2075. /**
  2076. * Sets the precision to the given value. The method can be
  2077. * overwritten in derived classes if the final precision must be computed
  2078. * analytically.
  2079. *
  2080. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2081. * @return {InputNode} A reference to this node.
  2082. */
  2083. setPrecision( precision ) {
  2084. this.precision = precision;
  2085. return this;
  2086. }
  2087. serialize( data ) {
  2088. super.serialize( data );
  2089. data.value = this.value;
  2090. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2091. data.valueType = getValueType( this.value );
  2092. data.nodeType = this.nodeType;
  2093. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2094. data.precision = this.precision;
  2095. }
  2096. deserialize( data ) {
  2097. super.deserialize( data );
  2098. this.nodeType = data.nodeType;
  2099. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2100. this.precision = data.precision || null;
  2101. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2102. }
  2103. generate( /*builder, output*/ ) {
  2104. warn( 'Abstract function.' );
  2105. }
  2106. }
  2107. const _regNum = /float|u?int/;
  2108. /**
  2109. * Class for representing a constant value in the shader.
  2110. *
  2111. * @augments InputNode
  2112. */
  2113. class ConstNode extends InputNode {
  2114. static get type() {
  2115. return 'ConstNode';
  2116. }
  2117. /**
  2118. * Constructs a new input node.
  2119. *
  2120. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2121. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2122. */
  2123. constructor( value, nodeType = null ) {
  2124. super( value, nodeType );
  2125. /**
  2126. * This flag can be used for type testing.
  2127. *
  2128. * @type {boolean}
  2129. * @readonly
  2130. * @default true
  2131. */
  2132. this.isConstNode = true;
  2133. }
  2134. /**
  2135. * Generates the shader string of the value with the current node builder.
  2136. *
  2137. * @param {NodeBuilder} builder - The current node builder.
  2138. * @return {string} The generated value as a shader string.
  2139. */
  2140. generateConst( builder ) {
  2141. return builder.generateConst( this.getNodeType( builder ), this.value );
  2142. }
  2143. generate( builder, output ) {
  2144. const type = this.getNodeType( builder );
  2145. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2146. return builder.generateConst( output, this.value );
  2147. }
  2148. return builder.format( this.generateConst( builder ), type, output );
  2149. }
  2150. }
  2151. /**
  2152. * Base class for representing member access on an object-like
  2153. * node data structures.
  2154. *
  2155. * @augments Node
  2156. */
  2157. class MemberNode extends Node {
  2158. static get type() {
  2159. return 'MemberNode';
  2160. }
  2161. /**
  2162. * Constructs a member node.
  2163. *
  2164. * @param {Node} structNode - The struct node.
  2165. * @param {string} property - The property name.
  2166. */
  2167. constructor( structNode, property ) {
  2168. super();
  2169. /**
  2170. * The struct node.
  2171. *
  2172. * @type {Node}
  2173. */
  2174. this.structNode = structNode;
  2175. /**
  2176. * The property name.
  2177. *
  2178. * @type {Node}
  2179. */
  2180. this.property = property;
  2181. /**
  2182. * This flag can be used for type testing.
  2183. *
  2184. * @type {boolean}
  2185. * @readonly
  2186. * @default true
  2187. */
  2188. this.isMemberNode = true;
  2189. }
  2190. hasMember( builder ) {
  2191. if ( this.structNode.isMemberNode ) {
  2192. if ( this.structNode.hasMember( builder ) === false ) {
  2193. return false;
  2194. }
  2195. }
  2196. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2197. }
  2198. getNodeType( builder ) {
  2199. if ( this.hasMember( builder ) === false ) {
  2200. // default type if member does not exist
  2201. return 'float';
  2202. }
  2203. return this.structNode.getMemberType( builder, this.property );
  2204. }
  2205. getMemberType( builder, name ) {
  2206. if ( this.hasMember( builder ) === false ) {
  2207. // default type if member does not exist
  2208. return 'float';
  2209. }
  2210. const type = this.getNodeType( builder );
  2211. const struct = builder.getStructTypeNode( type );
  2212. return struct.getMemberType( builder, name );
  2213. }
  2214. generate( builder ) {
  2215. if ( this.hasMember( builder ) === false ) {
  2216. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2217. const type = this.getNodeType( builder );
  2218. return builder.generateConst( type );
  2219. }
  2220. const propertyName = this.structNode.build( builder );
  2221. return propertyName + '.' + this.property;
  2222. }
  2223. }
  2224. let currentStack = null;
  2225. const NodeElements = new Map();
  2226. // Extend Node Class for TSL using prototype
  2227. function addMethodChaining( name, nodeElement ) {
  2228. if ( NodeElements.has( name ) ) {
  2229. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2230. return;
  2231. }
  2232. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2233. NodeElements.set( name, nodeElement );
  2234. if ( name !== 'assign' ) {
  2235. // Changing Node prototype to add method chaining
  2236. Node.prototype[ name ] = function ( ...params ) {
  2237. //if ( name === 'toVarIntent' ) return this;
  2238. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2239. };
  2240. // Adding assign method chaining
  2241. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2242. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2243. };
  2244. }
  2245. }
  2246. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2247. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2248. Node.prototype.assign = function ( ...params ) {
  2249. if ( this.isStackNode !== true ) {
  2250. if ( currentStack !== null ) {
  2251. currentStack.assign( this, ...params );
  2252. } else {
  2253. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2254. }
  2255. return this;
  2256. } else {
  2257. const nodeElement = NodeElements.get( 'assign' );
  2258. return this.addToStack( nodeElement( ...params ) );
  2259. }
  2260. };
  2261. Node.prototype.toVarIntent = function () {
  2262. return this;
  2263. };
  2264. Node.prototype.get = function ( value ) {
  2265. return new MemberNode( this, value );
  2266. };
  2267. // Cache prototype for TSL
  2268. const proto = {};
  2269. // Set swizzle properties for xyzw, rgba, and stpq.
  2270. function setProtoSwizzle( property, altA, altB ) {
  2271. // swizzle properties
  2272. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2273. get() {
  2274. this._cache = this._cache || {};
  2275. //
  2276. let split = this._cache[ property ];
  2277. if ( split === undefined ) {
  2278. split = new SplitNode( this, property );
  2279. this._cache[ property ] = split;
  2280. }
  2281. return split;
  2282. },
  2283. set( value ) {
  2284. this[ property ].assign( nodeObject( value ) );
  2285. }
  2286. };
  2287. // set properties ( swizzle ) and sort to xyzw sequence
  2288. const propUpper = property.toUpperCase();
  2289. const altAUpper = altA.toUpperCase();
  2290. const altBUpper = altB.toUpperCase();
  2291. // Set methods for swizzle properties
  2292. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2293. const swizzle = parseSwizzleAndSort( property );
  2294. return new SetNode( this, swizzle, nodeObject( value ) );
  2295. };
  2296. // Set methods for flip properties
  2297. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2298. const swizzle = parseSwizzleAndSort( property );
  2299. return new FlipNode( this, swizzle );
  2300. };
  2301. }
  2302. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2303. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2304. const swizzleC = [ 's', 't', 'p', 'q' ];
  2305. for ( let a = 0; a < 4; a ++ ) {
  2306. let prop = swizzleA[ a ];
  2307. let altA = swizzleB[ a ];
  2308. let altB = swizzleC[ a ];
  2309. setProtoSwizzle( prop, altA, altB );
  2310. for ( let b = 0; b < 4; b ++ ) {
  2311. prop = swizzleA[ a ] + swizzleA[ b ];
  2312. altA = swizzleB[ a ] + swizzleB[ b ];
  2313. altB = swizzleC[ a ] + swizzleC[ b ];
  2314. setProtoSwizzle( prop, altA, altB );
  2315. for ( let c = 0; c < 4; c ++ ) {
  2316. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2317. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2318. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2319. setProtoSwizzle( prop, altA, altB );
  2320. for ( let d = 0; d < 4; d ++ ) {
  2321. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2322. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2323. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2324. setProtoSwizzle( prop, altA, altB );
  2325. }
  2326. }
  2327. }
  2328. }
  2329. // Set/get static properties for array elements (0-31).
  2330. for ( let i = 0; i < 32; i ++ ) {
  2331. proto[ i ] = {
  2332. get() {
  2333. this._cache = this._cache || {};
  2334. //
  2335. let element = this._cache[ i ];
  2336. if ( element === undefined ) {
  2337. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2338. this._cache[ i ] = element;
  2339. }
  2340. return element;
  2341. },
  2342. set( value ) {
  2343. this[ i ].assign( nodeObject( value ) );
  2344. }
  2345. };
  2346. }
  2347. /*
  2348. // Set properties for width, height, and depth.
  2349. function setProtoProperty( property, target ) {
  2350. proto[ property ] = {
  2351. get() {
  2352. this._cache = this._cache || {};
  2353. //
  2354. let split = this._cache[ target ];
  2355. if ( split === undefined ) {
  2356. split = new SplitNode( this, target );
  2357. this._cache[ target ] = split;
  2358. }
  2359. return split;
  2360. },
  2361. set( value ) {
  2362. this[ target ].assign( nodeObject( value ) );
  2363. }
  2364. };
  2365. }
  2366. setProtoProperty( 'width', 'x' );
  2367. setProtoProperty( 'height', 'y' );
  2368. setProtoProperty( 'depth', 'z' );
  2369. */
  2370. Object.defineProperties( Node.prototype, proto );
  2371. // --- FINISH ---
  2372. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2373. const ShaderNodeObject = function ( obj, altType = null ) {
  2374. const type = getValueType( obj );
  2375. if ( type === 'node' ) {
  2376. return obj;
  2377. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2378. return nodeObject( getConstNode( obj, altType ) );
  2379. } else if ( type === 'shader' ) {
  2380. return obj.isFn ? obj : Fn( obj );
  2381. }
  2382. return obj;
  2383. };
  2384. const ShaderNodeObjects = function ( objects, altType = null ) {
  2385. for ( const name in objects ) {
  2386. objects[ name ] = nodeObject( objects[ name ], altType );
  2387. }
  2388. return objects;
  2389. };
  2390. const ShaderNodeArray = function ( array, altType = null ) {
  2391. const len = array.length;
  2392. for ( let i = 0; i < len; i ++ ) {
  2393. array[ i ] = nodeObject( array[ i ], altType );
  2394. }
  2395. return array;
  2396. };
  2397. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2398. function assignNode( node ) {
  2399. if ( settings !== null ) {
  2400. node = nodeObject( Object.assign( node, settings ) );
  2401. if ( settings.intent === true ) {
  2402. node = node.toVarIntent();
  2403. }
  2404. } else {
  2405. node = nodeObject( node );
  2406. }
  2407. return node;
  2408. }
  2409. let fn, name = scope, minParams, maxParams;
  2410. function verifyParamsLimit( params ) {
  2411. let tslName;
  2412. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2413. else tslName = NodeClass.type;
  2414. if ( minParams !== undefined && params.length < minParams ) {
  2415. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2416. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2417. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2418. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2419. return params.slice( 0, maxParams );
  2420. }
  2421. return params;
  2422. }
  2423. if ( scope === null ) {
  2424. fn = ( ...params ) => {
  2425. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2426. };
  2427. } else if ( factor !== null ) {
  2428. factor = nodeObject( factor );
  2429. fn = ( ...params ) => {
  2430. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2431. };
  2432. } else {
  2433. fn = ( ...params ) => {
  2434. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2435. };
  2436. }
  2437. fn.setParameterLength = ( ...params ) => {
  2438. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2439. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2440. return fn;
  2441. };
  2442. fn.setName = ( value ) => {
  2443. name = value;
  2444. return fn;
  2445. };
  2446. return fn;
  2447. };
  2448. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2449. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2450. };
  2451. class ShaderCallNodeInternal extends Node {
  2452. constructor( shaderNode, rawInputs ) {
  2453. super();
  2454. this.shaderNode = shaderNode;
  2455. this.rawInputs = rawInputs;
  2456. this.isShaderCallNodeInternal = true;
  2457. }
  2458. getNodeType( builder ) {
  2459. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2460. }
  2461. getMemberType( builder, name ) {
  2462. return this.getOutputNode( builder ).getMemberType( builder, name );
  2463. }
  2464. call( builder ) {
  2465. const { shaderNode, rawInputs } = this;
  2466. const properties = builder.getNodeProperties( shaderNode );
  2467. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2468. const subBuildProperty = subBuild || 'default';
  2469. if ( properties[ subBuildProperty ] ) {
  2470. return properties[ subBuildProperty ];
  2471. }
  2472. //
  2473. const previousSubBuildFn = builder.subBuildFn;
  2474. const previousFnCall = builder.fnCall;
  2475. builder.subBuildFn = subBuild;
  2476. builder.fnCall = this;
  2477. let result = null;
  2478. if ( shaderNode.layout ) {
  2479. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2480. if ( functionNodesCacheMap === undefined ) {
  2481. functionNodesCacheMap = new WeakMap();
  2482. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2483. }
  2484. let functionNode = functionNodesCacheMap.get( shaderNode );
  2485. if ( functionNode === undefined ) {
  2486. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2487. functionNodesCacheMap.set( shaderNode, functionNode );
  2488. }
  2489. builder.addInclude( functionNode );
  2490. //
  2491. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2492. result = nodeObject( functionNode.call( inputs ) );
  2493. } else {
  2494. const secureNodeBuilder = new Proxy( builder, {
  2495. get: ( target, property, receiver ) => {
  2496. let value;
  2497. if ( Symbol.iterator === property ) {
  2498. value = function* () {
  2499. yield undefined;
  2500. };
  2501. } else {
  2502. value = Reflect.get( target, property, receiver );
  2503. }
  2504. return value;
  2505. }
  2506. } );
  2507. //
  2508. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2509. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2510. const jsFunc = shaderNode.jsFunc;
  2511. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2512. result = nodeObject( outputNode );
  2513. }
  2514. builder.subBuildFn = previousSubBuildFn;
  2515. builder.fnCall = previousFnCall;
  2516. if ( shaderNode.once ) {
  2517. properties[ subBuildProperty ] = result;
  2518. }
  2519. return result;
  2520. }
  2521. setupOutput( builder ) {
  2522. builder.addStack();
  2523. builder.stack.outputNode = this.call( builder );
  2524. return builder.removeStack();
  2525. }
  2526. getOutputNode( builder ) {
  2527. const properties = builder.getNodeProperties( this );
  2528. const subBuildOutput = builder.getSubBuildOutput( this );
  2529. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2530. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2531. return properties[ subBuildOutput ];
  2532. }
  2533. build( builder, output = null ) {
  2534. let result = null;
  2535. const buildStage = builder.getBuildStage();
  2536. const properties = builder.getNodeProperties( this );
  2537. const subBuildOutput = builder.getSubBuildOutput( this );
  2538. const outputNode = this.getOutputNode( builder );
  2539. const previousFnCall = builder.fnCall;
  2540. builder.fnCall = this;
  2541. if ( buildStage === 'setup' ) {
  2542. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2543. if ( properties[ subBuildInitialized ] !== true ) {
  2544. properties[ subBuildInitialized ] = true;
  2545. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2546. properties[ subBuildOutput ].build( builder );
  2547. // If the shaderNode has subBuilds, add them to the chaining nodes
  2548. // so they can be built later in the build process.
  2549. if ( this.shaderNode.subBuilds ) {
  2550. for ( const node of builder.chaining ) {
  2551. const nodeData = builder.getDataFromNode( node, 'any' );
  2552. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2553. for ( const subBuild of this.shaderNode.subBuilds ) {
  2554. nodeData.subBuilds.add( subBuild );
  2555. }
  2556. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2557. }
  2558. }
  2559. }
  2560. result = properties[ subBuildOutput ];
  2561. } else if ( buildStage === 'analyze' ) {
  2562. outputNode.build( builder, output );
  2563. } else if ( buildStage === 'generate' ) {
  2564. result = outputNode.build( builder, output ) || '';
  2565. }
  2566. builder.fnCall = previousFnCall;
  2567. return result;
  2568. }
  2569. }
  2570. function getLayoutParameters( params ) {
  2571. let output;
  2572. nodeObjects( params );
  2573. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2574. if ( isArrayAsParameter ) {
  2575. output = [ ...params ];
  2576. } else {
  2577. output = params[ 0 ];
  2578. }
  2579. return output;
  2580. }
  2581. function getProxyParameters( params ) {
  2582. let index = 0;
  2583. nodeObjects( params );
  2584. return new Proxy( params, {
  2585. get: ( target, property, receiver ) => {
  2586. let value;
  2587. if ( property === 'length' ) {
  2588. value = params.length;
  2589. return value;
  2590. }
  2591. if ( Symbol.iterator === property ) {
  2592. value = function* () {
  2593. for ( const inputNode of params ) {
  2594. yield nodeObject( inputNode );
  2595. }
  2596. };
  2597. } else {
  2598. if ( params.length > 0 ) {
  2599. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2600. const objectTarget = params[ 0 ];
  2601. if ( objectTarget[ property ] === undefined ) {
  2602. value = objectTarget[ index ++ ];
  2603. } else {
  2604. value = Reflect.get( objectTarget, property, receiver );
  2605. }
  2606. } else if ( params[ 0 ] instanceof Node ) {
  2607. if ( params[ property ] === undefined ) {
  2608. value = params[ index ++ ];
  2609. } else {
  2610. value = Reflect.get( params, property, receiver );
  2611. }
  2612. }
  2613. } else {
  2614. value = Reflect.get( target, property, receiver );
  2615. }
  2616. value = nodeObject( value );
  2617. }
  2618. return value;
  2619. }
  2620. } );
  2621. }
  2622. class ShaderNodeInternal extends Node {
  2623. constructor( jsFunc, nodeType ) {
  2624. super( nodeType );
  2625. this.jsFunc = jsFunc;
  2626. this.layout = null;
  2627. this.global = true;
  2628. this.once = false;
  2629. }
  2630. setLayout( layout ) {
  2631. this.layout = layout;
  2632. return this;
  2633. }
  2634. getLayout() {
  2635. return this.layout;
  2636. }
  2637. call( rawInputs = null ) {
  2638. return new ShaderCallNodeInternal( this, rawInputs );
  2639. }
  2640. setup() {
  2641. return this.call();
  2642. }
  2643. }
  2644. const bools = [ false, true ];
  2645. const uints = [ 0, 1, 2, 3 ];
  2646. const ints = [ -1, -2 ];
  2647. 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 ];
  2648. const boolsCacheMap = new Map();
  2649. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2650. const uintsCacheMap = new Map();
  2651. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2652. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2653. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2654. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2655. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2656. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2657. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2658. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2659. const getConstNode = ( value, type ) => {
  2660. if ( constNodesCacheMap.has( value ) ) {
  2661. return constNodesCacheMap.get( value );
  2662. } else if ( value.isNode === true ) {
  2663. return value;
  2664. } else {
  2665. return new ConstNode( value, type );
  2666. }
  2667. };
  2668. const ConvertType = function ( type, cacheMap = null ) {
  2669. return ( ...params ) => {
  2670. for ( const param of params ) {
  2671. if ( param === undefined ) {
  2672. error( `TSL: Invalid parameter for the type "${ type }".` );
  2673. return nodeObject( new ConstNode( 0, type ) );
  2674. }
  2675. }
  2676. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2677. const paramType = typeof param;
  2678. return paramType !== 'object' && paramType !== 'function';
  2679. } ) ) ) {
  2680. params = [ getValueFromType( type, ...params ) ];
  2681. }
  2682. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2683. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2684. }
  2685. if ( params.length === 1 ) {
  2686. const node = getConstNode( params[ 0 ], type );
  2687. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2688. return nodeObjectIntent( new ConvertNode( node, type ) );
  2689. }
  2690. const nodes = params.map( param => getConstNode( param ) );
  2691. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2692. };
  2693. };
  2694. // exports
  2695. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2696. // utils
  2697. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2698. // shader node base
  2699. function ShaderNode( jsFunc, nodeType ) {
  2700. return new ShaderNodeInternal( jsFunc, nodeType );
  2701. }
  2702. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2703. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2704. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2705. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2706. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2707. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2708. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2709. let fnId = 0;
  2710. class FnNode extends Node {
  2711. constructor( jsFunc, layout = null ) {
  2712. super();
  2713. let nodeType = null;
  2714. if ( layout !== null ) {
  2715. if ( typeof layout === 'object' ) {
  2716. nodeType = layout.return;
  2717. } else {
  2718. if ( typeof layout === 'string' ) {
  2719. nodeType = layout;
  2720. } else {
  2721. error( 'TSL: Invalid layout type.' );
  2722. }
  2723. layout = null;
  2724. }
  2725. }
  2726. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2727. if ( layout !== null ) {
  2728. this.setLayout( layout );
  2729. }
  2730. this.isFn = true;
  2731. }
  2732. setLayout( layout ) {
  2733. const nodeType = this.shaderNode.nodeType;
  2734. if ( typeof layout.inputs !== 'object' ) {
  2735. const fullLayout = {
  2736. name: 'fn' + fnId ++,
  2737. type: nodeType,
  2738. inputs: []
  2739. };
  2740. for ( const name in layout ) {
  2741. if ( name === 'return' ) continue;
  2742. fullLayout.inputs.push( {
  2743. name: name,
  2744. type: layout[ name ]
  2745. } );
  2746. }
  2747. layout = fullLayout;
  2748. }
  2749. this.shaderNode.setLayout( layout );
  2750. return this;
  2751. }
  2752. getNodeType( builder ) {
  2753. return this.shaderNode.getNodeType( builder ) || 'float';
  2754. }
  2755. call( ...params ) {
  2756. const fnCall = this.shaderNode.call( params );
  2757. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2758. return fnCall.toVarIntent();
  2759. }
  2760. once( subBuilds = null ) {
  2761. this.shaderNode.once = true;
  2762. this.shaderNode.subBuilds = subBuilds;
  2763. return this;
  2764. }
  2765. generate( builder ) {
  2766. const type = this.getNodeType( builder );
  2767. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2768. return builder.generateConst( type );
  2769. }
  2770. }
  2771. function Fn( jsFunc, layout = null ) {
  2772. const instance = new FnNode( jsFunc, layout );
  2773. return new Proxy( () => {}, {
  2774. apply( target, thisArg, params ) {
  2775. return instance.call( ...params );
  2776. },
  2777. get( target, prop, receiver ) {
  2778. return Reflect.get( instance, prop, receiver );
  2779. },
  2780. set( target, prop, value, receiver ) {
  2781. return Reflect.set( instance, prop, value, receiver );
  2782. }
  2783. } );
  2784. }
  2785. //
  2786. const setCurrentStack = ( stack ) => {
  2787. currentStack = stack;
  2788. };
  2789. const getCurrentStack = () => currentStack;
  2790. /**
  2791. * Represent a conditional node using if/else statements.
  2792. *
  2793. * ```js
  2794. * If( condition, function )
  2795. * .ElseIf( condition, function )
  2796. * .Else( function )
  2797. * ```
  2798. * @tsl
  2799. * @function
  2800. * @param {...any} params - The parameters for the conditional node.
  2801. * @returns {StackNode} The conditional node.
  2802. */
  2803. const If = ( ...params ) => currentStack.If( ...params );
  2804. /**
  2805. * Represent a conditional node using switch/case statements.
  2806. *
  2807. * ```js
  2808. * Switch( value )
  2809. * .Case( 1, function )
  2810. * .Case( 2, 3, 4, function )
  2811. * .Default( function )
  2812. * ```
  2813. * @tsl
  2814. * @function
  2815. * @param {...any} params - The parameters for the conditional node.
  2816. * @returns {StackNode} The conditional node.
  2817. */
  2818. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2819. /**
  2820. * Add the given node to the current stack.
  2821. *
  2822. * @param {Node} node - The node to add.
  2823. * @returns {Node} The node that was added to the stack.
  2824. */
  2825. function Stack( node ) {
  2826. if ( currentStack ) currentStack.addToStack( node );
  2827. return node;
  2828. }
  2829. addMethodChaining( 'toStack', Stack );
  2830. // types
  2831. const color = new ConvertType( 'color' );
  2832. const float = new ConvertType( 'float', cacheMaps.float );
  2833. const int = new ConvertType( 'int', cacheMaps.ints );
  2834. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2835. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2836. const vec2 = new ConvertType( 'vec2' );
  2837. const ivec2 = new ConvertType( 'ivec2' );
  2838. const uvec2 = new ConvertType( 'uvec2' );
  2839. const bvec2 = new ConvertType( 'bvec2' );
  2840. const vec3 = new ConvertType( 'vec3' );
  2841. const ivec3 = new ConvertType( 'ivec3' );
  2842. const uvec3 = new ConvertType( 'uvec3' );
  2843. const bvec3 = new ConvertType( 'bvec3' );
  2844. const vec4 = new ConvertType( 'vec4' );
  2845. const ivec4 = new ConvertType( 'ivec4' );
  2846. const uvec4 = new ConvertType( 'uvec4' );
  2847. const bvec4 = new ConvertType( 'bvec4' );
  2848. const mat2 = new ConvertType( 'mat2' );
  2849. const mat3 = new ConvertType( 'mat3' );
  2850. const mat4 = new ConvertType( 'mat4' );
  2851. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2852. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2853. addMethodChaining( 'toColor', color );
  2854. addMethodChaining( 'toFloat', float );
  2855. addMethodChaining( 'toInt', int );
  2856. addMethodChaining( 'toUint', uint );
  2857. addMethodChaining( 'toBool', bool );
  2858. addMethodChaining( 'toVec2', vec2 );
  2859. addMethodChaining( 'toIVec2', ivec2 );
  2860. addMethodChaining( 'toUVec2', uvec2 );
  2861. addMethodChaining( 'toBVec2', bvec2 );
  2862. addMethodChaining( 'toVec3', vec3 );
  2863. addMethodChaining( 'toIVec3', ivec3 );
  2864. addMethodChaining( 'toUVec3', uvec3 );
  2865. addMethodChaining( 'toBVec3', bvec3 );
  2866. addMethodChaining( 'toVec4', vec4 );
  2867. addMethodChaining( 'toIVec4', ivec4 );
  2868. addMethodChaining( 'toUVec4', uvec4 );
  2869. addMethodChaining( 'toBVec4', bvec4 );
  2870. addMethodChaining( 'toMat2', mat2 );
  2871. addMethodChaining( 'toMat3', mat3 );
  2872. addMethodChaining( 'toMat4', mat4 );
  2873. // basic nodes
  2874. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2875. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2876. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2877. addMethodChaining( 'element', element );
  2878. addMethodChaining( 'convert', convert );
  2879. // deprecated
  2880. /**
  2881. * @tsl
  2882. * @function
  2883. * @deprecated since r176. Use {@link Stack} instead.
  2884. *
  2885. * @param {Node} node - The node to add.
  2886. * @returns {Function}
  2887. */
  2888. const append = ( node ) => { // @deprecated, r176
  2889. warn( 'TSL: append() has been renamed to Stack().' );
  2890. return Stack( node );
  2891. };
  2892. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2893. warn( 'TSL: .append() has been renamed to .toStack().' );
  2894. return Stack( node );
  2895. } );
  2896. /**
  2897. * This class represents a shader property. It can be used
  2898. * to explicitly define a property and assign a value to it.
  2899. *
  2900. * ```js
  2901. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2902. *```
  2903. * `PropertyNode` is used by the engine to predefined common material properties
  2904. * for TSL code.
  2905. *
  2906. * @augments Node
  2907. */
  2908. class PropertyNode extends Node {
  2909. static get type() {
  2910. return 'PropertyNode';
  2911. }
  2912. /**
  2913. * Constructs a new property node.
  2914. *
  2915. * @param {string} nodeType - The type of the node.
  2916. * @param {?string} [name=null] - The name of the property in the shader.
  2917. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2918. */
  2919. constructor( nodeType, name = null, varying = false ) {
  2920. super( nodeType );
  2921. /**
  2922. * The name of the property in the shader. If no name is defined,
  2923. * the node system auto-generates one.
  2924. *
  2925. * @type {?string}
  2926. * @default null
  2927. */
  2928. this.name = name;
  2929. /**
  2930. * Whether this property is a varying or not.
  2931. *
  2932. * @type {boolean}
  2933. * @default false
  2934. */
  2935. this.varying = varying;
  2936. /**
  2937. * This flag can be used for type testing.
  2938. *
  2939. * @type {boolean}
  2940. * @readonly
  2941. * @default true
  2942. */
  2943. this.isPropertyNode = true;
  2944. /**
  2945. * This flag is used for global cache.
  2946. *
  2947. * @type {boolean}
  2948. * @default true
  2949. */
  2950. this.global = true;
  2951. }
  2952. getHash( builder ) {
  2953. return this.name || super.getHash( builder );
  2954. }
  2955. generate( builder ) {
  2956. let nodeVar;
  2957. if ( this.varying === true ) {
  2958. nodeVar = builder.getVaryingFromNode( this, this.name );
  2959. nodeVar.needsInterpolation = true;
  2960. } else {
  2961. nodeVar = builder.getVarFromNode( this, this.name );
  2962. }
  2963. return builder.getPropertyName( nodeVar );
  2964. }
  2965. }
  2966. /**
  2967. * TSL function for creating a property node.
  2968. *
  2969. * @tsl
  2970. * @function
  2971. * @param {string} type - The type of the node.
  2972. * @param {?string} [name=null] - The name of the property in the shader.
  2973. * @returns {PropertyNode}
  2974. */
  2975. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2976. /**
  2977. * TSL function for creating a varying property node.
  2978. *
  2979. * @tsl
  2980. * @function
  2981. * @param {string} type - The type of the node.
  2982. * @param {?string} [name=null] - The name of the varying in the shader.
  2983. * @returns {PropertyNode}
  2984. */
  2985. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2986. /**
  2987. * TSL object that represents the shader variable `DiffuseColor`.
  2988. *
  2989. * @tsl
  2990. * @type {PropertyNode<vec4>}
  2991. */
  2992. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2993. /**
  2994. * TSL object that represents the shader variable `EmissiveColor`.
  2995. *
  2996. * @tsl
  2997. * @type {PropertyNode<vec3>}
  2998. */
  2999. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3000. /**
  3001. * TSL object that represents the shader variable `Roughness`.
  3002. *
  3003. * @tsl
  3004. * @type {PropertyNode<float>}
  3005. */
  3006. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3007. /**
  3008. * TSL object that represents the shader variable `Metalness`.
  3009. *
  3010. * @tsl
  3011. * @type {PropertyNode<float>}
  3012. */
  3013. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3014. /**
  3015. * TSL object that represents the shader variable `Clearcoat`.
  3016. *
  3017. * @tsl
  3018. * @type {PropertyNode<float>}
  3019. */
  3020. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3021. /**
  3022. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3023. *
  3024. * @tsl
  3025. * @type {PropertyNode<float>}
  3026. */
  3027. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3028. /**
  3029. * TSL object that represents the shader variable `Sheen`.
  3030. *
  3031. * @tsl
  3032. * @type {PropertyNode<vec3>}
  3033. */
  3034. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3035. /**
  3036. * TSL object that represents the shader variable `SheenRoughness`.
  3037. *
  3038. * @tsl
  3039. * @type {PropertyNode<float>}
  3040. */
  3041. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3042. /**
  3043. * TSL object that represents the shader variable `Iridescence`.
  3044. *
  3045. * @tsl
  3046. * @type {PropertyNode<float>}
  3047. */
  3048. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3049. /**
  3050. * TSL object that represents the shader variable `IridescenceIOR`.
  3051. *
  3052. * @tsl
  3053. * @type {PropertyNode<float>}
  3054. */
  3055. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3056. /**
  3057. * TSL object that represents the shader variable `IridescenceThickness`.
  3058. *
  3059. * @tsl
  3060. * @type {PropertyNode<float>}
  3061. */
  3062. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3063. /**
  3064. * TSL object that represents the shader variable `AlphaT`.
  3065. *
  3066. * @tsl
  3067. * @type {PropertyNode<float>}
  3068. */
  3069. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3070. /**
  3071. * TSL object that represents the shader variable `Anisotropy`.
  3072. *
  3073. * @tsl
  3074. * @type {PropertyNode<float>}
  3075. */
  3076. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3077. /**
  3078. * TSL object that represents the shader variable `AnisotropyT`.
  3079. *
  3080. * @tsl
  3081. * @type {PropertyNode<vec3>}
  3082. */
  3083. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3084. /**
  3085. * TSL object that represents the shader variable `AnisotropyB`.
  3086. *
  3087. * @tsl
  3088. * @type {PropertyNode<vec3>}
  3089. */
  3090. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3091. /**
  3092. * TSL object that represents the shader variable `SpecularColor`.
  3093. *
  3094. * @tsl
  3095. * @type {PropertyNode<color>}
  3096. */
  3097. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3098. /**
  3099. * TSL object that represents the shader variable `SpecularF90`.
  3100. *
  3101. * @tsl
  3102. * @type {PropertyNode<float>}
  3103. */
  3104. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3105. /**
  3106. * TSL object that represents the shader variable `Shininess`.
  3107. *
  3108. * @tsl
  3109. * @type {PropertyNode<float>}
  3110. */
  3111. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3112. /**
  3113. * TSL object that represents the shader variable `Output`.
  3114. *
  3115. * @tsl
  3116. * @type {PropertyNode<vec4>}
  3117. */
  3118. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3119. /**
  3120. * TSL object that represents the shader variable `dashSize`.
  3121. *
  3122. * @tsl
  3123. * @type {PropertyNode<float>}
  3124. */
  3125. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3126. /**
  3127. * TSL object that represents the shader variable `gapSize`.
  3128. *
  3129. * @tsl
  3130. * @type {PropertyNode<float>}
  3131. */
  3132. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3133. /**
  3134. * TSL object that represents the shader variable `pointWidth`.
  3135. *
  3136. * @tsl
  3137. * @type {PropertyNode<float>}
  3138. */
  3139. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3140. /**
  3141. * TSL object that represents the shader variable `IOR`.
  3142. *
  3143. * @tsl
  3144. * @type {PropertyNode<float>}
  3145. */
  3146. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3147. /**
  3148. * TSL object that represents the shader variable `Transmission`.
  3149. *
  3150. * @tsl
  3151. * @type {PropertyNode<float>}
  3152. */
  3153. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3154. /**
  3155. * TSL object that represents the shader variable `Thickness`.
  3156. *
  3157. * @tsl
  3158. * @type {PropertyNode<float>}
  3159. */
  3160. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3161. /**
  3162. * TSL object that represents the shader variable `AttenuationDistance`.
  3163. *
  3164. * @tsl
  3165. * @type {PropertyNode<float>}
  3166. */
  3167. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3168. /**
  3169. * TSL object that represents the shader variable `AttenuationColor`.
  3170. *
  3171. * @tsl
  3172. * @type {PropertyNode<color>}
  3173. */
  3174. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3175. /**
  3176. * TSL object that represents the shader variable `Dispersion`.
  3177. *
  3178. * @tsl
  3179. * @type {PropertyNode<float>}
  3180. */
  3181. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3182. /**
  3183. * This node can be used to group single instances of {@link UniformNode}
  3184. * and manage them as a uniform buffer.
  3185. *
  3186. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3187. * will be used when defining the {@link UniformNode#groupNode} property.
  3188. *
  3189. * - `objectGroup`: Uniform buffer per object.
  3190. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3191. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3192. *
  3193. * @augments Node
  3194. */
  3195. class UniformGroupNode extends Node {
  3196. static get type() {
  3197. return 'UniformGroupNode';
  3198. }
  3199. /**
  3200. * Constructs a new uniform group node.
  3201. *
  3202. * @param {string} name - The name of the uniform group node.
  3203. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3204. * @param {number} [order=1] - Influences the internal sorting.
  3205. */
  3206. constructor( name, shared = false, order = 1 ) {
  3207. super( 'string' );
  3208. /**
  3209. * The name of the uniform group node.
  3210. *
  3211. * @type {string}
  3212. */
  3213. this.name = name;
  3214. /**
  3215. * Whether this uniform group node is shared or not.
  3216. *
  3217. * @type {boolean}
  3218. * @default false
  3219. */
  3220. this.shared = shared;
  3221. /**
  3222. * Influences the internal sorting.
  3223. * TODO: Add details when this property should be changed.
  3224. *
  3225. * @type {number}
  3226. * @default 1
  3227. */
  3228. this.order = order;
  3229. /**
  3230. * This flag can be used for type testing.
  3231. *
  3232. * @type {boolean}
  3233. * @readonly
  3234. * @default true
  3235. */
  3236. this.isUniformGroup = true;
  3237. }
  3238. serialize( data ) {
  3239. super.serialize( data );
  3240. data.name = this.name;
  3241. data.version = this.version;
  3242. data.shared = this.shared;
  3243. }
  3244. deserialize( data ) {
  3245. super.deserialize( data );
  3246. this.name = data.name;
  3247. this.version = data.version;
  3248. this.shared = data.shared;
  3249. }
  3250. }
  3251. /**
  3252. * TSL function for creating a uniform group node with the given name.
  3253. *
  3254. * @tsl
  3255. * @function
  3256. * @param {string} name - The name of the uniform group node.
  3257. * @returns {UniformGroupNode}
  3258. */
  3259. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3260. /**
  3261. * TSL function for creating a shared uniform group node with the given name and order.
  3262. *
  3263. * @tsl
  3264. * @function
  3265. * @param {string} name - The name of the uniform group node.
  3266. * @param {number} [order=0] - Influences the internal sorting.
  3267. * @returns {UniformGroupNode}
  3268. */
  3269. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3270. /**
  3271. * TSL object that represents a shared uniform group node which is updated once per frame.
  3272. *
  3273. * @tsl
  3274. * @type {UniformGroupNode}
  3275. */
  3276. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3277. /**
  3278. * TSL object that represents a shared uniform group node which is updated once per render.
  3279. *
  3280. * @tsl
  3281. * @type {UniformGroupNode}
  3282. */
  3283. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3284. /**
  3285. * TSL object that represents a uniform group node which is updated once per object.
  3286. *
  3287. * @tsl
  3288. * @type {UniformGroupNode}
  3289. */
  3290. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3291. /**
  3292. * Class for representing a uniform.
  3293. *
  3294. * @augments InputNode
  3295. */
  3296. class UniformNode extends InputNode {
  3297. static get type() {
  3298. return 'UniformNode';
  3299. }
  3300. /**
  3301. * Constructs a new uniform node.
  3302. *
  3303. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3304. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3305. */
  3306. constructor( value, nodeType = null ) {
  3307. super( value, nodeType );
  3308. /**
  3309. * This flag can be used for type testing.
  3310. *
  3311. * @type {boolean}
  3312. * @readonly
  3313. * @default true
  3314. */
  3315. this.isUniformNode = true;
  3316. /**
  3317. * The name or label of the uniform.
  3318. *
  3319. * @type {string}
  3320. * @default ''
  3321. */
  3322. this.name = '';
  3323. /**
  3324. * The uniform group of this uniform. By default, uniforms are
  3325. * managed per object but they might belong to a shared group
  3326. * which is updated per frame or render call.
  3327. *
  3328. * @type {UniformGroupNode}
  3329. */
  3330. this.groupNode = objectGroup;
  3331. }
  3332. /**
  3333. * Sets the {@link UniformNode#name} property.
  3334. *
  3335. * @param {string} name - The name of the uniform.
  3336. * @return {UniformNode} A reference to this node.
  3337. */
  3338. setName( name ) {
  3339. this.name = name;
  3340. return this;
  3341. }
  3342. /**
  3343. * Sets the {@link UniformNode#name} property.
  3344. *
  3345. * @deprecated
  3346. * @param {string} name - The name of the uniform.
  3347. * @return {UniformNode} A reference to this node.
  3348. */
  3349. label( name ) {
  3350. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3351. return this.setName( name );
  3352. }
  3353. /**
  3354. * Sets the {@link UniformNode#groupNode} property.
  3355. *
  3356. * @param {UniformGroupNode} group - The uniform group.
  3357. * @return {UniformNode} A reference to this node.
  3358. */
  3359. setGroup( group ) {
  3360. this.groupNode = group;
  3361. return this;
  3362. }
  3363. /**
  3364. * Returns the {@link UniformNode#groupNode}.
  3365. *
  3366. * @return {UniformGroupNode} The uniform group.
  3367. */
  3368. getGroup() {
  3369. return this.groupNode;
  3370. }
  3371. /**
  3372. * By default, this method returns the result of {@link Node#getHash} but derived
  3373. * classes might overwrite this method with a different implementation.
  3374. *
  3375. * @param {NodeBuilder} builder - The current node builder.
  3376. * @return {string} The uniform hash.
  3377. */
  3378. getUniformHash( builder ) {
  3379. return this.getHash( builder );
  3380. }
  3381. onUpdate( callback, updateType ) {
  3382. callback = callback.bind( this );
  3383. return super.onUpdate( ( frame ) => {
  3384. const value = callback( frame, this );
  3385. if ( value !== undefined ) {
  3386. this.value = value;
  3387. }
  3388. }, updateType );
  3389. }
  3390. getInputType( builder ) {
  3391. let type = super.getInputType( builder );
  3392. if ( type === 'bool' ) {
  3393. type = 'uint';
  3394. }
  3395. return type;
  3396. }
  3397. generate( builder, output ) {
  3398. const type = this.getNodeType( builder );
  3399. const hash = this.getUniformHash( builder );
  3400. let sharedNode = builder.getNodeFromHash( hash );
  3401. if ( sharedNode === undefined ) {
  3402. builder.setHashNode( this, hash );
  3403. sharedNode = this;
  3404. }
  3405. const sharedNodeType = sharedNode.getInputType( builder );
  3406. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3407. const uniformName = builder.getPropertyName( nodeUniform );
  3408. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3409. //
  3410. let snippet = uniformName;
  3411. if ( type === 'bool' ) {
  3412. // cache to variable
  3413. const nodeData = builder.getDataFromNode( this );
  3414. let propertyName = nodeData.propertyName;
  3415. if ( propertyName === undefined ) {
  3416. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3417. propertyName = builder.getPropertyName( nodeVar );
  3418. nodeData.propertyName = propertyName;
  3419. snippet = builder.format( uniformName, sharedNodeType, type );
  3420. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3421. }
  3422. snippet = propertyName;
  3423. }
  3424. return builder.format( snippet, type, output );
  3425. }
  3426. }
  3427. /**
  3428. * TSL function for creating a uniform node.
  3429. *
  3430. * @tsl
  3431. * @function
  3432. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3433. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3434. * @returns {UniformNode}
  3435. */
  3436. const uniform = ( value, type ) => {
  3437. const nodeType = getConstNodeType( type || value );
  3438. if ( nodeType === value ) {
  3439. // if the value is a type but no having a value
  3440. value = getValueFromType( nodeType );
  3441. }
  3442. // @TODO: get ConstNode from .traverse() in the future
  3443. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3444. return nodeObject( new UniformNode( value, nodeType ) );
  3445. };
  3446. /**
  3447. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3448. * ```js
  3449. * const colors = array( [
  3450. * vec3( 1, 0, 0 ),
  3451. * vec3( 0, 1, 0 ),
  3452. * vec3( 0, 0, 1 )
  3453. * ] );
  3454. *
  3455. * const redColor = tintColors.element( 0 );
  3456. * ```
  3457. *
  3458. * @augments TempNode
  3459. */
  3460. class ArrayNode extends TempNode {
  3461. static get type() {
  3462. return 'ArrayNode';
  3463. }
  3464. /**
  3465. * Constructs a new array node.
  3466. *
  3467. * @param {?string} nodeType - The data type of the elements.
  3468. * @param {number} count - Size of the array.
  3469. * @param {?Array<Node>} [values=null] - Array default values.
  3470. */
  3471. constructor( nodeType, count, values = null ) {
  3472. super( nodeType );
  3473. /**
  3474. * Array size.
  3475. *
  3476. * @type {number}
  3477. */
  3478. this.count = count;
  3479. /**
  3480. * Array default values.
  3481. *
  3482. * @type {?Array<Node>}
  3483. */
  3484. this.values = values;
  3485. /**
  3486. * This flag can be used for type testing.
  3487. *
  3488. * @type {boolean}
  3489. * @readonly
  3490. * @default true
  3491. */
  3492. this.isArrayNode = true;
  3493. }
  3494. /**
  3495. * Returns the number of elements in the node array.
  3496. *
  3497. * @param {NodeBuilder} builder - The current node builder.
  3498. * @return {number} The number of elements in the node array.
  3499. */
  3500. getArrayCount( /*builder*/ ) {
  3501. return this.count;
  3502. }
  3503. /**
  3504. * Returns the node's type.
  3505. *
  3506. * @param {NodeBuilder} builder - The current node builder.
  3507. * @return {string} The type of the node.
  3508. */
  3509. getNodeType( builder ) {
  3510. if ( this.nodeType === null ) {
  3511. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3512. }
  3513. return this.nodeType;
  3514. }
  3515. /**
  3516. * Returns the node's type.
  3517. *
  3518. * @param {NodeBuilder} builder - The current node builder.
  3519. * @return {string} The type of the node.
  3520. */
  3521. getElementType( builder ) {
  3522. return this.getNodeType( builder );
  3523. }
  3524. /**
  3525. * This method builds the output node and returns the resulting array as a shader string.
  3526. *
  3527. * @param {NodeBuilder} builder - The current node builder.
  3528. * @return {string} The generated shader string.
  3529. */
  3530. generate( builder ) {
  3531. const type = this.getNodeType( builder );
  3532. return builder.generateArray( type, this.count, this.values );
  3533. }
  3534. }
  3535. /**
  3536. * TSL function for creating an array node.
  3537. *
  3538. * @tsl
  3539. * @function
  3540. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3541. * or an array containing the default values (e.g., [ vec3() ]).
  3542. * @param {?number} [count] - Size of the array.
  3543. * @returns {ArrayNode}
  3544. */
  3545. const array = ( ...params ) => {
  3546. let node;
  3547. if ( params.length === 1 ) {
  3548. const values = params[ 0 ];
  3549. node = new ArrayNode( null, values.length, values );
  3550. } else {
  3551. const nodeType = params[ 0 ];
  3552. const count = params[ 1 ];
  3553. node = new ArrayNode( nodeType, count );
  3554. }
  3555. return nodeObject( node );
  3556. };
  3557. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3558. /**
  3559. * These node represents an assign operation. Meaning a node is assigned
  3560. * to another node.
  3561. *
  3562. * @augments TempNode
  3563. */
  3564. class AssignNode extends TempNode {
  3565. static get type() {
  3566. return 'AssignNode';
  3567. }
  3568. /**
  3569. * Constructs a new assign node.
  3570. *
  3571. * @param {Node} targetNode - The target node.
  3572. * @param {Node} sourceNode - The source type.
  3573. */
  3574. constructor( targetNode, sourceNode ) {
  3575. super();
  3576. /**
  3577. * The target node.
  3578. *
  3579. * @type {Node}
  3580. */
  3581. this.targetNode = targetNode;
  3582. /**
  3583. * The source node.
  3584. *
  3585. * @type {Node}
  3586. */
  3587. this.sourceNode = sourceNode;
  3588. /**
  3589. * This flag can be used for type testing.
  3590. *
  3591. * @type {boolean}
  3592. * @readonly
  3593. * @default true
  3594. */
  3595. this.isAssignNode = true;
  3596. }
  3597. /**
  3598. * Whether this node is used more than once in context of other nodes. This method
  3599. * is overwritten since it always returns `false` (assigns are unique).
  3600. *
  3601. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3602. */
  3603. hasDependencies() {
  3604. return false;
  3605. }
  3606. getNodeType( builder, output ) {
  3607. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3608. }
  3609. /**
  3610. * Whether a split is required when assigning source to target. This can happen when the component length of
  3611. * target and source data type does not match.
  3612. *
  3613. * @param {NodeBuilder} builder - The current node builder.
  3614. * @return {boolean} Whether a split is required when assigning source to target.
  3615. */
  3616. needsSplitAssign( builder ) {
  3617. const { targetNode } = this;
  3618. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3619. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3620. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3621. return assignDifferentVector;
  3622. }
  3623. return false;
  3624. }
  3625. setup( builder ) {
  3626. const { targetNode, sourceNode } = this;
  3627. const scope = targetNode.getScope();
  3628. const targetProperties = builder.getNodeProperties( scope );
  3629. targetProperties.assign = true;
  3630. const properties = builder.getNodeProperties( this );
  3631. properties.sourceNode = sourceNode;
  3632. properties.targetNode = targetNode.context( { assign: true } );
  3633. }
  3634. generate( builder, output ) {
  3635. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3636. const needsSplitAssign = this.needsSplitAssign( builder );
  3637. const target = targetNode.build( builder );
  3638. const targetType = targetNode.getNodeType( builder );
  3639. const source = sourceNode.build( builder, targetType );
  3640. const sourceType = sourceNode.getNodeType( builder );
  3641. const nodeData = builder.getDataFromNode( this );
  3642. //
  3643. let snippet;
  3644. if ( nodeData.initialized === true ) {
  3645. if ( output !== 'void' ) {
  3646. snippet = target;
  3647. }
  3648. } else if ( needsSplitAssign ) {
  3649. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3650. const sourceProperty = builder.getPropertyName( sourceVar );
  3651. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3652. const splitNode = targetNode.node;
  3653. const splitTargetNode = splitNode.node.context( { assign: true } );
  3654. const targetRoot = splitTargetNode.build( builder );
  3655. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3656. const component = splitNode.components[ i ];
  3657. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3658. }
  3659. if ( output !== 'void' ) {
  3660. snippet = target;
  3661. }
  3662. } else {
  3663. snippet = `${ target } = ${ source }`;
  3664. if ( output === 'void' || sourceType === 'void' ) {
  3665. builder.addLineFlowCode( snippet, this );
  3666. if ( output !== 'void' ) {
  3667. snippet = target;
  3668. }
  3669. }
  3670. }
  3671. nodeData.initialized = true;
  3672. return builder.format( snippet, targetType, output );
  3673. }
  3674. }
  3675. /**
  3676. * TSL function for creating an assign node.
  3677. *
  3678. * @tsl
  3679. * @function
  3680. * @param {Node} targetNode - The target node.
  3681. * @param {Node} sourceNode - The source type.
  3682. * @returns {AssignNode}
  3683. */
  3684. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3685. addMethodChaining( 'assign', assign );
  3686. /**
  3687. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3688. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3689. * this logic.
  3690. *
  3691. * @augments TempNode
  3692. */
  3693. class FunctionCallNode extends TempNode {
  3694. static get type() {
  3695. return 'FunctionCallNode';
  3696. }
  3697. /**
  3698. * Constructs a new function call node.
  3699. *
  3700. * @param {?FunctionNode} functionNode - The function node.
  3701. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3702. */
  3703. constructor( functionNode = null, parameters = {} ) {
  3704. super();
  3705. /**
  3706. * The function node.
  3707. *
  3708. * @type {?FunctionNode}
  3709. * @default null
  3710. */
  3711. this.functionNode = functionNode;
  3712. /**
  3713. * The parameters of the function call.
  3714. *
  3715. * @type {Object<string, Node>}
  3716. * @default {}
  3717. */
  3718. this.parameters = parameters;
  3719. }
  3720. /**
  3721. * Sets the parameters of the function call node.
  3722. *
  3723. * @param {Object<string, Node>} parameters - The parameters to set.
  3724. * @return {FunctionCallNode} A reference to this node.
  3725. */
  3726. setParameters( parameters ) {
  3727. this.parameters = parameters;
  3728. return this;
  3729. }
  3730. /**
  3731. * Returns the parameters of the function call node.
  3732. *
  3733. * @return {Object<string, Node>} The parameters of this node.
  3734. */
  3735. getParameters() {
  3736. return this.parameters;
  3737. }
  3738. /**
  3739. * Returns the type of this function call node.
  3740. *
  3741. * @param {NodeBuilder} builder - The current node builder.
  3742. * @returns {string} The type of this node.
  3743. */
  3744. getNodeType( builder ) {
  3745. return this.functionNode.getNodeType( builder );
  3746. }
  3747. /**
  3748. * Returns the function node of this function call node.
  3749. *
  3750. * @param {NodeBuilder} builder - The current node builder.
  3751. * @param {string} [name] - The name of the member.
  3752. * @returns {string} The type of the member.
  3753. */
  3754. getMemberType( builder, name ) {
  3755. return this.functionNode.getMemberType( builder, name );
  3756. }
  3757. generate( builder ) {
  3758. const params = [];
  3759. const functionNode = this.functionNode;
  3760. const inputs = functionNode.getInputs( builder );
  3761. const parameters = this.parameters;
  3762. const generateInput = ( node, inputNode ) => {
  3763. const type = inputNode.type;
  3764. const pointer = type === 'pointer';
  3765. let output;
  3766. if ( pointer ) output = '&' + node.build( builder );
  3767. else output = node.build( builder, type );
  3768. return output;
  3769. };
  3770. if ( Array.isArray( parameters ) ) {
  3771. if ( parameters.length > inputs.length ) {
  3772. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3773. parameters.length = inputs.length;
  3774. } else if ( parameters.length < inputs.length ) {
  3775. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3776. while ( parameters.length < inputs.length ) {
  3777. parameters.push( float( 0 ) );
  3778. }
  3779. }
  3780. for ( let i = 0; i < parameters.length; i ++ ) {
  3781. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3782. }
  3783. } else {
  3784. for ( const inputNode of inputs ) {
  3785. const node = parameters[ inputNode.name ];
  3786. if ( node !== undefined ) {
  3787. params.push( generateInput( node, inputNode ) );
  3788. } else {
  3789. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3790. params.push( generateInput( float( 0 ), inputNode ) );
  3791. }
  3792. }
  3793. }
  3794. const functionName = functionNode.build( builder, 'property' );
  3795. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3796. }
  3797. }
  3798. const call = ( func, ...params ) => {
  3799. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3800. return new FunctionCallNode( nodeObject( func ), params );
  3801. };
  3802. addMethodChaining( 'call', call );
  3803. const _vectorOperators = {
  3804. '==': 'equal',
  3805. '!=': 'notEqual',
  3806. '<': 'lessThan',
  3807. '>': 'greaterThan',
  3808. '<=': 'lessThanEqual',
  3809. '>=': 'greaterThanEqual',
  3810. '%': 'mod'
  3811. };
  3812. /**
  3813. * This node represents basic mathematical and logical operations like addition,
  3814. * subtraction or comparisons (e.g. `equal()`).
  3815. *
  3816. * @augments TempNode
  3817. */
  3818. class OperatorNode extends TempNode {
  3819. static get type() {
  3820. return 'OperatorNode';
  3821. }
  3822. /**
  3823. * Constructs a new operator node.
  3824. *
  3825. * @param {string} op - The operator.
  3826. * @param {Node} aNode - The first input.
  3827. * @param {Node} bNode - The second input.
  3828. * @param {...Node} params - Additional input parameters.
  3829. */
  3830. constructor( op, aNode, bNode, ...params ) {
  3831. super();
  3832. if ( params.length > 0 ) {
  3833. let finalOp = new OperatorNode( op, aNode, bNode );
  3834. for ( let i = 0; i < params.length - 1; i ++ ) {
  3835. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3836. }
  3837. aNode = finalOp;
  3838. bNode = params[ params.length - 1 ];
  3839. }
  3840. /**
  3841. * The operator.
  3842. *
  3843. * @type {string}
  3844. */
  3845. this.op = op;
  3846. /**
  3847. * The first input.
  3848. *
  3849. * @type {Node}
  3850. */
  3851. this.aNode = aNode;
  3852. /**
  3853. * The second input.
  3854. *
  3855. * @type {Node}
  3856. */
  3857. this.bNode = bNode;
  3858. /**
  3859. * This flag can be used for type testing.
  3860. *
  3861. * @type {boolean}
  3862. * @readonly
  3863. * @default true
  3864. */
  3865. this.isOperatorNode = true;
  3866. }
  3867. /**
  3868. * Returns the operator method name.
  3869. *
  3870. * @param {NodeBuilder} builder - The current node builder.
  3871. * @param {string} output - The output type.
  3872. * @returns {string} The operator method name.
  3873. */
  3874. getOperatorMethod( builder, output ) {
  3875. return builder.getMethod( _vectorOperators[ this.op ], output );
  3876. }
  3877. /**
  3878. * This method is overwritten since the node type is inferred from the operator
  3879. * and the input node types.
  3880. *
  3881. * @param {NodeBuilder} builder - The current node builder.
  3882. * @param {?string} [output=null] - The output type.
  3883. * @return {string} The node type.
  3884. */
  3885. getNodeType( builder, output = null ) {
  3886. const op = this.op;
  3887. const aNode = this.aNode;
  3888. const bNode = this.bNode;
  3889. const typeA = aNode.getNodeType( builder );
  3890. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3891. if ( typeA === 'void' || typeB === 'void' ) {
  3892. return output || 'void';
  3893. } else if ( op === '%' ) {
  3894. return typeA;
  3895. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3896. return builder.getIntegerType( typeA );
  3897. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3898. return 'bool';
  3899. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3900. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3901. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3902. } else {
  3903. // Handle matrix operations
  3904. if ( builder.isMatrix( typeA ) ) {
  3905. if ( typeB === 'float' ) {
  3906. return typeA; // matrix * scalar = matrix
  3907. } else if ( builder.isVector( typeB ) ) {
  3908. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3909. } else if ( builder.isMatrix( typeB ) ) {
  3910. return typeA; // matrix * matrix
  3911. }
  3912. } else if ( builder.isMatrix( typeB ) ) {
  3913. if ( typeA === 'float' ) {
  3914. return typeB; // scalar * matrix = matrix
  3915. } else if ( builder.isVector( typeA ) ) {
  3916. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3917. }
  3918. }
  3919. // Handle non-matrix cases
  3920. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3921. // anytype x anytype: use the greater length vector
  3922. return typeB;
  3923. }
  3924. return typeA;
  3925. }
  3926. }
  3927. generate( builder, output ) {
  3928. const op = this.op;
  3929. const { aNode, bNode } = this;
  3930. const type = this.getNodeType( builder, output );
  3931. let typeA = null;
  3932. let typeB = null;
  3933. if ( type !== 'void' ) {
  3934. typeA = aNode.getNodeType( builder );
  3935. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3936. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3937. if ( builder.isVector( typeA ) ) {
  3938. typeB = typeA;
  3939. } else if ( builder.isVector( typeB ) ) {
  3940. typeA = typeB;
  3941. } else if ( typeA !== typeB ) {
  3942. typeA = typeB = 'float';
  3943. }
  3944. } else if ( op === '>>' || op === '<<' ) {
  3945. typeA = type;
  3946. typeB = builder.changeComponentType( typeB, 'uint' );
  3947. } else if ( op === '%' ) {
  3948. typeA = type;
  3949. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3950. } else if ( builder.isMatrix( typeA ) ) {
  3951. if ( typeB === 'float' ) {
  3952. // Keep matrix type for typeA, but ensure typeB stays float
  3953. typeB = 'float';
  3954. } else if ( builder.isVector( typeB ) ) {
  3955. // matrix x vector
  3956. typeB = builder.getVectorFromMatrix( typeA );
  3957. } else if ( builder.isMatrix( typeB ) ) ; else {
  3958. typeA = typeB = type;
  3959. }
  3960. } else if ( builder.isMatrix( typeB ) ) {
  3961. if ( typeA === 'float' ) {
  3962. // Keep matrix type for typeB, but ensure typeA stays float
  3963. typeA = 'float';
  3964. } else if ( builder.isVector( typeA ) ) {
  3965. // vector x matrix
  3966. typeA = builder.getVectorFromMatrix( typeB );
  3967. } else {
  3968. typeA = typeB = type;
  3969. }
  3970. } else {
  3971. // anytype x anytype
  3972. typeA = typeB = type;
  3973. }
  3974. } else {
  3975. typeA = typeB = type;
  3976. }
  3977. const a = aNode.build( builder, typeA );
  3978. const b = bNode ? bNode.build( builder, typeB ) : null;
  3979. const fnOpSnippet = builder.getFunctionOperator( op );
  3980. if ( output !== 'void' ) {
  3981. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3982. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3983. if ( isGLSL ) {
  3984. if ( builder.isVector( typeA ) ) {
  3985. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3986. } else {
  3987. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3988. }
  3989. } else {
  3990. // WGSL
  3991. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3992. }
  3993. } else if ( op === '%' ) {
  3994. if ( builder.isInteger( typeB ) ) {
  3995. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3996. } else {
  3997. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3998. }
  3999. } else if ( op === '!' || op === '~' ) {
  4000. return builder.format( `(${op}${a})`, typeA, output );
  4001. } else if ( fnOpSnippet ) {
  4002. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4003. } else {
  4004. // Handle matrix operations
  4005. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4006. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4007. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4008. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4009. } else {
  4010. let snippet = `( ${ a } ${ op } ${ b } )`;
  4011. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4012. snippet = `all${ snippet }`;
  4013. }
  4014. return builder.format( snippet, type, output );
  4015. }
  4016. }
  4017. } else if ( typeA !== 'void' ) {
  4018. if ( fnOpSnippet ) {
  4019. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4020. } else {
  4021. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4022. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4023. } else {
  4024. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4025. }
  4026. }
  4027. }
  4028. }
  4029. serialize( data ) {
  4030. super.serialize( data );
  4031. data.op = this.op;
  4032. }
  4033. deserialize( data ) {
  4034. super.deserialize( data );
  4035. this.op = data.op;
  4036. }
  4037. }
  4038. /**
  4039. * Returns the addition of two or more value.
  4040. *
  4041. * @tsl
  4042. * @function
  4043. * @param {Node} a - The first input.
  4044. * @param {Node} b - The second input.
  4045. * @param {...Node} params - Additional input parameters.
  4046. * @returns {OperatorNode}
  4047. */
  4048. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4049. /**
  4050. * Returns the subtraction of two or more value.
  4051. *
  4052. * @tsl
  4053. * @function
  4054. * @param {Node} a - The first input.
  4055. * @param {Node} b - The second input.
  4056. * @param {...Node} params - Additional input parameters.
  4057. * @returns {OperatorNode}
  4058. */
  4059. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4060. /**
  4061. * Returns the multiplication of two or more value.
  4062. *
  4063. * @tsl
  4064. * @function
  4065. * @param {Node} a - The first input.
  4066. * @param {Node} b - The second input.
  4067. * @param {...Node} params - Additional input parameters.
  4068. * @returns {OperatorNode}
  4069. */
  4070. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4071. /**
  4072. * Returns the division of two or more value.
  4073. *
  4074. * @tsl
  4075. * @function
  4076. * @param {Node} a - The first input.
  4077. * @param {Node} b - The second input.
  4078. * @param {...Node} params - Additional input parameters.
  4079. * @returns {OperatorNode}
  4080. */
  4081. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4082. /**
  4083. * Computes the remainder of dividing the first node by the second one.
  4084. *
  4085. * @tsl
  4086. * @function
  4087. * @param {Node} a - The first input.
  4088. * @param {Node} b - The second input.
  4089. * @returns {OperatorNode}
  4090. */
  4091. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4092. /**
  4093. * Checks if two nodes are equal.
  4094. *
  4095. * @tsl
  4096. * @function
  4097. * @param {Node} a - The first input.
  4098. * @param {Node} b - The second input.
  4099. * @returns {OperatorNode}
  4100. */
  4101. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4102. /**
  4103. * Checks if two nodes are not equal.
  4104. *
  4105. * @tsl
  4106. * @function
  4107. * @param {Node} a - The first input.
  4108. * @param {Node} b - The second input.
  4109. * @returns {OperatorNode}
  4110. */
  4111. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4112. /**
  4113. * Checks if the first node is less than the second.
  4114. *
  4115. * @tsl
  4116. * @function
  4117. * @param {Node} a - The first input.
  4118. * @param {Node} b - The second input.
  4119. * @returns {OperatorNode}
  4120. */
  4121. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4122. /**
  4123. * Checks if the first node is greater than the second.
  4124. *
  4125. * @tsl
  4126. * @function
  4127. * @param {Node} a - The first input.
  4128. * @param {Node} b - The second input.
  4129. * @returns {OperatorNode}
  4130. */
  4131. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4132. /**
  4133. * Checks if the first node is less than or equal to the second.
  4134. *
  4135. * @tsl
  4136. * @function
  4137. * @param {Node} a - The first input.
  4138. * @param {Node} b - The second input.
  4139. * @returns {OperatorNode}
  4140. */
  4141. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4142. /**
  4143. * Checks if the first node is greater than or equal to the second.
  4144. *
  4145. * @tsl
  4146. * @function
  4147. * @param {Node} a - The first input.
  4148. * @param {Node} b - The second input.
  4149. * @returns {OperatorNode}
  4150. */
  4151. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4152. /**
  4153. * Performs a logical AND operation on multiple nodes.
  4154. *
  4155. * @tsl
  4156. * @function
  4157. * @param {...Node} nodes - The input nodes to be combined using AND.
  4158. * @returns {OperatorNode}
  4159. */
  4160. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4161. /**
  4162. * Performs a logical OR operation on multiple nodes.
  4163. *
  4164. * @tsl
  4165. * @function
  4166. * @param {...Node} nodes - The input nodes to be combined using OR.
  4167. * @returns {OperatorNode}
  4168. */
  4169. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4170. /**
  4171. * Performs logical NOT on a node.
  4172. *
  4173. * @tsl
  4174. * @function
  4175. * @param {Node} value - The value.
  4176. * @returns {OperatorNode}
  4177. */
  4178. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4179. /**
  4180. * Performs logical XOR on two nodes.
  4181. *
  4182. * @tsl
  4183. * @function
  4184. * @param {Node} a - The first input.
  4185. * @param {Node} b - The second input.
  4186. * @returns {OperatorNode}
  4187. */
  4188. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4189. /**
  4190. * Performs bitwise AND on two nodes.
  4191. *
  4192. * @tsl
  4193. * @function
  4194. * @param {Node} a - The first input.
  4195. * @param {Node} b - The second input.
  4196. * @returns {OperatorNode}
  4197. */
  4198. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4199. /**
  4200. * Performs bitwise NOT on a node.
  4201. *
  4202. * @tsl
  4203. * @function
  4204. * @param {Node} a - The first input.
  4205. * @param {Node} b - The second input.
  4206. * @returns {OperatorNode}
  4207. */
  4208. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4209. /**
  4210. * Performs bitwise OR on two nodes.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node} a - The first input.
  4215. * @param {Node} b - The second input.
  4216. * @returns {OperatorNode}
  4217. */
  4218. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4219. /**
  4220. * Performs bitwise XOR on two nodes.
  4221. *
  4222. * @tsl
  4223. * @function
  4224. * @param {Node} a - The first input.
  4225. * @param {Node} b - The second input.
  4226. * @returns {OperatorNode}
  4227. */
  4228. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4229. /**
  4230. * Shifts a node to the left.
  4231. *
  4232. * @tsl
  4233. * @function
  4234. * @param {Node} a - The node to shift.
  4235. * @param {Node} b - The value to shift.
  4236. * @returns {OperatorNode}
  4237. */
  4238. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4239. /**
  4240. * Shifts a node to the right.
  4241. *
  4242. * @tsl
  4243. * @function
  4244. * @param {Node} a - The node to shift.
  4245. * @param {Node} b - The value to shift.
  4246. * @returns {OperatorNode}
  4247. */
  4248. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4249. /**
  4250. * Increments a node by 1.
  4251. *
  4252. * @tsl
  4253. * @function
  4254. * @param {Node} a - The node to increment.
  4255. * @returns {OperatorNode}
  4256. */
  4257. const incrementBefore = Fn( ( [ a ] ) => {
  4258. a.addAssign( 1 );
  4259. return a;
  4260. } );
  4261. /**
  4262. * Decrements a node by 1.
  4263. *
  4264. * @tsl
  4265. * @function
  4266. * @param {Node} a - The node to decrement.
  4267. * @returns {OperatorNode}
  4268. */
  4269. const decrementBefore = Fn( ( [ a ] ) => {
  4270. a.subAssign( 1 );
  4271. return a;
  4272. } );
  4273. /**
  4274. * Increments a node by 1 and returns the previous value.
  4275. *
  4276. * @tsl
  4277. * @function
  4278. * @param {Node} a - The node to increment.
  4279. * @returns {OperatorNode}
  4280. */
  4281. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4282. const temp = int( a ).toConst();
  4283. a.addAssign( 1 );
  4284. return temp;
  4285. } );
  4286. /**
  4287. * Decrements a node by 1 and returns the previous value.
  4288. *
  4289. * @tsl
  4290. * @function
  4291. * @param {Node} a - The node to decrement.
  4292. * @returns {OperatorNode}
  4293. */
  4294. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4295. const temp = int( a ).toConst();
  4296. a.subAssign( 1 );
  4297. return temp;
  4298. } );
  4299. addMethodChaining( 'add', add );
  4300. addMethodChaining( 'sub', sub );
  4301. addMethodChaining( 'mul', mul );
  4302. addMethodChaining( 'div', div );
  4303. addMethodChaining( 'mod', mod );
  4304. addMethodChaining( 'equal', equal );
  4305. addMethodChaining( 'notEqual', notEqual );
  4306. addMethodChaining( 'lessThan', lessThan );
  4307. addMethodChaining( 'greaterThan', greaterThan );
  4308. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4309. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4310. addMethodChaining( 'and', and );
  4311. addMethodChaining( 'or', or );
  4312. addMethodChaining( 'not', not );
  4313. addMethodChaining( 'xor', xor );
  4314. addMethodChaining( 'bitAnd', bitAnd );
  4315. addMethodChaining( 'bitNot', bitNot );
  4316. addMethodChaining( 'bitOr', bitOr );
  4317. addMethodChaining( 'bitXor', bitXor );
  4318. addMethodChaining( 'shiftLeft', shiftLeft );
  4319. addMethodChaining( 'shiftRight', shiftRight );
  4320. addMethodChaining( 'incrementBefore', incrementBefore );
  4321. addMethodChaining( 'decrementBefore', decrementBefore );
  4322. addMethodChaining( 'increment', increment );
  4323. addMethodChaining( 'decrement', decrement );
  4324. /**
  4325. * @tsl
  4326. * @function
  4327. * @deprecated since r175. Use {@link mod} instead.
  4328. *
  4329. * @param {Node} a - The first input.
  4330. * @param {Node} b - The second input.
  4331. * @returns {OperatorNode}
  4332. */
  4333. const modInt = ( a, b ) => { // @deprecated, r175
  4334. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4335. return mod( int( a ), int( b ) );
  4336. };
  4337. addMethodChaining( 'modInt', modInt );
  4338. /**
  4339. * This node represents a variety of mathematical methods available in shaders.
  4340. * They are divided into three categories:
  4341. *
  4342. * - Methods with one input like `sin`, `cos` or `normalize`.
  4343. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4344. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4345. *
  4346. * @augments TempNode
  4347. */
  4348. class MathNode extends TempNode {
  4349. static get type() {
  4350. return 'MathNode';
  4351. }
  4352. /**
  4353. * Constructs a new math node.
  4354. *
  4355. * @param {string} method - The method name.
  4356. * @param {Node} aNode - The first input.
  4357. * @param {?Node} [bNode=null] - The second input.
  4358. * @param {?Node} [cNode=null] - The third input.
  4359. */
  4360. constructor( method, aNode, bNode = null, cNode = null ) {
  4361. super();
  4362. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4363. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4364. let finalOp = new MathNode( method, aNode, bNode );
  4365. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4366. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4367. }
  4368. aNode = finalOp;
  4369. bNode = arguments[ arguments.length - 1 ];
  4370. cNode = null;
  4371. }
  4372. /**
  4373. * The method name.
  4374. *
  4375. * @type {string}
  4376. */
  4377. this.method = method;
  4378. /**
  4379. * The first input.
  4380. *
  4381. * @type {Node}
  4382. */
  4383. this.aNode = aNode;
  4384. /**
  4385. * The second input.
  4386. *
  4387. * @type {?Node}
  4388. * @default null
  4389. */
  4390. this.bNode = bNode;
  4391. /**
  4392. * The third input.
  4393. *
  4394. * @type {?Node}
  4395. * @default null
  4396. */
  4397. this.cNode = cNode;
  4398. /**
  4399. * This flag can be used for type testing.
  4400. *
  4401. * @type {boolean}
  4402. * @readonly
  4403. * @default true
  4404. */
  4405. this.isMathNode = true;
  4406. }
  4407. /**
  4408. * The input type is inferred from the node types of the input nodes.
  4409. *
  4410. * @param {NodeBuilder} builder - The current node builder.
  4411. * @return {string} The input type.
  4412. */
  4413. getInputType( builder ) {
  4414. const aType = this.aNode.getNodeType( builder );
  4415. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4416. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4417. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4418. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4419. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4420. if ( aLen > bLen && aLen > cLen ) {
  4421. return aType;
  4422. } else if ( bLen > cLen ) {
  4423. return bType;
  4424. } else if ( cLen > aLen ) {
  4425. return cType;
  4426. }
  4427. return aType;
  4428. }
  4429. /**
  4430. * The selected method as well as the input type determine the node type of this node.
  4431. *
  4432. * @param {NodeBuilder} builder - The current node builder.
  4433. * @return {string} The node type.
  4434. */
  4435. getNodeType( builder ) {
  4436. const method = this.method;
  4437. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4438. return 'float';
  4439. } else if ( method === MathNode.CROSS ) {
  4440. return 'vec3';
  4441. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4442. return 'bool';
  4443. } else if ( method === MathNode.EQUALS ) {
  4444. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4445. } else {
  4446. return this.getInputType( builder );
  4447. }
  4448. }
  4449. setup( builder ) {
  4450. const { aNode, bNode, method } = this;
  4451. let outputNode = null;
  4452. if ( method === MathNode.ONE_MINUS ) {
  4453. outputNode = sub( 1.0, aNode );
  4454. } else if ( method === MathNode.RECIPROCAL ) {
  4455. outputNode = div( 1.0, aNode );
  4456. } else if ( method === MathNode.DIFFERENCE ) {
  4457. outputNode = abs( sub( aNode, bNode ) );
  4458. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4459. // dir can be either a direction vector or a normal vector
  4460. // upper-left 3x3 of matrix is assumed to be orthogonal
  4461. let tA = aNode;
  4462. let tB = bNode;
  4463. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4464. tB = vec4( vec3( tB ), 0.0 );
  4465. } else {
  4466. tA = vec4( vec3( tA ), 0.0 );
  4467. }
  4468. const mulNode = mul( tA, tB ).xyz;
  4469. outputNode = normalize( mulNode );
  4470. }
  4471. if ( outputNode !== null ) {
  4472. return outputNode;
  4473. } else {
  4474. return super.setup( builder );
  4475. }
  4476. }
  4477. generate( builder, output ) {
  4478. const properties = builder.getNodeProperties( this );
  4479. if ( properties.outputNode ) {
  4480. return super.generate( builder, output );
  4481. }
  4482. let method = this.method;
  4483. const type = this.getNodeType( builder );
  4484. const inputType = this.getInputType( builder );
  4485. const a = this.aNode;
  4486. const b = this.bNode;
  4487. const c = this.cNode;
  4488. const coordinateSystem = builder.renderer.coordinateSystem;
  4489. if ( method === MathNode.NEGATE ) {
  4490. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4491. } else {
  4492. const params = [];
  4493. if ( method === MathNode.CROSS ) {
  4494. params.push(
  4495. a.build( builder, type ),
  4496. b.build( builder, type )
  4497. );
  4498. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4499. params.push(
  4500. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4501. b.build( builder, inputType )
  4502. );
  4503. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4504. params.push(
  4505. a.build( builder, inputType ),
  4506. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4507. );
  4508. } else if ( method === MathNode.REFRACT ) {
  4509. params.push(
  4510. a.build( builder, inputType ),
  4511. b.build( builder, inputType ),
  4512. c.build( builder, 'float' )
  4513. );
  4514. } else if ( method === MathNode.MIX ) {
  4515. params.push(
  4516. a.build( builder, inputType ),
  4517. b.build( builder, inputType ),
  4518. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4519. );
  4520. } else {
  4521. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4522. method = 'atan2';
  4523. }
  4524. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4525. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4526. method = '/*' + method + '*/';
  4527. }
  4528. params.push( a.build( builder, inputType ) );
  4529. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4530. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4531. }
  4532. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4533. }
  4534. }
  4535. serialize( data ) {
  4536. super.serialize( data );
  4537. data.method = this.method;
  4538. }
  4539. deserialize( data ) {
  4540. super.deserialize( data );
  4541. this.method = data.method;
  4542. }
  4543. }
  4544. // 1 input
  4545. MathNode.ALL = 'all';
  4546. MathNode.ANY = 'any';
  4547. MathNode.RADIANS = 'radians';
  4548. MathNode.DEGREES = 'degrees';
  4549. MathNode.EXP = 'exp';
  4550. MathNode.EXP2 = 'exp2';
  4551. MathNode.LOG = 'log';
  4552. MathNode.LOG2 = 'log2';
  4553. MathNode.SQRT = 'sqrt';
  4554. MathNode.INVERSE_SQRT = 'inversesqrt';
  4555. MathNode.FLOOR = 'floor';
  4556. MathNode.CEIL = 'ceil';
  4557. MathNode.NORMALIZE = 'normalize';
  4558. MathNode.FRACT = 'fract';
  4559. MathNode.SIN = 'sin';
  4560. MathNode.COS = 'cos';
  4561. MathNode.TAN = 'tan';
  4562. MathNode.ASIN = 'asin';
  4563. MathNode.ACOS = 'acos';
  4564. MathNode.ATAN = 'atan';
  4565. MathNode.ABS = 'abs';
  4566. MathNode.SIGN = 'sign';
  4567. MathNode.LENGTH = 'length';
  4568. MathNode.NEGATE = 'negate';
  4569. MathNode.ONE_MINUS = 'oneMinus';
  4570. MathNode.DFDX = 'dFdx';
  4571. MathNode.DFDY = 'dFdy';
  4572. MathNode.ROUND = 'round';
  4573. MathNode.RECIPROCAL = 'reciprocal';
  4574. MathNode.TRUNC = 'trunc';
  4575. MathNode.FWIDTH = 'fwidth';
  4576. MathNode.TRANSPOSE = 'transpose';
  4577. MathNode.DETERMINANT = 'determinant';
  4578. MathNode.INVERSE = 'inverse';
  4579. // 2 inputs
  4580. MathNode.EQUALS = 'equals';
  4581. MathNode.MIN = 'min';
  4582. MathNode.MAX = 'max';
  4583. MathNode.STEP = 'step';
  4584. MathNode.REFLECT = 'reflect';
  4585. MathNode.DISTANCE = 'distance';
  4586. MathNode.DIFFERENCE = 'difference';
  4587. MathNode.DOT = 'dot';
  4588. MathNode.CROSS = 'cross';
  4589. MathNode.POW = 'pow';
  4590. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4591. // 3 inputs
  4592. MathNode.MIX = 'mix';
  4593. MathNode.CLAMP = 'clamp';
  4594. MathNode.REFRACT = 'refract';
  4595. MathNode.SMOOTHSTEP = 'smoothstep';
  4596. MathNode.FACEFORWARD = 'faceforward';
  4597. // 1 inputs
  4598. /**
  4599. * A small value used to handle floating-point precision errors.
  4600. *
  4601. * @tsl
  4602. * @type {Node<float>}
  4603. */
  4604. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4605. /**
  4606. * Represents infinity.
  4607. *
  4608. * @tsl
  4609. * @type {Node<float>}
  4610. */
  4611. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4612. /**
  4613. * Represents PI.
  4614. *
  4615. * @tsl
  4616. * @type {Node<float>}
  4617. */
  4618. const PI = /*@__PURE__*/ float( Math.PI );
  4619. /**
  4620. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4621. *
  4622. * @tsl
  4623. * @deprecated
  4624. * @type {Node<float>}
  4625. */
  4626. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4627. /**
  4628. * Represents PI * 2.
  4629. *
  4630. * @tsl
  4631. * @type {Node<float>}
  4632. */
  4633. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4634. /**
  4635. * Represents PI / 2.
  4636. *
  4637. * @tsl
  4638. * @type {Node<float>}
  4639. */
  4640. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4641. /**
  4642. * Returns `true` if all components of `x` are `true`.
  4643. *
  4644. * @tsl
  4645. * @function
  4646. * @param {Node | number} x - The parameter.
  4647. * @returns {Node<bool>}
  4648. */
  4649. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4650. /**
  4651. * Returns `true` if any components of `x` are `true`.
  4652. *
  4653. * @tsl
  4654. * @function
  4655. * @param {Node | number} x - The parameter.
  4656. * @returns {Node<bool>}
  4657. */
  4658. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4659. /**
  4660. * Converts a quantity in degrees to radians.
  4661. *
  4662. * @tsl
  4663. * @function
  4664. * @param {Node | number} x - The input in degrees.
  4665. * @returns {Node}
  4666. */
  4667. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4668. /**
  4669. * Convert a quantity in radians to degrees.
  4670. *
  4671. * @tsl
  4672. * @function
  4673. * @param {Node | number} x - The input in radians.
  4674. * @returns {Node}
  4675. */
  4676. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4677. /**
  4678. * Returns the natural exponentiation of the parameter.
  4679. *
  4680. * @tsl
  4681. * @function
  4682. * @param {Node | number} x - The parameter.
  4683. * @returns {Node}
  4684. */
  4685. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4686. /**
  4687. * Returns 2 raised to the power of the parameter.
  4688. *
  4689. * @tsl
  4690. * @function
  4691. * @param {Node | number} x - The parameter.
  4692. * @returns {Node}
  4693. */
  4694. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4695. /**
  4696. * Returns the natural logarithm of the parameter.
  4697. *
  4698. * @tsl
  4699. * @function
  4700. * @param {Node | number} x - The parameter.
  4701. * @returns {Node}
  4702. */
  4703. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4704. /**
  4705. * Returns the base 2 logarithm of the parameter.
  4706. *
  4707. * @tsl
  4708. * @function
  4709. * @param {Node | number} x - The parameter.
  4710. * @returns {Node}
  4711. */
  4712. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4713. /**
  4714. * Returns the square root of the parameter.
  4715. *
  4716. * @tsl
  4717. * @function
  4718. * @param {Node | number} x - The parameter.
  4719. * @returns {Node}
  4720. */
  4721. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4722. /**
  4723. * Returns the inverse of the square root of the parameter.
  4724. *
  4725. * @tsl
  4726. * @function
  4727. * @param {Node | number} x - The parameter.
  4728. * @returns {Node}
  4729. */
  4730. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4731. /**
  4732. * Finds the nearest integer less than or equal to the parameter.
  4733. *
  4734. * @tsl
  4735. * @function
  4736. * @param {Node | number} x - The parameter.
  4737. * @returns {Node}
  4738. */
  4739. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4740. /**
  4741. * Finds the nearest integer that is greater than or equal to the parameter.
  4742. *
  4743. * @tsl
  4744. * @function
  4745. * @param {Node | number} x - The parameter.
  4746. * @returns {Node}
  4747. */
  4748. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4749. /**
  4750. * Calculates the unit vector in the same direction as the original vector.
  4751. *
  4752. * @tsl
  4753. * @function
  4754. * @param {Node} x - The input vector.
  4755. * @returns {Node}
  4756. */
  4757. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4758. /**
  4759. * Computes the fractional part of the parameter.
  4760. *
  4761. * @tsl
  4762. * @function
  4763. * @param {Node | number} x - The parameter.
  4764. * @returns {Node}
  4765. */
  4766. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4767. /**
  4768. * Returns the sine of the parameter.
  4769. *
  4770. * @tsl
  4771. * @function
  4772. * @param {Node | number} x - The parameter.
  4773. * @returns {Node}
  4774. */
  4775. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4776. /**
  4777. * Returns the cosine of the parameter.
  4778. *
  4779. * @tsl
  4780. * @function
  4781. * @param {Node | number} x - The parameter.
  4782. * @returns {Node}
  4783. */
  4784. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4785. /**
  4786. * Returns the tangent of the parameter.
  4787. *
  4788. * @tsl
  4789. * @function
  4790. * @param {Node | number} x - The parameter.
  4791. * @returns {Node}
  4792. */
  4793. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4794. /**
  4795. * Returns the arcsine of the parameter.
  4796. *
  4797. * @tsl
  4798. * @function
  4799. * @param {Node | number} x - The parameter.
  4800. * @returns {Node}
  4801. */
  4802. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4803. /**
  4804. * Returns the arccosine of the parameter.
  4805. *
  4806. * @tsl
  4807. * @function
  4808. * @param {Node | number} x - The parameter.
  4809. * @returns {Node}
  4810. */
  4811. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4812. /**
  4813. * Returns the arc-tangent of the parameter.
  4814. * If two parameters are provided, the result is `atan2(y/x)`.
  4815. *
  4816. * @tsl
  4817. * @function
  4818. * @param {Node | number} y - The y parameter.
  4819. * @param {?(Node | number)} x - The x parameter.
  4820. * @returns {Node}
  4821. */
  4822. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4823. /**
  4824. * Returns the absolute value of the parameter.
  4825. *
  4826. * @tsl
  4827. * @function
  4828. * @param {Node | number} x - The parameter.
  4829. * @returns {Node}
  4830. */
  4831. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4832. /**
  4833. * Extracts the sign of the parameter.
  4834. *
  4835. * @tsl
  4836. * @function
  4837. * @param {Node | number} x - The parameter.
  4838. * @returns {Node}
  4839. */
  4840. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4841. /**
  4842. * Calculates the length of a vector.
  4843. *
  4844. * @tsl
  4845. * @function
  4846. * @param {Node} x - The parameter.
  4847. * @returns {Node<float>}
  4848. */
  4849. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4850. /**
  4851. * Negates the value of the parameter (-x).
  4852. *
  4853. * @tsl
  4854. * @function
  4855. * @param {Node | number} x - The parameter.
  4856. * @returns {Node}
  4857. */
  4858. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4859. /**
  4860. * Return `1` minus the parameter.
  4861. *
  4862. * @tsl
  4863. * @function
  4864. * @param {Node | number} x - The parameter.
  4865. * @returns {Node}
  4866. */
  4867. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4868. /**
  4869. * Returns the partial derivative of the parameter with respect to x.
  4870. *
  4871. * @tsl
  4872. * @function
  4873. * @param {Node | number} x - The parameter.
  4874. * @returns {Node}
  4875. */
  4876. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4877. /**
  4878. * Returns the partial derivative of the parameter with respect to y.
  4879. *
  4880. * @tsl
  4881. * @function
  4882. * @param {Node | number} x - The parameter.
  4883. * @returns {Node}
  4884. */
  4885. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4886. /**
  4887. * Rounds the parameter to the nearest integer.
  4888. *
  4889. * @tsl
  4890. * @function
  4891. * @param {Node | number} x - The parameter.
  4892. * @returns {Node}
  4893. */
  4894. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4895. /**
  4896. * Returns the reciprocal of the parameter `(1/x)`.
  4897. *
  4898. * @tsl
  4899. * @function
  4900. * @param {Node | number} x - The parameter.
  4901. * @returns {Node}
  4902. */
  4903. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4904. /**
  4905. * Truncates the parameter, removing the fractional part.
  4906. *
  4907. * @tsl
  4908. * @function
  4909. * @param {Node | number} x - The parameter.
  4910. * @returns {Node}
  4911. */
  4912. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4913. /**
  4914. * Returns the sum of the absolute derivatives in x and y.
  4915. *
  4916. * @tsl
  4917. * @function
  4918. * @param {Node | number} x - The parameter.
  4919. * @returns {Node}
  4920. */
  4921. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4922. /**
  4923. * Returns the transpose of a matrix.
  4924. *
  4925. * @tsl
  4926. * @function
  4927. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4928. * @returns {Node}
  4929. */
  4930. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4931. /**
  4932. * Returns the determinant of a matrix.
  4933. *
  4934. * @tsl
  4935. * @function
  4936. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4937. * @returns {Node<float>}
  4938. */
  4939. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4940. /**
  4941. * Returns the inverse of a matrix.
  4942. *
  4943. * @tsl
  4944. * @function
  4945. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4946. * @returns {Node<mat2|mat3|mat4>}
  4947. */
  4948. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4949. // 2 inputs
  4950. /**
  4951. * Returns `true` if `x` equals `y`.
  4952. *
  4953. * @tsl
  4954. * @function
  4955. * @param {Node | number} x - The first parameter.
  4956. * @param {Node | number} y - The second parameter.
  4957. * @deprecated since r175. Use {@link equal} instead.
  4958. * @returns {Node<bool>}
  4959. */
  4960. const equals = ( x, y ) => { // @deprecated, r172
  4961. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4962. return equal( x, y );
  4963. };
  4964. /**
  4965. * Returns the least of the given values.
  4966. *
  4967. * @tsl
  4968. * @function
  4969. * @param {...(Node | number)} values - The values to compare.
  4970. * @returns {Node}
  4971. */
  4972. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4973. /**
  4974. * Returns the greatest of the given values.
  4975. *
  4976. * @tsl
  4977. * @function
  4978. * @param {...(Node | number)} values - The values to compare.
  4979. * @returns {Node}
  4980. */
  4981. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4982. /**
  4983. * Generate a step function by comparing two values.
  4984. *
  4985. * @tsl
  4986. * @function
  4987. * @param {Node | number} x - The y parameter.
  4988. * @param {Node | number} y - The x parameter.
  4989. * @returns {Node}
  4990. */
  4991. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4992. /**
  4993. * Calculates the reflection direction for an incident vector.
  4994. *
  4995. * @tsl
  4996. * @function
  4997. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4998. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4999. * @returns {Node<vec2|vec3|vec4>}
  5000. */
  5001. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5002. /**
  5003. * Calculates the distance between two points.
  5004. *
  5005. * @tsl
  5006. * @function
  5007. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5008. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5009. * @returns {Node<float>}
  5010. */
  5011. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5012. /**
  5013. * Calculates the absolute difference between two values.
  5014. *
  5015. * @tsl
  5016. * @function
  5017. * @param {Node | number} x - The first parameter.
  5018. * @param {Node | number} y - The second parameter.
  5019. * @returns {Node}
  5020. */
  5021. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5022. /**
  5023. * Calculates the dot product of two vectors.
  5024. *
  5025. * @tsl
  5026. * @function
  5027. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5028. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5029. * @returns {Node<float>}
  5030. */
  5031. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5032. /**
  5033. * Calculates the cross product of two vectors.
  5034. *
  5035. * @tsl
  5036. * @function
  5037. * @param {Node<vec2|vec3>} x - The first vector.
  5038. * @param {Node<vec2|vec3>} y - The second vector.
  5039. * @returns {Node<float|vec3>}
  5040. */
  5041. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5042. /**
  5043. * Return the value of the first parameter raised to the power of the second one.
  5044. *
  5045. * @tsl
  5046. * @function
  5047. * @param {Node | number} x - The first parameter.
  5048. * @param {Node | number} y - The second parameter.
  5049. * @returns {Node}
  5050. */
  5051. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5052. /**
  5053. * Returns the square of the parameter.
  5054. *
  5055. * @tsl
  5056. * @function
  5057. * @param {Node | number} x - The first parameter.
  5058. * @returns {Node}
  5059. */
  5060. const pow2 = ( x ) => mul( x, x );
  5061. /**
  5062. * Returns the cube of the parameter.
  5063. *
  5064. * @tsl
  5065. * @function
  5066. * @param {Node | number} x - The first parameter.
  5067. * @returns {Node}
  5068. */
  5069. const pow3 = ( x ) => mul( x, x, x );
  5070. /**
  5071. * Returns the fourth power of the parameter.
  5072. *
  5073. * @tsl
  5074. * @function
  5075. * @param {Node | number} x - The first parameter.
  5076. * @returns {Node}
  5077. */
  5078. const pow4 = ( x ) => mul( x, x, x, x );
  5079. /**
  5080. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5081. *
  5082. * @tsl
  5083. * @function
  5084. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5085. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5086. * @returns {Node}
  5087. */
  5088. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5089. /**
  5090. * Returns the cube root of a number.
  5091. *
  5092. * @tsl
  5093. * @function
  5094. * @param {Node | number} a - The first parameter.
  5095. * @returns {Node}
  5096. */
  5097. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5098. /**
  5099. * Calculate the squared length of a vector.
  5100. *
  5101. * @tsl
  5102. * @function
  5103. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5104. * @returns {Node<float>}
  5105. */
  5106. const lengthSq = ( a ) => dot( a, a );
  5107. /**
  5108. * Linearly interpolates between two values.
  5109. *
  5110. * @tsl
  5111. * @function
  5112. * @param {Node | number} a - The first parameter.
  5113. * @param {Node | number} b - The second parameter.
  5114. * @param {Node | number} t - The interpolation value.
  5115. * @returns {Node}
  5116. */
  5117. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5118. /**
  5119. * Constrains a value to lie between two further values.
  5120. *
  5121. * @tsl
  5122. * @function
  5123. * @param {Node | number} value - The value to constrain.
  5124. * @param {Node | number} [low=0] - The lower bound.
  5125. * @param {Node | number} [high=1] - The upper bound.
  5126. * @returns {Node}
  5127. */
  5128. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5129. /**
  5130. * Constrains a value between `0` and `1`.
  5131. *
  5132. * @tsl
  5133. * @function
  5134. * @param {Node | number} value - The value to constrain.
  5135. * @returns {Node}
  5136. */
  5137. const saturate = ( value ) => clamp( value );
  5138. /**
  5139. * Calculates the refraction direction for an incident vector.
  5140. *
  5141. * @tsl
  5142. * @function
  5143. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5144. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5145. * @param {Node<float>} eta - The ratio of indices of refraction.
  5146. * @returns {Node<vec2|vec3|vec4>}
  5147. */
  5148. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5149. /**
  5150. * Performs a Hermite interpolation between two values.
  5151. *
  5152. * @tsl
  5153. * @function
  5154. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5155. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5156. * @param {Node | number} x - The source value for interpolation.
  5157. * @returns {Node}
  5158. */
  5159. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5160. /**
  5161. * Returns a vector pointing in the same direction as another.
  5162. *
  5163. * @tsl
  5164. * @function
  5165. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5166. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5167. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5168. * @returns {Node<vec2|vec3|vec4>}
  5169. */
  5170. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5171. /**
  5172. * Returns a random value for the given uv.
  5173. *
  5174. * @tsl
  5175. * @function
  5176. * @param {Node<vec2>} uv - The uv node.
  5177. * @returns {Node<float>}
  5178. */
  5179. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5180. const a = 12.9898, b = 78.233, c = 43758.5453;
  5181. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5182. return fract( sin( sn ).mul( c ) );
  5183. } );
  5184. /**
  5185. * Alias for `mix()` with a different parameter order.
  5186. *
  5187. * @tsl
  5188. * @function
  5189. * @param {Node | number} t - The interpolation value.
  5190. * @param {Node | number} e1 - The first parameter.
  5191. * @param {Node | number} e2 - The second parameter.
  5192. * @returns {Node}
  5193. */
  5194. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5195. /**
  5196. * Alias for `smoothstep()` with a different parameter order.
  5197. *
  5198. * @tsl
  5199. * @function
  5200. * @param {Node | number} x - The source value for interpolation.
  5201. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5202. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5203. * @returns {Node}
  5204. */
  5205. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5206. /**
  5207. * Alias for `step()` with a different parameter order.
  5208. *
  5209. * @tsl
  5210. * @function
  5211. * @param {Node | number} x - The source value for interpolation.
  5212. * @param {Node | number} edge - The edge value.
  5213. * @returns {Node}
  5214. */
  5215. const stepElement = ( x, edge ) => step( edge, x );
  5216. /**
  5217. * Returns the arc-tangent of the quotient of its parameters.
  5218. *
  5219. * @tsl
  5220. * @function
  5221. * @deprecated since r172. Use {@link atan} instead.
  5222. *
  5223. * @param {Node | number} y - The y parameter.
  5224. * @param {Node | number} x - The x parameter.
  5225. * @returns {Node}
  5226. */
  5227. const atan2 = ( y, x ) => { // @deprecated, r172
  5228. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5229. return atan( y, x );
  5230. };
  5231. // GLSL alias function
  5232. const faceforward = faceForward;
  5233. const inversesqrt = inverseSqrt;
  5234. // Method chaining
  5235. addMethodChaining( 'all', all );
  5236. addMethodChaining( 'any', any );
  5237. addMethodChaining( 'equals', equals );
  5238. addMethodChaining( 'radians', radians );
  5239. addMethodChaining( 'degrees', degrees );
  5240. addMethodChaining( 'exp', exp );
  5241. addMethodChaining( 'exp2', exp2 );
  5242. addMethodChaining( 'log', log );
  5243. addMethodChaining( 'log2', log2 );
  5244. addMethodChaining( 'sqrt', sqrt );
  5245. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5246. addMethodChaining( 'floor', floor );
  5247. addMethodChaining( 'ceil', ceil );
  5248. addMethodChaining( 'normalize', normalize );
  5249. addMethodChaining( 'fract', fract );
  5250. addMethodChaining( 'sin', sin );
  5251. addMethodChaining( 'cos', cos );
  5252. addMethodChaining( 'tan', tan );
  5253. addMethodChaining( 'asin', asin );
  5254. addMethodChaining( 'acos', acos );
  5255. addMethodChaining( 'atan', atan );
  5256. addMethodChaining( 'abs', abs );
  5257. addMethodChaining( 'sign', sign );
  5258. addMethodChaining( 'length', length );
  5259. addMethodChaining( 'lengthSq', lengthSq );
  5260. addMethodChaining( 'negate', negate );
  5261. addMethodChaining( 'oneMinus', oneMinus );
  5262. addMethodChaining( 'dFdx', dFdx );
  5263. addMethodChaining( 'dFdy', dFdy );
  5264. addMethodChaining( 'round', round );
  5265. addMethodChaining( 'reciprocal', reciprocal );
  5266. addMethodChaining( 'trunc', trunc );
  5267. addMethodChaining( 'fwidth', fwidth );
  5268. addMethodChaining( 'atan2', atan2 );
  5269. addMethodChaining( 'min', min$1 );
  5270. addMethodChaining( 'max', max$1 );
  5271. addMethodChaining( 'step', stepElement );
  5272. addMethodChaining( 'reflect', reflect );
  5273. addMethodChaining( 'distance', distance );
  5274. addMethodChaining( 'dot', dot );
  5275. addMethodChaining( 'cross', cross );
  5276. addMethodChaining( 'pow', pow );
  5277. addMethodChaining( 'pow2', pow2 );
  5278. addMethodChaining( 'pow3', pow3 );
  5279. addMethodChaining( 'pow4', pow4 );
  5280. addMethodChaining( 'transformDirection', transformDirection );
  5281. addMethodChaining( 'mix', mixElement );
  5282. addMethodChaining( 'clamp', clamp );
  5283. addMethodChaining( 'refract', refract );
  5284. addMethodChaining( 'smoothstep', smoothstepElement );
  5285. addMethodChaining( 'faceForward', faceForward );
  5286. addMethodChaining( 'difference', difference );
  5287. addMethodChaining( 'saturate', saturate );
  5288. addMethodChaining( 'cbrt', cbrt );
  5289. addMethodChaining( 'transpose', transpose );
  5290. addMethodChaining( 'determinant', determinant );
  5291. addMethodChaining( 'inverse', inverse );
  5292. addMethodChaining( 'rand', rand );
  5293. /**
  5294. * Represents a logical `if/else` statement. Can be used as an alternative
  5295. * to the `If()`/`Else()` syntax.
  5296. *
  5297. * The corresponding TSL `select()` looks like so:
  5298. * ```js
  5299. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5300. * ```
  5301. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5302. * determine the outcome of the entire statement.
  5303. *
  5304. * @augments Node
  5305. */
  5306. class ConditionalNode extends Node {
  5307. static get type() {
  5308. return 'ConditionalNode';
  5309. }
  5310. /**
  5311. * Constructs a new conditional node.
  5312. *
  5313. * @param {Node} condNode - The node that defines the condition.
  5314. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5315. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5316. */
  5317. constructor( condNode, ifNode, elseNode = null ) {
  5318. super();
  5319. /**
  5320. * The node that defines the condition.
  5321. *
  5322. * @type {Node}
  5323. */
  5324. this.condNode = condNode;
  5325. /**
  5326. * The node that is evaluate when the condition ends up `true`.
  5327. *
  5328. * @type {Node}
  5329. */
  5330. this.ifNode = ifNode;
  5331. /**
  5332. * The node that is evaluate when the condition ends up `false`.
  5333. *
  5334. * @type {?Node}
  5335. * @default null
  5336. */
  5337. this.elseNode = elseNode;
  5338. }
  5339. /**
  5340. * This method is overwritten since the node type is inferred from the if/else
  5341. * nodes.
  5342. *
  5343. * @param {NodeBuilder} builder - The current node builder.
  5344. * @return {string} The node type.
  5345. */
  5346. getNodeType( builder ) {
  5347. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5348. if ( ifNode === undefined ) {
  5349. // fallback setup
  5350. builder.flowBuildStage( this, 'setup' );
  5351. return this.getNodeType( builder );
  5352. }
  5353. const ifType = ifNode.getNodeType( builder );
  5354. if ( elseNode !== null ) {
  5355. const elseType = elseNode.getNodeType( builder );
  5356. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5357. return elseType;
  5358. }
  5359. }
  5360. return ifType;
  5361. }
  5362. setup( builder ) {
  5363. const condNode = this.condNode;
  5364. const ifNode = this.ifNode.isolate();
  5365. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5366. //
  5367. const currentNodeBlock = builder.context.nodeBlock;
  5368. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5369. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5370. //
  5371. const isUniformFlow = builder.context.uniformFlow;
  5372. const properties = builder.getNodeProperties( this );
  5373. properties.condNode = condNode;
  5374. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5375. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5376. }
  5377. generate( builder, output ) {
  5378. const type = this.getNodeType( builder );
  5379. const nodeData = builder.getDataFromNode( this );
  5380. if ( nodeData.nodeProperty !== undefined ) {
  5381. return nodeData.nodeProperty;
  5382. }
  5383. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5384. const functionNode = builder.currentFunctionNode;
  5385. const needsOutput = output !== 'void';
  5386. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5387. nodeData.nodeProperty = nodeProperty;
  5388. const nodeSnippet = condNode.build( builder, 'bool' );
  5389. const isUniformFlow = builder.context.uniformFlow;
  5390. if ( isUniformFlow && elseNode !== null ) {
  5391. const ifSnippet = ifNode.build( builder, type );
  5392. const elseSnippet = elseNode.build( builder, type );
  5393. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5394. // TODO: If node property already exists return something else
  5395. return builder.format( mathSnippet, type, output );
  5396. }
  5397. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5398. let ifSnippet = ifNode.build( builder, type );
  5399. if ( ifSnippet ) {
  5400. if ( needsOutput ) {
  5401. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5402. } else {
  5403. ifSnippet = 'return ' + ifSnippet + ';';
  5404. if ( functionNode === null ) {
  5405. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5406. ifSnippet = '// ' + ifSnippet;
  5407. }
  5408. }
  5409. }
  5410. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5411. if ( elseNode !== null ) {
  5412. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5413. let elseSnippet = elseNode.build( builder, type );
  5414. if ( elseSnippet ) {
  5415. if ( needsOutput ) {
  5416. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5417. } else {
  5418. elseSnippet = 'return ' + elseSnippet + ';';
  5419. if ( functionNode === null ) {
  5420. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5421. elseSnippet = '// ' + elseSnippet;
  5422. }
  5423. }
  5424. }
  5425. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5426. } else {
  5427. builder.addFlowCode( '\n\n' );
  5428. }
  5429. return builder.format( nodeProperty, type, output );
  5430. }
  5431. }
  5432. /**
  5433. * TSL function for creating a conditional node.
  5434. *
  5435. * @tsl
  5436. * @function
  5437. * @param {Node} condNode - The node that defines the condition.
  5438. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5439. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5440. * @returns {ConditionalNode}
  5441. */
  5442. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5443. addMethodChaining( 'select', select );
  5444. /**
  5445. * This node can be used as a context management component for another node.
  5446. * {@link NodeBuilder} performs its node building process in a specific context and
  5447. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5448. *
  5449. * ```js
  5450. *node.context( { getUV: () => customCoord } );
  5451. *```
  5452. * @augments Node
  5453. */
  5454. class ContextNode extends Node {
  5455. static get type() {
  5456. return 'ContextNode';
  5457. }
  5458. /**
  5459. * Constructs a new context node.
  5460. *
  5461. * @param {Node} node - The node whose context should be modified.
  5462. * @param {Object} [value={}] - The modified context data.
  5463. */
  5464. constructor( node, value = {} ) {
  5465. super();
  5466. /**
  5467. * This flag can be used for type testing.
  5468. *
  5469. * @type {boolean}
  5470. * @readonly
  5471. * @default true
  5472. */
  5473. this.isContextNode = true;
  5474. /**
  5475. * The node whose context should be modified.
  5476. *
  5477. * @type {Node}
  5478. */
  5479. this.node = node;
  5480. /**
  5481. * The modified context data.
  5482. *
  5483. * @type {Object}
  5484. * @default {}
  5485. */
  5486. this.value = value;
  5487. }
  5488. /**
  5489. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5490. *
  5491. * @return {Node} A reference to {@link ContextNode#node}.
  5492. */
  5493. getScope() {
  5494. return this.node.getScope();
  5495. }
  5496. /**
  5497. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5498. *
  5499. * @param {NodeBuilder} builder - The current node builder.
  5500. * @return {string} The node type.
  5501. */
  5502. getNodeType( builder ) {
  5503. return this.node.getNodeType( builder );
  5504. }
  5505. /**
  5506. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5507. *
  5508. * @param {NodeBuilder} builder - The current node builder.
  5509. * @param {string} name - The member name.
  5510. * @returns {string} The member type.
  5511. */
  5512. getMemberType( builder, name ) {
  5513. return this.node.getMemberType( builder, name );
  5514. }
  5515. analyze( builder ) {
  5516. const previousContext = builder.addContext( this.value );
  5517. this.node.build( builder );
  5518. builder.setContext( previousContext );
  5519. }
  5520. setup( builder ) {
  5521. const previousContext = builder.addContext( this.value );
  5522. this.node.build( builder );
  5523. builder.setContext( previousContext );
  5524. }
  5525. generate( builder, output ) {
  5526. const previousContext = builder.addContext( this.value );
  5527. const snippet = this.node.build( builder, output );
  5528. builder.setContext( previousContext );
  5529. return snippet;
  5530. }
  5531. }
  5532. /**
  5533. * TSL function for creating a context node.
  5534. *
  5535. * @tsl
  5536. * @function
  5537. * @param {Node} node - The node whose context should be modified.
  5538. * @param {Object} [value={}] - The modified context data.
  5539. * @returns {ContextNode}
  5540. */
  5541. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5542. /**
  5543. * TSL function for defining a uniformFlow context value for a given node.
  5544. *
  5545. * @tsl
  5546. * @function
  5547. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5548. * @returns {ContextNode}
  5549. */
  5550. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5551. /**
  5552. * TSL function for defining a name for the context value for a given node.
  5553. *
  5554. * @tsl
  5555. * @function
  5556. * @param {Node} node - The node whose context should be modified.
  5557. * @param {string} name - The name to set.
  5558. * @returns {ContextNode}
  5559. */
  5560. const setName = ( node, name ) => context( node, { nodeName: name } );
  5561. /**
  5562. * TSL function for defining a label context value for a given node.
  5563. *
  5564. * @tsl
  5565. * @function
  5566. * @deprecated
  5567. * @param {Node} node - The node whose context should be modified.
  5568. * @param {string} name - The name/label to set.
  5569. * @returns {ContextNode}
  5570. */
  5571. function label( node, name ) {
  5572. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5573. return setName( node, name );
  5574. }
  5575. addMethodChaining( 'context', context );
  5576. addMethodChaining( 'label', label );
  5577. addMethodChaining( 'uniformFlow', uniformFlow );
  5578. addMethodChaining( 'setName', setName );
  5579. /**
  5580. * Class for representing shader variables as nodes. Variables are created from
  5581. * existing nodes like the following:
  5582. *
  5583. * ```js
  5584. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5585. * ```
  5586. *
  5587. * @augments Node
  5588. */
  5589. class VarNode extends Node {
  5590. static get type() {
  5591. return 'VarNode';
  5592. }
  5593. /**
  5594. * Constructs a new variable node.
  5595. *
  5596. * @param {Node} node - The node for which a variable should be created.
  5597. * @param {?string} [name=null] - The name of the variable in the shader.
  5598. * @param {boolean} [readOnly=false] - The read-only flag.
  5599. */
  5600. constructor( node, name = null, readOnly = false ) {
  5601. super();
  5602. /**
  5603. * The node for which a variable should be created.
  5604. *
  5605. * @type {Node}
  5606. */
  5607. this.node = node;
  5608. /**
  5609. * The name of the variable in the shader. If no name is defined,
  5610. * the node system auto-generates one.
  5611. *
  5612. * @type {?string}
  5613. * @default null
  5614. */
  5615. this.name = name;
  5616. /**
  5617. * `VarNode` sets this property to `true` by default.
  5618. *
  5619. * @type {boolean}
  5620. * @default true
  5621. */
  5622. this.global = true;
  5623. /**
  5624. * This flag can be used for type testing.
  5625. *
  5626. * @type {boolean}
  5627. * @readonly
  5628. * @default true
  5629. */
  5630. this.isVarNode = true;
  5631. /**
  5632. *
  5633. * The read-only flag.
  5634. *
  5635. * @type {boolean}
  5636. * @default false
  5637. */
  5638. this.readOnly = readOnly;
  5639. /**
  5640. *
  5641. * Add this flag to the node system to indicate that this node require parents.
  5642. *
  5643. * @type {boolean}
  5644. * @default true
  5645. */
  5646. this.parents = true;
  5647. /**
  5648. * This flag is used to indicate that this node is used for intent.
  5649. *
  5650. * @type {boolean}
  5651. * @default false
  5652. */
  5653. this.intent = false;
  5654. }
  5655. /**
  5656. * Sets the intent flag for this node.
  5657. *
  5658. * This flag is used to indicate that this node is used for intent
  5659. * and should not be built directly. Instead, it is used to indicate that
  5660. * the node should be treated as a variable intent.
  5661. *
  5662. * It's useful for assigning variables without needing creating a new variable node.
  5663. *
  5664. * @param {boolean} value - The value to set for the intent flag.
  5665. * @returns {VarNode} This node.
  5666. */
  5667. setIntent( value ) {
  5668. this.intent = value;
  5669. return this;
  5670. }
  5671. /**
  5672. * Returns the intent flag of this node.
  5673. *
  5674. * @return {boolean} The intent flag.
  5675. */
  5676. getIntent() {
  5677. return this.intent;
  5678. }
  5679. getMemberType( builder, name ) {
  5680. return this.node.getMemberType( builder, name );
  5681. }
  5682. getElementType( builder ) {
  5683. return this.node.getElementType( builder );
  5684. }
  5685. getNodeType( builder ) {
  5686. return this.node.getNodeType( builder );
  5687. }
  5688. getArrayCount( builder ) {
  5689. return this.node.getArrayCount( builder );
  5690. }
  5691. isAssign( builder ) {
  5692. const properties = builder.getNodeProperties( this );
  5693. let assign = properties.assign;
  5694. if ( assign !== true ) {
  5695. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5696. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5697. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5698. if ( shaderNodeData.hasLoop ) {
  5699. assign = true;
  5700. }
  5701. }
  5702. }
  5703. }
  5704. return assign;
  5705. }
  5706. build( ...params ) {
  5707. if ( this.intent === true ) {
  5708. const builder = params[ 0 ];
  5709. if ( this.isAssign( builder ) !== true ) {
  5710. return this.node.build( ...params );
  5711. }
  5712. }
  5713. return super.build( ...params );
  5714. }
  5715. generate( builder ) {
  5716. const { node, name, readOnly } = this;
  5717. const { renderer } = builder;
  5718. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5719. let isDeterministic = false;
  5720. let shouldTreatAsReadOnly = false;
  5721. if ( readOnly ) {
  5722. isDeterministic = builder.isDeterministic( node );
  5723. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5724. }
  5725. const nodeType = this.getNodeType( builder );
  5726. if ( nodeType == 'void' ) {
  5727. if ( this.intent !== true ) {
  5728. error( 'TSL: ".toVar()" can not be used with void type.' );
  5729. }
  5730. const snippet = node.build( builder );
  5731. return snippet;
  5732. }
  5733. const vectorType = builder.getVectorType( nodeType );
  5734. const snippet = node.build( builder, vectorType );
  5735. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5736. const propertyName = builder.getPropertyName( nodeVar );
  5737. let declarationPrefix = propertyName;
  5738. if ( shouldTreatAsReadOnly ) {
  5739. if ( isWebGPUBackend ) {
  5740. declarationPrefix = isDeterministic
  5741. ? `const ${ propertyName }`
  5742. : `let ${ propertyName }`;
  5743. } else {
  5744. const count = node.getArrayCount( builder );
  5745. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5746. }
  5747. }
  5748. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5749. return propertyName;
  5750. }
  5751. }
  5752. /**
  5753. * TSL function for creating a var node.
  5754. *
  5755. * @tsl
  5756. * @function
  5757. * @param {Node} node - The node for which a variable should be created.
  5758. * @param {?string} name - The name of the variable in the shader.
  5759. * @returns {VarNode}
  5760. */
  5761. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5762. /**
  5763. * TSL function for creating a var node.
  5764. *
  5765. * @tsl
  5766. * @function
  5767. * @param {Node} node - The node for which a variable should be created.
  5768. * @param {?string} name - The name of the variable in the shader.
  5769. * @returns {VarNode}
  5770. */
  5771. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5772. /**
  5773. * TSL function for creating a const node.
  5774. *
  5775. * @tsl
  5776. * @function
  5777. * @param {Node} node - The node for which a constant should be created.
  5778. * @param {?string} name - The name of the constant in the shader.
  5779. * @returns {VarNode}
  5780. */
  5781. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5782. //
  5783. //
  5784. /**
  5785. * TSL function for creating a var intent node.
  5786. *
  5787. * @tsl
  5788. * @function
  5789. * @param {Node} node - The node for which a variable should be created.
  5790. * @param {?string} name - The name of the variable in the shader.
  5791. * @returns {VarNode}
  5792. */
  5793. const VarIntent = ( node ) => {
  5794. if ( getCurrentStack() === null ) {
  5795. return node;
  5796. }
  5797. return createVar( node ).setIntent( true ).toStack();
  5798. };
  5799. // Method chaining
  5800. addMethodChaining( 'toVar', Var );
  5801. addMethodChaining( 'toConst', Const );
  5802. addMethodChaining( 'toVarIntent', VarIntent );
  5803. /**
  5804. * This node is used to build a sub-build in the node system.
  5805. *
  5806. * @augments Node
  5807. * @param {Node} node - The node to be built in the sub-build.
  5808. * @param {string} name - The name of the sub-build.
  5809. * @param {?string} [nodeType=null] - The type of the node, if known.
  5810. */
  5811. class SubBuildNode extends Node {
  5812. static get type() {
  5813. return 'SubBuild';
  5814. }
  5815. constructor( node, name, nodeType = null ) {
  5816. super( nodeType );
  5817. /**
  5818. * The node to be built in the sub-build.
  5819. *
  5820. * @type {Node}
  5821. */
  5822. this.node = node;
  5823. /**
  5824. * The name of the sub-build.
  5825. *
  5826. * @type {string}
  5827. */
  5828. this.name = name;
  5829. /**
  5830. * This flag can be used for type testing.
  5831. *
  5832. * @type {boolean}
  5833. * @readonly
  5834. * @default true
  5835. */
  5836. this.isSubBuildNode = true;
  5837. }
  5838. getNodeType( builder ) {
  5839. if ( this.nodeType !== null ) return this.nodeType;
  5840. builder.addSubBuild( this.name );
  5841. const nodeType = this.node.getNodeType( builder );
  5842. builder.removeSubBuild();
  5843. return nodeType;
  5844. }
  5845. build( builder, ...params ) {
  5846. builder.addSubBuild( this.name );
  5847. const data = this.node.build( builder, ...params );
  5848. builder.removeSubBuild();
  5849. return data;
  5850. }
  5851. }
  5852. /**
  5853. * Creates a new sub-build node.
  5854. *
  5855. * @tsl
  5856. * @function
  5857. * @param {Node} node - The node to be built in the sub-build.
  5858. * @param {string} name - The name of the sub-build.
  5859. * @param {?string} [type=null] - The type of the node, if known.
  5860. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5861. */
  5862. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5863. /**
  5864. * Class for representing shader varyings as nodes. Varyings are create from
  5865. * existing nodes like the following:
  5866. *
  5867. * ```js
  5868. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5869. * ```
  5870. *
  5871. * @augments Node
  5872. */
  5873. class VaryingNode extends Node {
  5874. static get type() {
  5875. return 'VaryingNode';
  5876. }
  5877. /**
  5878. * Constructs a new varying node.
  5879. *
  5880. * @param {Node} node - The node for which a varying should be created.
  5881. * @param {?string} name - The name of the varying in the shader.
  5882. */
  5883. constructor( node, name = null ) {
  5884. super();
  5885. /**
  5886. * The node for which a varying should be created.
  5887. *
  5888. * @type {Node}
  5889. */
  5890. this.node = node;
  5891. /**
  5892. * The name of the varying in the shader. If no name is defined,
  5893. * the node system auto-generates one.
  5894. *
  5895. * @type {?string}
  5896. * @default null
  5897. */
  5898. this.name = name;
  5899. /**
  5900. * This flag can be used for type testing.
  5901. *
  5902. * @type {boolean}
  5903. * @readonly
  5904. * @default true
  5905. */
  5906. this.isVaryingNode = true;
  5907. /**
  5908. * The interpolation type of the varying data.
  5909. *
  5910. * @type {?string}
  5911. * @default null
  5912. */
  5913. this.interpolationType = null;
  5914. /**
  5915. * The interpolation sampling type of varying data.
  5916. *
  5917. * @type {?string}
  5918. * @default null
  5919. */
  5920. this.interpolationSampling = null;
  5921. /**
  5922. * This flag is used for global cache.
  5923. *
  5924. * @type {boolean}
  5925. * @default true
  5926. */
  5927. this.global = true;
  5928. }
  5929. /**
  5930. * Defines the interpolation type of the varying.
  5931. *
  5932. * @param {string} type - The interpolation type.
  5933. * @param {?string} sampling - The interpolation sampling type
  5934. * @return {VaryingNode} A reference to this node.
  5935. */
  5936. setInterpolation( type, sampling = null ) {
  5937. this.interpolationType = type;
  5938. this.interpolationSampling = sampling;
  5939. return this;
  5940. }
  5941. getHash( builder ) {
  5942. return this.name || super.getHash( builder );
  5943. }
  5944. getNodeType( builder ) {
  5945. // VaryingNode is auto type
  5946. return this.node.getNodeType( builder );
  5947. }
  5948. /**
  5949. * This method performs the setup of a varying node with the current node builder.
  5950. *
  5951. * @param {NodeBuilder} builder - The current node builder.
  5952. * @return {NodeVarying} The node varying from the node builder.
  5953. */
  5954. setupVarying( builder ) {
  5955. const properties = builder.getNodeProperties( this );
  5956. let varying = properties.varying;
  5957. if ( varying === undefined ) {
  5958. const name = this.name;
  5959. const type = this.getNodeType( builder );
  5960. const interpolationType = this.interpolationType;
  5961. const interpolationSampling = this.interpolationSampling;
  5962. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5963. properties.node = subBuild( this.node, 'VERTEX' );
  5964. }
  5965. // this property can be used to check if the varying can be optimized for a variable
  5966. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5967. return varying;
  5968. }
  5969. setup( builder ) {
  5970. this.setupVarying( builder );
  5971. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5972. }
  5973. analyze( builder ) {
  5974. this.setupVarying( builder );
  5975. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5976. }
  5977. generate( builder ) {
  5978. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5979. const properties = builder.getNodeProperties( this );
  5980. const varying = this.setupVarying( builder );
  5981. if ( properties[ propertyKey ] === undefined ) {
  5982. const type = this.getNodeType( builder );
  5983. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5984. // force node run in vertex stage
  5985. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5986. properties[ propertyKey ] = propertyName;
  5987. }
  5988. return builder.getPropertyName( varying );
  5989. }
  5990. }
  5991. /**
  5992. * TSL function for creating a varying node.
  5993. *
  5994. * @tsl
  5995. * @function
  5996. * @param {Node} node - The node for which a varying should be created.
  5997. * @param {?string} name - The name of the varying in the shader.
  5998. * @returns {VaryingNode}
  5999. */
  6000. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6001. /**
  6002. * Computes a node in the vertex stage.
  6003. *
  6004. * @tsl
  6005. * @function
  6006. * @param {Node} node - The node which should be executed in the vertex stage.
  6007. * @returns {VaryingNode}
  6008. */
  6009. const vertexStage = ( node ) => varying( node );
  6010. addMethodChaining( 'toVarying', varying );
  6011. addMethodChaining( 'toVertexStage', vertexStage );
  6012. // Deprecated
  6013. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6014. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6015. return varying( ...params );
  6016. } );
  6017. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6018. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6019. return varying( ...params );
  6020. } );
  6021. /**
  6022. * Converts the given color value from sRGB to linear-sRGB color space.
  6023. *
  6024. * @tsl
  6025. * @function
  6026. * @param {Node<vec3>} color - The sRGB color.
  6027. * @return {Node<vec3>} The linear-sRGB color.
  6028. */
  6029. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6030. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6031. const b = color.mul( 0.0773993808 );
  6032. const factor = color.lessThanEqual( 0.04045 );
  6033. const rgbResult = mix( a, b, factor );
  6034. return rgbResult;
  6035. } ).setLayout( {
  6036. name: 'sRGBTransferEOTF',
  6037. type: 'vec3',
  6038. inputs: [
  6039. { name: 'color', type: 'vec3' }
  6040. ]
  6041. } );
  6042. /**
  6043. * Converts the given color value from linear-sRGB to sRGB color space.
  6044. *
  6045. * @tsl
  6046. * @function
  6047. * @param {Node<vec3>} color - The linear-sRGB color.
  6048. * @return {Node<vec3>} The sRGB color.
  6049. */
  6050. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6051. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6052. const b = color.mul( 12.92 );
  6053. const factor = color.lessThanEqual( 0.0031308 );
  6054. const rgbResult = mix( a, b, factor );
  6055. return rgbResult;
  6056. } ).setLayout( {
  6057. name: 'sRGBTransferOETF',
  6058. type: 'vec3',
  6059. inputs: [
  6060. { name: 'color', type: 'vec3' }
  6061. ]
  6062. } );
  6063. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6064. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6065. /**
  6066. * This node represents a color space conversion. Meaning it converts
  6067. * a color value from a source to a target color space.
  6068. *
  6069. * @augments TempNode
  6070. */
  6071. class ColorSpaceNode extends TempNode {
  6072. static get type() {
  6073. return 'ColorSpaceNode';
  6074. }
  6075. /**
  6076. * Constructs a new color space node.
  6077. *
  6078. * @param {Node} colorNode - Represents the color to convert.
  6079. * @param {string} source - The source color space.
  6080. * @param {string} target - The target color space.
  6081. */
  6082. constructor( colorNode, source, target ) {
  6083. super( 'vec4' );
  6084. /**
  6085. * Represents the color to convert.
  6086. *
  6087. * @type {Node}
  6088. */
  6089. this.colorNode = colorNode;
  6090. /**
  6091. * The source color space.
  6092. *
  6093. * @type {string}
  6094. */
  6095. this.source = source;
  6096. /**
  6097. * The target color space.
  6098. *
  6099. * @type {string}
  6100. */
  6101. this.target = target;
  6102. }
  6103. /**
  6104. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6105. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6106. * color management and renderer.
  6107. *
  6108. * @param {NodeBuilder} builder - The current node builder.
  6109. * @param {string} colorSpace - The color space to resolve.
  6110. * @return {string} The resolved color space.
  6111. */
  6112. resolveColorSpace( builder, colorSpace ) {
  6113. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6114. return ColorManagement.workingColorSpace;
  6115. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6116. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6117. }
  6118. return colorSpace;
  6119. }
  6120. setup( builder ) {
  6121. const { colorNode } = this;
  6122. const source = this.resolveColorSpace( builder, this.source );
  6123. const target = this.resolveColorSpace( builder, this.target );
  6124. let outputNode = colorNode;
  6125. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6126. return outputNode;
  6127. }
  6128. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6129. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6130. }
  6131. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6132. outputNode = vec4(
  6133. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6134. outputNode.a
  6135. );
  6136. }
  6137. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6138. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6139. }
  6140. return outputNode;
  6141. }
  6142. }
  6143. /**
  6144. * TSL function for converting a given color node from the current working color space to the given color space.
  6145. *
  6146. * @tsl
  6147. * @function
  6148. * @param {Node} node - Represents the node to convert.
  6149. * @param {string} targetColorSpace - The target color space.
  6150. * @returns {ColorSpaceNode}
  6151. */
  6152. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6153. /**
  6154. * TSL function for converting a given color node from the given color space to the current working color space.
  6155. *
  6156. * @tsl
  6157. * @function
  6158. * @param {Node} node - Represents the node to convert.
  6159. * @param {string} sourceColorSpace - The source color space.
  6160. * @returns {ColorSpaceNode}
  6161. */
  6162. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6163. /**
  6164. * TSL function for converting a given color node from one color space to another one.
  6165. *
  6166. * @tsl
  6167. * @function
  6168. * @param {Node} node - Represents the node to convert.
  6169. * @param {string} sourceColorSpace - The source color space.
  6170. * @param {string} targetColorSpace - The target color space.
  6171. * @returns {ColorSpaceNode}
  6172. */
  6173. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6174. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6175. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6176. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6177. /**
  6178. * This class is only relevant if the referenced property is array-like.
  6179. * In this case, `ReferenceElementNode` allows to refer to a specific
  6180. * element inside the data structure via an index.
  6181. *
  6182. * @augments ArrayElementNode
  6183. */
  6184. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6185. static get type() {
  6186. return 'ReferenceElementNode';
  6187. }
  6188. /**
  6189. * Constructs a new reference element node.
  6190. *
  6191. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6192. * @param {Node} indexNode - The index node that defines the element access.
  6193. */
  6194. constructor( referenceNode, indexNode ) {
  6195. super( referenceNode, indexNode );
  6196. /**
  6197. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6198. * property references to the current node.
  6199. *
  6200. * @type {?ReferenceBaseNode}
  6201. * @default null
  6202. */
  6203. this.referenceNode = referenceNode;
  6204. /**
  6205. * This flag can be used for type testing.
  6206. *
  6207. * @type {boolean}
  6208. * @readonly
  6209. * @default true
  6210. */
  6211. this.isReferenceElementNode = true;
  6212. }
  6213. /**
  6214. * This method is overwritten since the node type is inferred from
  6215. * the uniform type of the reference node.
  6216. *
  6217. * @return {string} The node type.
  6218. */
  6219. getNodeType() {
  6220. return this.referenceNode.uniformType;
  6221. }
  6222. generate( builder ) {
  6223. const snippet = super.generate( builder );
  6224. const arrayType = this.referenceNode.getNodeType();
  6225. const elementType = this.getNodeType();
  6226. return builder.format( snippet, arrayType, elementType );
  6227. }
  6228. };
  6229. /**
  6230. * Base class for nodes which establishes a reference to a property of another object.
  6231. * In this way, the value of the node is automatically linked to the value of
  6232. * referenced object. Reference nodes internally represent the linked value
  6233. * as a uniform.
  6234. *
  6235. * @augments Node
  6236. */
  6237. class ReferenceBaseNode extends Node {
  6238. static get type() {
  6239. return 'ReferenceBaseNode';
  6240. }
  6241. /**
  6242. * Constructs a new reference base node.
  6243. *
  6244. * @param {string} property - The name of the property the node refers to.
  6245. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6246. * @param {?Object} [object=null] - The object the property belongs to.
  6247. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6248. */
  6249. constructor( property, uniformType, object = null, count = null ) {
  6250. super();
  6251. /**
  6252. * The name of the property the node refers to.
  6253. *
  6254. * @type {string}
  6255. */
  6256. this.property = property;
  6257. /**
  6258. * The uniform type that should be used to represent the property value.
  6259. *
  6260. * @type {string}
  6261. */
  6262. this.uniformType = uniformType;
  6263. /**
  6264. * The object the property belongs to.
  6265. *
  6266. * @type {?Object}
  6267. * @default null
  6268. */
  6269. this.object = object;
  6270. /**
  6271. * When the linked property is an array, this parameter defines its length.
  6272. *
  6273. * @type {?number}
  6274. * @default null
  6275. */
  6276. this.count = count;
  6277. /**
  6278. * The property name might have dots so nested properties can be referred.
  6279. * The hierarchy of the names is stored inside this array.
  6280. *
  6281. * @type {Array<string>}
  6282. */
  6283. this.properties = property.split( '.' );
  6284. /**
  6285. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6286. * since the final reference might be updated from calling code.
  6287. *
  6288. * @type {?Object}
  6289. * @default null
  6290. */
  6291. this.reference = object;
  6292. /**
  6293. * The uniform node that holds the value of the reference node.
  6294. *
  6295. * @type {UniformNode}
  6296. * @default null
  6297. */
  6298. this.node = null;
  6299. /**
  6300. * The uniform group of the internal uniform.
  6301. *
  6302. * @type {UniformGroupNode}
  6303. * @default null
  6304. */
  6305. this.group = null;
  6306. /**
  6307. * Overwritten since reference nodes are updated per object.
  6308. *
  6309. * @type {string}
  6310. * @default 'object'
  6311. */
  6312. this.updateType = NodeUpdateType.OBJECT;
  6313. }
  6314. /**
  6315. * Sets the uniform group for this reference node.
  6316. *
  6317. * @param {UniformGroupNode} group - The uniform group to set.
  6318. * @return {ReferenceBaseNode} A reference to this node.
  6319. */
  6320. setGroup( group ) {
  6321. this.group = group;
  6322. return this;
  6323. }
  6324. /**
  6325. * When the referred property is array-like, this method can be used
  6326. * to access elements via an index node.
  6327. *
  6328. * @param {IndexNode} indexNode - indexNode.
  6329. * @return {ReferenceElementNode} A reference to an element.
  6330. */
  6331. element( indexNode ) {
  6332. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6333. }
  6334. /**
  6335. * Sets the node type which automatically defines the internal
  6336. * uniform type.
  6337. *
  6338. * @param {string} uniformType - The type to set.
  6339. */
  6340. setNodeType( uniformType ) {
  6341. const node = uniform( null, uniformType );
  6342. if ( this.group !== null ) {
  6343. node.setGroup( this.group );
  6344. }
  6345. this.node = node;
  6346. }
  6347. /**
  6348. * This method is overwritten since the node type is inferred from
  6349. * the type of the reference node.
  6350. *
  6351. * @param {NodeBuilder} builder - The current node builder.
  6352. * @return {string} The node type.
  6353. */
  6354. getNodeType( builder ) {
  6355. if ( this.node === null ) {
  6356. this.updateReference( builder );
  6357. this.updateValue();
  6358. }
  6359. return this.node.getNodeType( builder );
  6360. }
  6361. /**
  6362. * Returns the property value from the given referred object.
  6363. *
  6364. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6365. * @return {any} The value.
  6366. */
  6367. getValueFromReference( object = this.reference ) {
  6368. const { properties } = this;
  6369. let value = object[ properties[ 0 ] ];
  6370. for ( let i = 1; i < properties.length; i ++ ) {
  6371. value = value[ properties[ i ] ];
  6372. }
  6373. return value;
  6374. }
  6375. /**
  6376. * Allows to update the reference based on the given state. The state is only
  6377. * evaluated {@link ReferenceBaseNode#object} is not set.
  6378. *
  6379. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6380. * @return {Object} The updated reference.
  6381. */
  6382. updateReference( state ) {
  6383. this.reference = this.object !== null ? this.object : state.object;
  6384. return this.reference;
  6385. }
  6386. /**
  6387. * The output of the reference node is the internal uniform node.
  6388. *
  6389. * @return {UniformNode} The output node.
  6390. */
  6391. setup() {
  6392. this.updateValue();
  6393. return this.node;
  6394. }
  6395. /**
  6396. * Overwritten to update the internal uniform value.
  6397. *
  6398. * @param {NodeFrame} frame - A reference to the current node frame.
  6399. */
  6400. update( /*frame*/ ) {
  6401. this.updateValue();
  6402. }
  6403. /**
  6404. * Retrieves the value from the referred object property and uses it
  6405. * to updated the internal uniform.
  6406. */
  6407. updateValue() {
  6408. if ( this.node === null ) this.setNodeType( this.uniformType );
  6409. const value = this.getValueFromReference();
  6410. if ( Array.isArray( value ) ) {
  6411. this.node.array = value;
  6412. } else {
  6413. this.node.value = value;
  6414. }
  6415. }
  6416. }
  6417. /**
  6418. * TSL function for creating a reference base node.
  6419. *
  6420. * @tsl
  6421. * @function
  6422. * @param {string} name - The name of the property the node refers to.
  6423. * @param {string} type - The uniform type that should be used to represent the property value.
  6424. * @param {Object} object - The object the property belongs to.
  6425. * @returns {ReferenceBaseNode}
  6426. */
  6427. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6428. /**
  6429. * This node is a special type of reference node which is intended
  6430. * for linking renderer properties with node values.
  6431. * ```js
  6432. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6433. * ```
  6434. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6435. * automatically be updated.
  6436. *
  6437. * @augments ReferenceBaseNode
  6438. */
  6439. class RendererReferenceNode extends ReferenceBaseNode {
  6440. static get type() {
  6441. return 'RendererReferenceNode';
  6442. }
  6443. /**
  6444. * Constructs a new renderer reference node.
  6445. *
  6446. * @param {string} property - The name of the property the node refers to.
  6447. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6448. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6449. * the node refers to the renderer of the current state.
  6450. */
  6451. constructor( property, inputType, renderer = null ) {
  6452. super( property, inputType, renderer );
  6453. /**
  6454. * The renderer the property belongs to. When no renderer is set,
  6455. * the node refers to the renderer of the current state.
  6456. *
  6457. * @type {?Renderer}
  6458. * @default null
  6459. */
  6460. this.renderer = renderer;
  6461. this.setGroup( renderGroup );
  6462. }
  6463. /**
  6464. * Updates the reference based on the given state. The state is only evaluated
  6465. * {@link RendererReferenceNode#renderer} is not set.
  6466. *
  6467. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6468. * @return {Object} The updated reference.
  6469. */
  6470. updateReference( state ) {
  6471. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6472. return this.reference;
  6473. }
  6474. }
  6475. /**
  6476. * TSL function for creating a renderer reference node.
  6477. *
  6478. * @tsl
  6479. * @function
  6480. * @param {string} name - The name of the property the node refers to.
  6481. * @param {string} type - The uniform type that should be used to represent the property value.
  6482. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6483. * the node refers to the renderer of the current state.
  6484. * @returns {RendererReferenceNode}
  6485. */
  6486. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6487. /**
  6488. * This node represents a tone mapping operation.
  6489. *
  6490. * @augments TempNode
  6491. */
  6492. class ToneMappingNode extends TempNode {
  6493. static get type() {
  6494. return 'ToneMappingNode';
  6495. }
  6496. /**
  6497. * Constructs a new tone mapping node.
  6498. *
  6499. * @param {number} toneMapping - The tone mapping type.
  6500. * @param {Node} exposureNode - The tone mapping exposure.
  6501. * @param {Node} [colorNode=null] - The color node to process.
  6502. */
  6503. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6504. super( 'vec3' );
  6505. /**
  6506. * The tone mapping type.
  6507. *
  6508. * @private
  6509. * @type {number}
  6510. */
  6511. this._toneMapping = toneMapping;
  6512. /**
  6513. * The tone mapping exposure.
  6514. *
  6515. * @type {Node}
  6516. * @default null
  6517. */
  6518. this.exposureNode = exposureNode;
  6519. /**
  6520. * Represents the color to process.
  6521. *
  6522. * @type {?Node}
  6523. * @default null
  6524. */
  6525. this.colorNode = colorNode;
  6526. }
  6527. /**
  6528. * Overwrites the default `customCacheKey()` implementation by including the tone
  6529. * mapping type into the cache key.
  6530. *
  6531. * @return {number} The hash.
  6532. */
  6533. customCacheKey() {
  6534. return hash$1( this._toneMapping );
  6535. }
  6536. /**
  6537. * Sets the tone mapping type.
  6538. *
  6539. * @param {number} value - The tone mapping type.
  6540. * @return {ToneMappingNode} A reference to this node.
  6541. */
  6542. setToneMapping( value ) {
  6543. this._toneMapping = value;
  6544. return this;
  6545. }
  6546. /**
  6547. * Gets the tone mapping type.
  6548. *
  6549. * @returns {number} The tone mapping type.
  6550. */
  6551. getToneMapping() {
  6552. return this._toneMapping;
  6553. }
  6554. setup( builder ) {
  6555. const colorNode = this.colorNode || builder.context.color;
  6556. const toneMapping = this._toneMapping;
  6557. if ( toneMapping === NoToneMapping ) return colorNode;
  6558. let outputNode = null;
  6559. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6560. if ( toneMappingFn !== null ) {
  6561. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6562. } else {
  6563. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6564. outputNode = colorNode;
  6565. }
  6566. return outputNode;
  6567. }
  6568. }
  6569. /**
  6570. * TSL function for creating a tone mapping node.
  6571. *
  6572. * @tsl
  6573. * @function
  6574. * @param {number} mapping - The tone mapping type.
  6575. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6576. * @param {Node<vec3> | Color} color - The color node to process.
  6577. * @returns {ToneMappingNode<vec3>}
  6578. */
  6579. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6580. /**
  6581. * TSL object that represents the global tone mapping exposure of the renderer.
  6582. *
  6583. * @tsl
  6584. * @type {RendererReferenceNode<vec3>}
  6585. */
  6586. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6587. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6588. /**
  6589. * In earlier `three.js` versions it was only possible to define attribute data
  6590. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6591. * on the node level.
  6592. * ```js
  6593. * const geometry = new THREE.PlaneGeometry();
  6594. * const positionAttribute = geometry.getAttribute( 'position' );
  6595. *
  6596. * const colors = [];
  6597. * for ( let i = 0; i < position.count; i ++ ) {
  6598. * colors.push( 1, 0, 0 );
  6599. * }
  6600. *
  6601. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6602. * ```
  6603. * This new approach is especially interesting when geometry data are generated via
  6604. * compute shaders. The below line converts a storage buffer into an attribute node.
  6605. * ```js
  6606. * material.positionNode = positionBuffer.toAttribute();
  6607. * ```
  6608. * @augments InputNode
  6609. */
  6610. class BufferAttributeNode extends InputNode {
  6611. static get type() {
  6612. return 'BufferAttributeNode';
  6613. }
  6614. /**
  6615. * Constructs a new buffer attribute node.
  6616. *
  6617. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6618. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6619. * @param {number} [bufferStride=0] - The buffer stride.
  6620. * @param {number} [bufferOffset=0] - The buffer offset.
  6621. */
  6622. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6623. super( value, bufferType );
  6624. /**
  6625. * This flag can be used for type testing.
  6626. *
  6627. * @type {boolean}
  6628. * @readonly
  6629. * @default true
  6630. */
  6631. this.isBufferNode = true;
  6632. /**
  6633. * The buffer type (e.g. `'vec3'`).
  6634. *
  6635. * @type {?string}
  6636. * @default null
  6637. */
  6638. this.bufferType = bufferType;
  6639. /**
  6640. * The buffer stride.
  6641. *
  6642. * @type {number}
  6643. * @default 0
  6644. */
  6645. this.bufferStride = bufferStride;
  6646. /**
  6647. * The buffer offset.
  6648. *
  6649. * @type {number}
  6650. * @default 0
  6651. */
  6652. this.bufferOffset = bufferOffset;
  6653. /**
  6654. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6655. * if you are planning to update the attribute data per frame.
  6656. *
  6657. * @type {number}
  6658. * @default StaticDrawUsage
  6659. */
  6660. this.usage = StaticDrawUsage;
  6661. /**
  6662. * Whether the attribute is instanced or not.
  6663. *
  6664. * @type {boolean}
  6665. * @default false
  6666. */
  6667. this.instanced = false;
  6668. /**
  6669. * A reference to the buffer attribute.
  6670. *
  6671. * @type {?BufferAttribute}
  6672. * @default null
  6673. */
  6674. this.attribute = null;
  6675. /**
  6676. * `BufferAttributeNode` sets this property to `true` by default.
  6677. *
  6678. * @type {boolean}
  6679. * @default true
  6680. */
  6681. this.global = true;
  6682. if ( value && value.isBufferAttribute === true ) {
  6683. this.attribute = value;
  6684. this.usage = value.usage;
  6685. this.instanced = value.isInstancedBufferAttribute;
  6686. }
  6687. }
  6688. /**
  6689. * This method is overwritten since the attribute data might be shared
  6690. * and thus the hash should be shared as well.
  6691. *
  6692. * @param {NodeBuilder} builder - The current node builder.
  6693. * @return {string} The hash.
  6694. */
  6695. getHash( builder ) {
  6696. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6697. let bufferData = builder.globalCache.getData( this.value );
  6698. if ( bufferData === undefined ) {
  6699. bufferData = {
  6700. node: this
  6701. };
  6702. builder.globalCache.setData( this.value, bufferData );
  6703. }
  6704. return bufferData.node.uuid;
  6705. }
  6706. return this.uuid;
  6707. }
  6708. /**
  6709. * This method is overwritten since the node type is inferred from
  6710. * the buffer attribute.
  6711. *
  6712. * @param {NodeBuilder} builder - The current node builder.
  6713. * @return {string} The node type.
  6714. */
  6715. getNodeType( builder ) {
  6716. if ( this.bufferType === null ) {
  6717. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6718. }
  6719. return this.bufferType;
  6720. }
  6721. /**
  6722. * Depending on which value was passed to the node, `setup()` behaves
  6723. * differently. If no instance of `BufferAttribute` was passed, the method
  6724. * creates an internal attribute and configures it respectively.
  6725. *
  6726. * @param {NodeBuilder} builder - The current node builder.
  6727. */
  6728. setup( builder ) {
  6729. if ( this.attribute !== null ) return;
  6730. const type = this.getNodeType( builder );
  6731. const array = this.value;
  6732. const itemSize = builder.getTypeLength( type );
  6733. const stride = this.bufferStride || itemSize;
  6734. const offset = this.bufferOffset;
  6735. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6736. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6737. buffer.setUsage( this.usage );
  6738. this.attribute = bufferAttribute;
  6739. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6740. }
  6741. /**
  6742. * Generates the code snippet of the buffer attribute node.
  6743. *
  6744. * @param {NodeBuilder} builder - The current node builder.
  6745. * @return {string} The generated code snippet.
  6746. */
  6747. generate( builder ) {
  6748. const nodeType = this.getNodeType( builder );
  6749. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6750. const propertyName = builder.getPropertyName( nodeAttribute );
  6751. let output = null;
  6752. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6753. this.name = propertyName;
  6754. output = propertyName;
  6755. } else {
  6756. const nodeVarying = varying( this );
  6757. output = nodeVarying.build( builder, nodeType );
  6758. }
  6759. return output;
  6760. }
  6761. /**
  6762. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6763. *
  6764. * @param {NodeBuilder} builder - The current node builder.
  6765. * @return {string} The input type.
  6766. */
  6767. getInputType( /*builder*/ ) {
  6768. return 'bufferAttribute';
  6769. }
  6770. /**
  6771. * Sets the `usage` property to the given value.
  6772. *
  6773. * @param {number} value - The usage to set.
  6774. * @return {BufferAttributeNode} A reference to this node.
  6775. */
  6776. setUsage( value ) {
  6777. this.usage = value;
  6778. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6779. this.attribute.usage = value;
  6780. }
  6781. return this;
  6782. }
  6783. /**
  6784. * Sets the `instanced` property to the given value.
  6785. *
  6786. * @param {boolean} value - The value to set.
  6787. * @return {BufferAttributeNode} A reference to this node.
  6788. */
  6789. setInstanced( value ) {
  6790. this.instanced = value;
  6791. return this;
  6792. }
  6793. }
  6794. /**
  6795. * TSL function for creating a buffer attribute node.
  6796. *
  6797. * @tsl
  6798. * @function
  6799. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6800. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6801. * @param {number} [stride=0] - The buffer stride.
  6802. * @param {number} [offset=0] - The buffer offset.
  6803. * @returns {BufferAttributeNode}
  6804. */
  6805. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6806. /**
  6807. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6808. * Use this function if attribute data are updated per frame.
  6809. *
  6810. * @tsl
  6811. * @function
  6812. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6813. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6814. * @param {number} [stride=0] - The buffer stride.
  6815. * @param {number} [offset=0] - The buffer offset.
  6816. * @returns {BufferAttributeNode}
  6817. */
  6818. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6819. /**
  6820. * TSL function for creating a buffer attribute node but with enabled instancing
  6821. *
  6822. * @tsl
  6823. * @function
  6824. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6825. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6826. * @param {number} [stride=0] - The buffer stride.
  6827. * @param {number} [offset=0] - The buffer offset.
  6828. * @returns {BufferAttributeNode}
  6829. */
  6830. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6831. /**
  6832. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6833. *
  6834. * @tsl
  6835. * @function
  6836. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6837. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6838. * @param {number} [stride=0] - The buffer stride.
  6839. * @param {number} [offset=0] - The buffer offset.
  6840. * @returns {BufferAttributeNode}
  6841. */
  6842. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6843. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6844. /**
  6845. * TODO
  6846. *
  6847. * @augments Node
  6848. */
  6849. class ComputeNode extends Node {
  6850. static get type() {
  6851. return 'ComputeNode';
  6852. }
  6853. /**
  6854. * Constructs a new compute node.
  6855. *
  6856. * @param {Node} computeNode - TODO
  6857. * @param {Array<number>} workgroupSize - TODO.
  6858. */
  6859. constructor( computeNode, workgroupSize ) {
  6860. super( 'void' );
  6861. /**
  6862. * This flag can be used for type testing.
  6863. *
  6864. * @type {boolean}
  6865. * @readonly
  6866. * @default true
  6867. */
  6868. this.isComputeNode = true;
  6869. /**
  6870. * TODO
  6871. *
  6872. * @type {Node}
  6873. */
  6874. this.computeNode = computeNode;
  6875. /**
  6876. * TODO
  6877. *
  6878. * @type {Array<number>}
  6879. * @default [ 64 ]
  6880. */
  6881. this.workgroupSize = workgroupSize;
  6882. /**
  6883. * TODO
  6884. *
  6885. * @type {number}
  6886. */
  6887. this.count = null;
  6888. /**
  6889. * TODO
  6890. *
  6891. * @type {number}
  6892. */
  6893. this.version = 1;
  6894. /**
  6895. * The name or label of the uniform.
  6896. *
  6897. * @type {string}
  6898. * @default ''
  6899. */
  6900. this.name = '';
  6901. /**
  6902. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6903. * is executed once per object by default.
  6904. *
  6905. * @type {string}
  6906. * @default 'object'
  6907. */
  6908. this.updateBeforeType = NodeUpdateType.OBJECT;
  6909. /**
  6910. * TODO
  6911. *
  6912. * @type {?Function}
  6913. */
  6914. this.onInitFunction = null;
  6915. }
  6916. setCount( count ) {
  6917. this.count = count;
  6918. return this;
  6919. }
  6920. getCount() {
  6921. return this.count;
  6922. }
  6923. /**
  6924. * Executes the `dispose` event for this node.
  6925. */
  6926. dispose() {
  6927. this.dispatchEvent( { type: 'dispose' } );
  6928. }
  6929. /**
  6930. * Sets the {@link ComputeNode#name} property.
  6931. *
  6932. * @param {string} name - The name of the uniform.
  6933. * @return {ComputeNode} A reference to this node.
  6934. */
  6935. setName( name ) {
  6936. this.name = name;
  6937. return this;
  6938. }
  6939. /**
  6940. * Sets the {@link ComputeNode#name} property.
  6941. *
  6942. * @deprecated
  6943. * @param {string} name - The name of the uniform.
  6944. * @return {ComputeNode} A reference to this node.
  6945. */
  6946. label( name ) {
  6947. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6948. return this.setName( name );
  6949. }
  6950. /**
  6951. * TODO
  6952. *
  6953. * @param {Function} callback - TODO.
  6954. * @return {ComputeNode} A reference to this node.
  6955. */
  6956. onInit( callback ) {
  6957. this.onInitFunction = callback;
  6958. return this;
  6959. }
  6960. /**
  6961. * The method execute the compute for this node.
  6962. *
  6963. * @param {NodeFrame} frame - A reference to the current node frame.
  6964. */
  6965. updateBefore( { renderer } ) {
  6966. renderer.compute( this );
  6967. }
  6968. setup( builder ) {
  6969. const result = this.computeNode.build( builder );
  6970. if ( result ) {
  6971. const properties = builder.getNodeProperties( this );
  6972. properties.outputComputeNode = result.outputNode;
  6973. result.outputNode = null;
  6974. }
  6975. return result;
  6976. }
  6977. generate( builder, output ) {
  6978. const { shaderStage } = builder;
  6979. if ( shaderStage === 'compute' ) {
  6980. const snippet = this.computeNode.build( builder, 'void' );
  6981. if ( snippet !== '' ) {
  6982. builder.addLineFlowCode( snippet, this );
  6983. }
  6984. } else {
  6985. const properties = builder.getNodeProperties( this );
  6986. const outputComputeNode = properties.outputComputeNode;
  6987. if ( outputComputeNode ) {
  6988. return outputComputeNode.build( builder, output );
  6989. }
  6990. }
  6991. }
  6992. }
  6993. /**
  6994. * TSL function for creating a compute kernel node.
  6995. *
  6996. * @tsl
  6997. * @function
  6998. * @param {Node} node - TODO
  6999. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7000. * @returns {AtomicFunctionNode}
  7001. */
  7002. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7003. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7004. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7005. }
  7006. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7007. const val = workgroupSize[ i ];
  7008. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7009. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7010. }
  7011. }
  7012. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7013. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7014. //
  7015. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7016. };
  7017. /**
  7018. * TSL function for creating a compute node.
  7019. *
  7020. * @tsl
  7021. * @function
  7022. * @param {Node} node - TODO
  7023. * @param {number} count - TODO.
  7024. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7025. * @returns {AtomicFunctionNode}
  7026. */
  7027. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7028. addMethodChaining( 'compute', compute );
  7029. addMethodChaining( 'computeKernel', computeKernel );
  7030. /**
  7031. * This node can be used as a cache management component for another node.
  7032. * Caching is in general used by default in {@link NodeBuilder} but this node
  7033. * allows the usage of a shared parent cache during the build process.
  7034. *
  7035. * @augments Node
  7036. */
  7037. class IsolateNode extends Node {
  7038. static get type() {
  7039. return 'IsolateNode';
  7040. }
  7041. /**
  7042. * Constructs a new cache node.
  7043. *
  7044. * @param {Node} node - The node that should be cached.
  7045. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7046. */
  7047. constructor( node, parent = true ) {
  7048. super();
  7049. /**
  7050. * The node that should be cached.
  7051. *
  7052. * @type {Node}
  7053. */
  7054. this.node = node;
  7055. /**
  7056. * Whether this node refers to a shared parent cache or not.
  7057. *
  7058. * @type {boolean}
  7059. * @default true
  7060. */
  7061. this.parent = parent;
  7062. /**
  7063. * This flag can be used for type testing.
  7064. *
  7065. * @type {boolean}
  7066. * @readonly
  7067. * @default true
  7068. */
  7069. this.isIsolateNode = true;
  7070. }
  7071. getNodeType( builder ) {
  7072. const previousCache = builder.getCache();
  7073. const cache = builder.getCacheFromNode( this, this.parent );
  7074. builder.setCache( cache );
  7075. const nodeType = this.node.getNodeType( builder );
  7076. builder.setCache( previousCache );
  7077. return nodeType;
  7078. }
  7079. build( builder, ...params ) {
  7080. const previousCache = builder.getCache();
  7081. const cache = builder.getCacheFromNode( this, this.parent );
  7082. builder.setCache( cache );
  7083. const data = this.node.build( builder, ...params );
  7084. builder.setCache( previousCache );
  7085. return data;
  7086. }
  7087. setParent( parent ) {
  7088. this.parent = parent;
  7089. return this;
  7090. }
  7091. getParent() {
  7092. return this.parent;
  7093. }
  7094. }
  7095. /**
  7096. * TSL function for creating a cache node.
  7097. *
  7098. * @tsl
  7099. * @function
  7100. * @param {Node} node - The node that should be cached.
  7101. * @returns {IsolateNode}
  7102. */
  7103. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7104. /**
  7105. * TSL function for creating a cache node.
  7106. *
  7107. * @tsl
  7108. * @function
  7109. * @deprecated
  7110. * @param {Node} node - The node that should be cached.
  7111. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7112. * @returns {IsolateNode}
  7113. */
  7114. function cache( node, parent = true ) {
  7115. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7116. return isolate( node ).setParent( parent );
  7117. }
  7118. addMethodChaining( 'cache', cache );
  7119. addMethodChaining( 'isolate', isolate );
  7120. /**
  7121. * The class generates the code of a given node but returns another node in the output.
  7122. * This can be used to call a method or node that does not return a value, i.e.
  7123. * type `void` on an input where returning a value is required. Example:
  7124. *
  7125. * ```js
  7126. * material.colorNode = myColor.bypass( runVoidFn() )
  7127. *```
  7128. *
  7129. * @augments Node
  7130. */
  7131. class BypassNode extends Node {
  7132. static get type() {
  7133. return 'BypassNode';
  7134. }
  7135. /**
  7136. * Constructs a new bypass node.
  7137. *
  7138. * @param {Node} outputNode - The output node.
  7139. * @param {Node} callNode - The call node.
  7140. */
  7141. constructor( outputNode, callNode ) {
  7142. super();
  7143. /**
  7144. * This flag can be used for type testing.
  7145. *
  7146. * @type {boolean}
  7147. * @readonly
  7148. * @default true
  7149. */
  7150. this.isBypassNode = true;
  7151. /**
  7152. * The output node.
  7153. *
  7154. * @type {Node}
  7155. */
  7156. this.outputNode = outputNode;
  7157. /**
  7158. * The call node.
  7159. *
  7160. * @type {Node}
  7161. */
  7162. this.callNode = callNode;
  7163. }
  7164. getNodeType( builder ) {
  7165. return this.outputNode.getNodeType( builder );
  7166. }
  7167. generate( builder ) {
  7168. const snippet = this.callNode.build( builder, 'void' );
  7169. if ( snippet !== '' ) {
  7170. builder.addLineFlowCode( snippet, this );
  7171. }
  7172. return this.outputNode.build( builder );
  7173. }
  7174. }
  7175. /**
  7176. * TSL function for creating a bypass node.
  7177. *
  7178. * @tsl
  7179. * @function
  7180. * @param {Node} outputNode - The output node.
  7181. * @param {Node} callNode - The call node.
  7182. * @returns {BypassNode}
  7183. */
  7184. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7185. addMethodChaining( 'bypass', bypass );
  7186. /**
  7187. * This node allows to remap a node value from one range into another. E.g a value of
  7188. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7189. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7190. *
  7191. * @augments Node
  7192. */
  7193. class RemapNode extends Node {
  7194. static get type() {
  7195. return 'RemapNode';
  7196. }
  7197. /**
  7198. * Constructs a new remap node.
  7199. *
  7200. * @param {Node} node - The node that should be remapped.
  7201. * @param {Node} inLowNode - The source or current lower bound of the range.
  7202. * @param {Node} inHighNode - The source or current upper bound of the range.
  7203. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7204. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7205. */
  7206. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7207. super();
  7208. /**
  7209. * The node that should be remapped.
  7210. *
  7211. * @type {Node}
  7212. */
  7213. this.node = node;
  7214. /**
  7215. * The source or current lower bound of the range.
  7216. *
  7217. * @type {Node}
  7218. */
  7219. this.inLowNode = inLowNode;
  7220. /**
  7221. * The source or current upper bound of the range.
  7222. *
  7223. * @type {Node}
  7224. */
  7225. this.inHighNode = inHighNode;
  7226. /**
  7227. * The target lower bound of the range.
  7228. *
  7229. * @type {Node}
  7230. * @default float(0)
  7231. */
  7232. this.outLowNode = outLowNode;
  7233. /**
  7234. * The target upper bound of the range.
  7235. *
  7236. * @type {Node}
  7237. * @default float(1)
  7238. */
  7239. this.outHighNode = outHighNode;
  7240. /**
  7241. * Whether the node value should be clamped before
  7242. * remapping it to the target range.
  7243. *
  7244. * @type {boolean}
  7245. * @default true
  7246. */
  7247. this.doClamp = true;
  7248. }
  7249. setup() {
  7250. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7251. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7252. if ( doClamp === true ) t = t.clamp();
  7253. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7254. }
  7255. }
  7256. /**
  7257. * TSL function for creating a remap node.
  7258. *
  7259. * @tsl
  7260. * @function
  7261. * @param {Node} node - The node that should be remapped.
  7262. * @param {Node} inLowNode - The source or current lower bound of the range.
  7263. * @param {Node} inHighNode - The source or current upper bound of the range.
  7264. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7265. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7266. * @returns {RemapNode}
  7267. */
  7268. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7269. /**
  7270. * TSL function for creating a remap node, but with enabled clamping.
  7271. *
  7272. * @tsl
  7273. * @function
  7274. * @param {Node} node - The node that should be remapped.
  7275. * @param {Node} inLowNode - The source or current lower bound of the range.
  7276. * @param {Node} inHighNode - The source or current upper bound of the range.
  7277. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7278. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7279. * @returns {RemapNode}
  7280. */
  7281. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7282. addMethodChaining( 'remap', remap );
  7283. addMethodChaining( 'remapClamp', remapClamp );
  7284. /**
  7285. * This class can be used to implement basic expressions in shader code.
  7286. * Basic examples for that are `return`, `continue` or `discard` statements.
  7287. *
  7288. * @augments Node
  7289. */
  7290. class ExpressionNode extends Node {
  7291. static get type() {
  7292. return 'ExpressionNode';
  7293. }
  7294. /**
  7295. * Constructs a new expression node.
  7296. *
  7297. * @param {string} [snippet=''] - The native code snippet.
  7298. * @param {string} [nodeType='void'] - The node type.
  7299. */
  7300. constructor( snippet = '', nodeType = 'void' ) {
  7301. super( nodeType );
  7302. /**
  7303. * The native code snippet.
  7304. *
  7305. * @type {string}
  7306. * @default ''
  7307. */
  7308. this.snippet = snippet;
  7309. }
  7310. generate( builder, output ) {
  7311. const type = this.getNodeType( builder );
  7312. const snippet = this.snippet;
  7313. if ( type === 'void' ) {
  7314. builder.addLineFlowCode( snippet, this );
  7315. } else {
  7316. return builder.format( snippet, type, output );
  7317. }
  7318. }
  7319. }
  7320. /**
  7321. * TSL function for creating an expression node.
  7322. *
  7323. * @tsl
  7324. * @function
  7325. * @param {string} [snippet] - The native code snippet.
  7326. * @param {?string} [nodeType='void'] - The node type.
  7327. * @returns {ExpressionNode}
  7328. */
  7329. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7330. /**
  7331. * Represents a `discard` shader operation in TSL.
  7332. *
  7333. * @tsl
  7334. * @function
  7335. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7336. * @return {Node} The `discard` expression.
  7337. */
  7338. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7339. /**
  7340. * Represents a `return` shader operation in TSL.
  7341. *
  7342. * @tsl
  7343. * @function
  7344. * @return {ExpressionNode} The `return` expression.
  7345. */
  7346. const Return = () => expression( 'return' ).toStack();
  7347. addMethodChaining( 'discard', Discard );
  7348. /**
  7349. * Normally, tone mapping and color conversion happens automatically
  7350. * before outputting pixel too the default (screen) framebuffer. In certain
  7351. * post processing setups this happens to late because certain effects
  7352. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7353. * to apply tone mapping and color space conversion at an arbitrary point
  7354. * in the effect chain.
  7355. *
  7356. * When applying tone mapping and color space conversion manually with this node,
  7357. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7358. *
  7359. * ```js
  7360. * const postProcessing = new PostProcessing( renderer );
  7361. * postProcessing.outputColorTransform = false;
  7362. *
  7363. * const scenePass = pass( scene, camera );
  7364. * const outputPass = renderOutput( scenePass );
  7365. *
  7366. * postProcessing.outputNode = outputPass;
  7367. * ```
  7368. *
  7369. * @augments TempNode
  7370. */
  7371. class RenderOutputNode extends TempNode {
  7372. static get type() {
  7373. return 'RenderOutputNode';
  7374. }
  7375. /**
  7376. * Constructs a new render output node.
  7377. *
  7378. * @param {Node} colorNode - The color node to process.
  7379. * @param {?number} toneMapping - The tone mapping type.
  7380. * @param {?string} outputColorSpace - The output color space.
  7381. */
  7382. constructor( colorNode, toneMapping, outputColorSpace ) {
  7383. super( 'vec4' );
  7384. /**
  7385. * The color node to process.
  7386. *
  7387. * @type {Node}
  7388. */
  7389. this.colorNode = colorNode;
  7390. /**
  7391. * The tone mapping type.
  7392. *
  7393. * @private
  7394. * @type {?number}
  7395. */
  7396. this._toneMapping = toneMapping;
  7397. /**
  7398. * The output color space.
  7399. *
  7400. * @type {?string}
  7401. */
  7402. this.outputColorSpace = outputColorSpace;
  7403. /**
  7404. * This flag can be used for type testing.
  7405. *
  7406. * @type {boolean}
  7407. * @readonly
  7408. * @default true
  7409. */
  7410. this.isRenderOutputNode = true;
  7411. }
  7412. /**
  7413. * Sets the tone mapping type.
  7414. *
  7415. * @param {number} value - The tone mapping type.
  7416. * @return {ToneMappingNode} A reference to this node.
  7417. */
  7418. setToneMapping( value ) {
  7419. this._toneMapping = value;
  7420. return this;
  7421. }
  7422. /**
  7423. * Gets the tone mapping type.
  7424. *
  7425. * @returns {number} The tone mapping type.
  7426. */
  7427. getToneMapping() {
  7428. return this._toneMapping;
  7429. }
  7430. setup( { context } ) {
  7431. let outputNode = this.colorNode || context.color;
  7432. // tone mapping
  7433. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7434. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7435. if ( toneMapping !== NoToneMapping ) {
  7436. outputNode = outputNode.toneMapping( toneMapping );
  7437. }
  7438. // working to output color space
  7439. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7440. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7441. }
  7442. return outputNode;
  7443. }
  7444. }
  7445. /**
  7446. * TSL function for creating a posterize node.
  7447. *
  7448. * @tsl
  7449. * @function
  7450. * @param {Node} color - The color node to process.
  7451. * @param {?number} [toneMapping=null] - The tone mapping type.
  7452. * @param {?string} [outputColorSpace=null] - The output color space.
  7453. * @returns {RenderOutputNode}
  7454. */
  7455. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7456. addMethodChaining( 'renderOutput', renderOutput );
  7457. class DebugNode extends TempNode {
  7458. static get type() {
  7459. return 'DebugNode';
  7460. }
  7461. constructor( node, callback = null ) {
  7462. super();
  7463. this.node = node;
  7464. this.callback = callback;
  7465. }
  7466. getNodeType( builder ) {
  7467. return this.node.getNodeType( builder );
  7468. }
  7469. setup( builder ) {
  7470. return this.node.build( builder );
  7471. }
  7472. analyze( builder ) {
  7473. return this.node.build( builder );
  7474. }
  7475. generate( builder ) {
  7476. const callback = this.callback;
  7477. const snippet = this.node.build( builder );
  7478. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7479. const border = '-'.repeat( title.length );
  7480. let code = '';
  7481. code += '// #' + title + '#\n';
  7482. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7483. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7484. code += '// #' + border + '#\n';
  7485. if ( callback !== null ) {
  7486. callback( builder, code );
  7487. } else {
  7488. log$1( code );
  7489. }
  7490. return snippet;
  7491. }
  7492. }
  7493. /**
  7494. * TSL function for creating a debug node.
  7495. *
  7496. * @tsl
  7497. * @function
  7498. * @param {Node} node - The node to debug.
  7499. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7500. * @returns {DebugNode}
  7501. */
  7502. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7503. addMethodChaining( 'debug', debug );
  7504. /**
  7505. * InspectorBase is the base class for all inspectors.
  7506. *
  7507. * @class InspectorBase
  7508. */
  7509. class InspectorBase {
  7510. /**
  7511. * Creates a new InspectorBase.
  7512. */
  7513. constructor() {
  7514. /**
  7515. * The renderer associated with this inspector.
  7516. *
  7517. * @type {WebGLRenderer}
  7518. * @private
  7519. */
  7520. this._renderer = null;
  7521. /**
  7522. * The current frame being processed.
  7523. *
  7524. * @type {Object}
  7525. */
  7526. this.currentFrame = null;
  7527. }
  7528. /**
  7529. * Returns the node frame for the current renderer.
  7530. *
  7531. * @return {Object} The node frame.
  7532. */
  7533. get nodeFrame() {
  7534. return this._renderer._nodes.nodeFrame;
  7535. }
  7536. /**
  7537. * Sets the renderer for this inspector.
  7538. *
  7539. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7540. * @return {InspectorBase} This inspector instance.
  7541. */
  7542. setRenderer( renderer ) {
  7543. this._renderer = renderer;
  7544. return this;
  7545. }
  7546. /**
  7547. * Returns the renderer associated with this inspector.
  7548. *
  7549. * @return {WebGLRenderer} The associated renderer.
  7550. */
  7551. getRenderer() {
  7552. return this._renderer;
  7553. }
  7554. /**
  7555. * Initializes the inspector.
  7556. */
  7557. init() { }
  7558. /**
  7559. * Called when a frame begins.
  7560. */
  7561. begin() { }
  7562. /**
  7563. * Called when a frame ends.
  7564. */
  7565. finish() { }
  7566. /**
  7567. * Inspects a node.
  7568. *
  7569. * @param {Node} node - The node to inspect.
  7570. */
  7571. inspect( /*node*/ ) { }
  7572. /**
  7573. * When a compute operation is performed.
  7574. *
  7575. * @param {ComputeNode} computeNode - The compute node being executed.
  7576. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7577. */
  7578. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7579. /**
  7580. * Called when a compute operation begins.
  7581. *
  7582. * @param {string} uid - A unique identifier for the render context.
  7583. * @param {ComputeNode} computeNode - The compute node being executed.
  7584. */
  7585. beginCompute( /*uid, computeNode*/ ) { }
  7586. /**
  7587. * Called when a compute operation ends.
  7588. *
  7589. * @param {string} uid - A unique identifier for the render context.
  7590. * @param {ComputeNode} computeNode - The compute node being executed.
  7591. */
  7592. finishCompute( /*uid*/ ) { }
  7593. /**
  7594. * Called when a render operation begins.
  7595. *
  7596. * @param {string} uid - A unique identifier for the render context.
  7597. * @param {Scene} scene - The scene being rendered.
  7598. * @param {Camera} camera - The camera being used for rendering.
  7599. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7600. */
  7601. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7602. /**
  7603. * Called when an animation loop ends.
  7604. *
  7605. * @param {string} uid - A unique identifier for the render context.
  7606. */
  7607. finishRender( /*uid*/ ) { }
  7608. /**
  7609. * Called when a texture copy operation is performed.
  7610. *
  7611. * @param {Texture} srcTexture - The source texture.
  7612. * @param {Texture} dstTexture - The destination texture.
  7613. */
  7614. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7615. /**
  7616. * Called when a framebuffer copy operation is performed.
  7617. *
  7618. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7619. */
  7620. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7621. }
  7622. /**
  7623. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7624. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7625. *
  7626. * @augments Node
  7627. */
  7628. class InspectorNode extends Node {
  7629. /**
  7630. * Returns the type of the node.
  7631. *
  7632. * @returns {string}
  7633. */
  7634. static get type() {
  7635. return 'InspectorNode';
  7636. }
  7637. /**
  7638. * Creates an InspectorNode.
  7639. *
  7640. * @param {Node} node - The node to inspect.
  7641. * @param {string} [name=''] - Optional name for the inspector node.
  7642. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7643. */
  7644. constructor( node, name = '', callback = null ) {
  7645. super();
  7646. this.node = node;
  7647. this.name = name;
  7648. this.callback = callback;
  7649. this.updateType = NodeUpdateType.FRAME;
  7650. this.isInspectorNode = true;
  7651. }
  7652. /**
  7653. * Returns the name of the inspector node.
  7654. *
  7655. * @returns {string}
  7656. */
  7657. getName() {
  7658. return this.name || this.node.name;
  7659. }
  7660. /**
  7661. * Updates the inspector node, allowing inspection of the wrapped node.
  7662. *
  7663. * @param {NodeFrame} frame - A reference to the current node frame.
  7664. */
  7665. update( frame ) {
  7666. frame.renderer.inspector.inspect( this );
  7667. }
  7668. /**
  7669. * Returns the type of the wrapped node.
  7670. *
  7671. * @param {NodeBuilder} builder - The node builder.
  7672. * @returns {string}
  7673. */
  7674. getNodeType( builder ) {
  7675. return this.node.getNodeType( builder );
  7676. }
  7677. /**
  7678. * Sets up the inspector node.
  7679. *
  7680. * @param {NodeBuilder} builder - The node builder.
  7681. * @returns {Node} The setup node.
  7682. */
  7683. setup( builder ) {
  7684. let node = this.node;
  7685. if ( builder.context.inspector === true && this.callback !== null ) {
  7686. node = this.callback( node );
  7687. }
  7688. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7689. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7690. }
  7691. return node;
  7692. }
  7693. }
  7694. /**
  7695. * Creates an inspector node to wrap around a given node for inspection purposes.
  7696. *
  7697. * @tsl
  7698. * @param {Node} node - The node to inspect.
  7699. * @param {string} [name=''] - Optional name for the inspector node.
  7700. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7701. * @returns {Node} The inspector node.
  7702. */
  7703. function inspector( node, name = '', callback = null ) {
  7704. node = nodeObject( node );
  7705. return node.before( new InspectorNode( node, name, callback ) );
  7706. }
  7707. addMethodChaining( 'toInspector', inspector );
  7708. function addNodeElement( name/*, nodeElement*/ ) {
  7709. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7710. }
  7711. /**
  7712. * Base class for representing shader attributes as nodes.
  7713. *
  7714. * @augments Node
  7715. */
  7716. class AttributeNode extends Node {
  7717. static get type() {
  7718. return 'AttributeNode';
  7719. }
  7720. /**
  7721. * Constructs a new attribute node.
  7722. *
  7723. * @param {string} attributeName - The name of the attribute.
  7724. * @param {?string} nodeType - The node type.
  7725. */
  7726. constructor( attributeName, nodeType = null ) {
  7727. super( nodeType );
  7728. /**
  7729. * `AttributeNode` sets this property to `true` by default.
  7730. *
  7731. * @type {boolean}
  7732. * @default true
  7733. */
  7734. this.global = true;
  7735. this._attributeName = attributeName;
  7736. }
  7737. getHash( builder ) {
  7738. return this.getAttributeName( builder );
  7739. }
  7740. getNodeType( builder ) {
  7741. let nodeType = this.nodeType;
  7742. if ( nodeType === null ) {
  7743. const attributeName = this.getAttributeName( builder );
  7744. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7745. const attribute = builder.geometry.getAttribute( attributeName );
  7746. nodeType = builder.getTypeFromAttribute( attribute );
  7747. } else {
  7748. nodeType = 'float';
  7749. }
  7750. }
  7751. return nodeType;
  7752. }
  7753. /**
  7754. * Sets the attribute name to the given value. The method can be
  7755. * overwritten in derived classes if the final name must be computed
  7756. * analytically.
  7757. *
  7758. * @param {string} attributeName - The name of the attribute.
  7759. * @return {AttributeNode} A reference to this node.
  7760. */
  7761. setAttributeName( attributeName ) {
  7762. this._attributeName = attributeName;
  7763. return this;
  7764. }
  7765. /**
  7766. * Returns the attribute name of this node. The method can be
  7767. * overwritten in derived classes if the final name must be computed
  7768. * analytically.
  7769. *
  7770. * @param {NodeBuilder} builder - The current node builder.
  7771. * @return {string} The attribute name.
  7772. */
  7773. getAttributeName( /*builder*/ ) {
  7774. return this._attributeName;
  7775. }
  7776. generate( builder ) {
  7777. const attributeName = this.getAttributeName( builder );
  7778. const nodeType = this.getNodeType( builder );
  7779. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7780. if ( geometryAttribute === true ) {
  7781. const attribute = builder.geometry.getAttribute( attributeName );
  7782. const attributeType = builder.getTypeFromAttribute( attribute );
  7783. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7784. if ( builder.shaderStage === 'vertex' ) {
  7785. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7786. } else {
  7787. const nodeVarying = varying( this );
  7788. return nodeVarying.build( builder, nodeType );
  7789. }
  7790. } else {
  7791. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7792. return builder.generateConst( nodeType );
  7793. }
  7794. }
  7795. serialize( data ) {
  7796. super.serialize( data );
  7797. data.global = this.global;
  7798. data._attributeName = this._attributeName;
  7799. }
  7800. deserialize( data ) {
  7801. super.deserialize( data );
  7802. this.global = data.global;
  7803. this._attributeName = data._attributeName;
  7804. }
  7805. }
  7806. /**
  7807. * TSL function for creating an attribute node.
  7808. *
  7809. * @tsl
  7810. * @function
  7811. * @param {string} name - The name of the attribute.
  7812. * @param {?string} [nodeType=null] - The node type.
  7813. * @returns {AttributeNode}
  7814. */
  7815. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7816. /**
  7817. * TSL function for creating an uv attribute node with the given index.
  7818. *
  7819. * @tsl
  7820. * @function
  7821. * @param {number} [index=0] - The uv index.
  7822. * @return {AttributeNode<vec2>} The uv attribute node.
  7823. */
  7824. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7825. /**
  7826. * A node that represents the dimensions of a texture. The texture size is
  7827. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7828. * or `textureSize()`.
  7829. *
  7830. * @augments Node
  7831. */
  7832. class TextureSizeNode extends Node {
  7833. static get type() {
  7834. return 'TextureSizeNode';
  7835. }
  7836. /**
  7837. * Constructs a new texture size node.
  7838. *
  7839. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7840. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7841. */
  7842. constructor( textureNode, levelNode = null ) {
  7843. super( 'uvec2' );
  7844. /**
  7845. * This flag can be used for type testing.
  7846. *
  7847. * @type {boolean}
  7848. * @readonly
  7849. * @default true
  7850. */
  7851. this.isTextureSizeNode = true;
  7852. /**
  7853. * A texture node which size should be retrieved.
  7854. *
  7855. * @type {TextureNode}
  7856. */
  7857. this.textureNode = textureNode;
  7858. /**
  7859. * A level node which defines the requested mip.
  7860. *
  7861. * @type {Node<int>}
  7862. * @default null
  7863. */
  7864. this.levelNode = levelNode;
  7865. }
  7866. generate( builder, output ) {
  7867. const textureProperty = this.textureNode.build( builder, 'property' );
  7868. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7869. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7870. }
  7871. }
  7872. /**
  7873. * TSL function for creating a texture size node.
  7874. *
  7875. * @tsl
  7876. * @function
  7877. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7878. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7879. * @returns {TextureSizeNode}
  7880. */
  7881. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7882. /**
  7883. * A special type of uniform node that computes the
  7884. * maximum mipmap level for a given texture node.
  7885. *
  7886. * ```js
  7887. * const level = maxMipLevel( textureNode );
  7888. * ```
  7889. *
  7890. * @augments UniformNode
  7891. */
  7892. class MaxMipLevelNode extends UniformNode {
  7893. static get type() {
  7894. return 'MaxMipLevelNode';
  7895. }
  7896. /**
  7897. * Constructs a new max mip level node.
  7898. *
  7899. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7900. */
  7901. constructor( textureNode ) {
  7902. super( 0 );
  7903. /**
  7904. * The texture node to compute the max mip level for.
  7905. *
  7906. * @private
  7907. * @type {TextureNode}
  7908. */
  7909. this._textureNode = textureNode;
  7910. /**
  7911. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7912. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7913. *
  7914. * @type {string}
  7915. * @default 'frame'
  7916. */
  7917. this.updateType = NodeUpdateType.FRAME;
  7918. }
  7919. /**
  7920. * The texture node to compute the max mip level for.
  7921. *
  7922. * @readonly
  7923. * @type {TextureNode}
  7924. */
  7925. get textureNode() {
  7926. return this._textureNode;
  7927. }
  7928. /**
  7929. * The texture.
  7930. *
  7931. * @readonly
  7932. * @type {Texture}
  7933. */
  7934. get texture() {
  7935. return this._textureNode.value;
  7936. }
  7937. update() {
  7938. const texture = this.texture;
  7939. const images = texture.images;
  7940. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7941. if ( image && image.width !== undefined ) {
  7942. const { width, height } = image;
  7943. this.value = Math.log2( Math.max( width, height ) );
  7944. }
  7945. }
  7946. }
  7947. /**
  7948. * TSL function for creating a max mip level node.
  7949. *
  7950. * @tsl
  7951. * @function
  7952. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7953. * @returns {MaxMipLevelNode}
  7954. */
  7955. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7956. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7957. /**
  7958. * This type of uniform node represents a 2D texture.
  7959. *
  7960. * @augments UniformNode
  7961. */
  7962. class TextureNode extends UniformNode {
  7963. static get type() {
  7964. return 'TextureNode';
  7965. }
  7966. /**
  7967. * Constructs a new texture node.
  7968. *
  7969. * @param {Texture} [value=EmptyTexture] - The texture.
  7970. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7971. * @param {?Node<int>} [levelNode=null] - The level node.
  7972. * @param {?Node<float>} [biasNode=null] - The bias node.
  7973. */
  7974. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7975. super( value );
  7976. /**
  7977. * This flag can be used for type testing.
  7978. *
  7979. * @type {boolean}
  7980. * @readonly
  7981. * @default true
  7982. */
  7983. this.isTextureNode = true;
  7984. /**
  7985. * Represents the texture coordinates.
  7986. *
  7987. * @type {?Node<vec2|vec3>}
  7988. * @default null
  7989. */
  7990. this.uvNode = uvNode;
  7991. /**
  7992. * Represents the mip level that should be selected.
  7993. *
  7994. * @type {?Node<int>}
  7995. * @default null
  7996. */
  7997. this.levelNode = levelNode;
  7998. /**
  7999. * Represents the bias to be applied during level-of-detail computation.
  8000. *
  8001. * @type {?Node<float>}
  8002. * @default null
  8003. */
  8004. this.biasNode = biasNode;
  8005. /**
  8006. * Represents a reference value a texture sample is compared to.
  8007. *
  8008. * @type {?Node<float>}
  8009. * @default null
  8010. */
  8011. this.compareNode = null;
  8012. /**
  8013. * When using texture arrays, the depth node defines the layer to select.
  8014. *
  8015. * @type {?Node<int>}
  8016. * @default null
  8017. */
  8018. this.depthNode = null;
  8019. /**
  8020. * When defined, a texture is sampled using explicit gradients.
  8021. *
  8022. * @type {?Array<Node<vec2>>}
  8023. * @default null
  8024. */
  8025. this.gradNode = null;
  8026. /**
  8027. * Represents the optional texel offset applied to the unnormalized texture
  8028. * coordinate before sampling the texture.
  8029. *
  8030. * @type {?Node<ivec2|ivec3>}
  8031. * @default null
  8032. */
  8033. this.offsetNode = null;
  8034. /**
  8035. * Whether texture values should be sampled or fetched.
  8036. *
  8037. * @type {boolean}
  8038. * @default true
  8039. */
  8040. this.sampler = true;
  8041. /**
  8042. * Whether the uv transformation matrix should be
  8043. * automatically updated or not. Use `setUpdateMatrix()`
  8044. * if you want to change the value of the property.
  8045. *
  8046. * @type {boolean}
  8047. * @default false
  8048. */
  8049. this.updateMatrix = false;
  8050. /**
  8051. * By default the `update()` method is not executed. Depending on
  8052. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8053. * is executed per object.
  8054. *
  8055. * @type {string}
  8056. * @default 'none'
  8057. */
  8058. this.updateType = NodeUpdateType.NONE;
  8059. /**
  8060. * The reference node.
  8061. *
  8062. * @type {?Node}
  8063. * @default null
  8064. */
  8065. this.referenceNode = null;
  8066. /**
  8067. * The texture value is stored in a private property.
  8068. *
  8069. * @private
  8070. * @type {Texture}
  8071. */
  8072. this._value = value;
  8073. /**
  8074. * The uniform node that represents the uv transformation matrix.
  8075. *
  8076. * @private
  8077. * @type {?UniformNode<mat3>}
  8078. * @default null
  8079. */
  8080. this._matrixUniform = null;
  8081. /**
  8082. * The uniform node that represents the y-flip. Only required for WebGL.
  8083. *
  8084. * @private
  8085. * @type {?UniformNode<bool>}
  8086. * @default null
  8087. */
  8088. this._flipYUniform = null;
  8089. this.setUpdateMatrix( uvNode === null );
  8090. }
  8091. set value( value ) {
  8092. if ( this.referenceNode ) {
  8093. this.referenceNode.value = value;
  8094. } else {
  8095. this._value = value;
  8096. }
  8097. }
  8098. /**
  8099. * The texture value.
  8100. *
  8101. * @type {Texture}
  8102. */
  8103. get value() {
  8104. return this.referenceNode ? this.referenceNode.value : this._value;
  8105. }
  8106. /**
  8107. * Overwritten since the uniform hash is defined by the texture's UUID.
  8108. *
  8109. * @param {NodeBuilder} builder - The current node builder.
  8110. * @return {string} The uniform hash.
  8111. */
  8112. getUniformHash( /*builder*/ ) {
  8113. return this.value.uuid;
  8114. }
  8115. /**
  8116. * Overwritten since the node type is inferred from the texture type.
  8117. *
  8118. * @param {NodeBuilder} builder - The current node builder.
  8119. * @return {string} The node type.
  8120. */
  8121. getNodeType( /*builder*/ ) {
  8122. if ( this.value.isDepthTexture === true ) return 'float';
  8123. if ( this.value.type === UnsignedIntType ) {
  8124. return 'uvec4';
  8125. } else if ( this.value.type === IntType ) {
  8126. return 'ivec4';
  8127. }
  8128. return 'vec4';
  8129. }
  8130. /**
  8131. * Overwrites the default implementation to return a fixed value `'texture'`.
  8132. *
  8133. * @param {NodeBuilder} builder - The current node builder.
  8134. * @return {string} The input type.
  8135. */
  8136. getInputType( /*builder*/ ) {
  8137. return 'texture';
  8138. }
  8139. /**
  8140. * Returns a default uvs based on the current texture's channel.
  8141. *
  8142. * @return {AttributeNode<vec2>} The default uvs.
  8143. */
  8144. getDefaultUV() {
  8145. return uv$1( this.value.channel );
  8146. }
  8147. /**
  8148. * Overwritten to always return the texture reference of the node.
  8149. *
  8150. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8151. * @return {Texture} The texture reference.
  8152. */
  8153. updateReference( /*state*/ ) {
  8154. return this.value;
  8155. }
  8156. /**
  8157. * Transforms the given uv node with the texture transformation matrix.
  8158. *
  8159. * @param {Node} uvNode - The uv node to transform.
  8160. * @return {Node} The transformed uv node.
  8161. */
  8162. getTransformedUV( uvNode ) {
  8163. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8164. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8165. }
  8166. /**
  8167. * Defines whether the uv transformation matrix should automatically be updated or not.
  8168. *
  8169. * @param {boolean} value - The update toggle.
  8170. * @return {TextureNode} A reference to this node.
  8171. */
  8172. setUpdateMatrix( value ) {
  8173. this.updateMatrix = value;
  8174. return this;
  8175. }
  8176. /**
  8177. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8178. * to modify the uv node for correct sampling.
  8179. *
  8180. * @param {NodeBuilder} builder - The current node builder.
  8181. * @param {Node} uvNode - The uv node to setup.
  8182. * @return {Node} The updated uv node.
  8183. */
  8184. setupUV( builder, uvNode ) {
  8185. if ( builder.isFlipY() ) {
  8186. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8187. uvNode = uvNode.toVar();
  8188. if ( this.sampler ) {
  8189. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8190. } else {
  8191. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8192. }
  8193. }
  8194. return uvNode;
  8195. }
  8196. /**
  8197. * Setups texture node by preparing the internal nodes for code generation.
  8198. *
  8199. * @param {NodeBuilder} builder - The current node builder.
  8200. */
  8201. setup( builder ) {
  8202. const properties = builder.getNodeProperties( this );
  8203. properties.referenceNode = this.referenceNode;
  8204. //
  8205. const texture = this.value;
  8206. if ( ! texture || texture.isTexture !== true ) {
  8207. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8208. }
  8209. //
  8210. const uvNode = Fn( () => {
  8211. let uvNode = this.uvNode;
  8212. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8213. uvNode = builder.context.getUV( this, builder );
  8214. }
  8215. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8216. if ( this.updateMatrix === true ) {
  8217. uvNode = this.getTransformedUV( uvNode );
  8218. }
  8219. uvNode = this.setupUV( builder, uvNode );
  8220. //
  8221. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8222. //
  8223. return uvNode;
  8224. } )();
  8225. //
  8226. let levelNode = this.levelNode;
  8227. if ( levelNode === null && builder.context.getTextureLevel ) {
  8228. levelNode = builder.context.getTextureLevel( this );
  8229. }
  8230. //
  8231. properties.uvNode = uvNode;
  8232. properties.levelNode = levelNode;
  8233. properties.biasNode = this.biasNode;
  8234. properties.compareNode = this.compareNode;
  8235. properties.gradNode = this.gradNode;
  8236. properties.depthNode = this.depthNode;
  8237. properties.offsetNode = this.offsetNode;
  8238. }
  8239. /**
  8240. * Generates the uv code snippet.
  8241. *
  8242. * @param {NodeBuilder} builder - The current node builder.
  8243. * @param {Node} uvNode - The uv node to generate code for.
  8244. * @return {string} The generated code snippet.
  8245. */
  8246. generateUV( builder, uvNode ) {
  8247. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8248. }
  8249. /**
  8250. * Generates the offset code snippet.
  8251. *
  8252. * @param {NodeBuilder} builder - The current node builder.
  8253. * @param {Node} offsetNode - The offset node to generate code for.
  8254. * @return {string} The generated code snippet.
  8255. */
  8256. generateOffset( builder, offsetNode ) {
  8257. return offsetNode.build( builder, 'ivec2' );
  8258. }
  8259. /**
  8260. * Generates the snippet for the texture sampling.
  8261. *
  8262. * @param {NodeBuilder} builder - The current node builder.
  8263. * @param {string} textureProperty - The texture property.
  8264. * @param {string} uvSnippet - The uv snippet.
  8265. * @param {?string} levelSnippet - The level snippet.
  8266. * @param {?string} biasSnippet - The bias snippet.
  8267. * @param {?string} depthSnippet - The depth snippet.
  8268. * @param {?string} compareSnippet - The compare snippet.
  8269. * @param {?Array<string>} gradSnippet - The grad snippet.
  8270. * @param {?string} offsetSnippet - The offset snippet.
  8271. * @return {string} The generated code snippet.
  8272. */
  8273. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8274. const texture = this.value;
  8275. let snippet;
  8276. if ( biasSnippet ) {
  8277. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8278. } else if ( gradSnippet ) {
  8279. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8280. } else if ( compareSnippet ) {
  8281. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8282. } else if ( this.sampler === false ) {
  8283. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8284. } else if ( levelSnippet ) {
  8285. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8286. } else {
  8287. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8288. }
  8289. return snippet;
  8290. }
  8291. /**
  8292. * Generates the code snippet of the texture node.
  8293. *
  8294. * @param {NodeBuilder} builder - The current node builder.
  8295. * @param {string} output - The current output.
  8296. * @return {string} The generated code snippet.
  8297. */
  8298. generate( builder, output ) {
  8299. const texture = this.value;
  8300. const properties = builder.getNodeProperties( this );
  8301. const textureProperty = super.generate( builder, 'property' );
  8302. if ( /^sampler/.test( output ) ) {
  8303. return textureProperty + '_sampler';
  8304. } else if ( builder.isReference( output ) ) {
  8305. return textureProperty;
  8306. } else {
  8307. const nodeData = builder.getDataFromNode( this );
  8308. let propertyName = nodeData.propertyName;
  8309. if ( propertyName === undefined ) {
  8310. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8311. const uvSnippet = this.generateUV( builder, uvNode );
  8312. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8313. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8314. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8315. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8316. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8317. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8318. const nodeVar = builder.getVarFromNode( this );
  8319. propertyName = builder.getPropertyName( nodeVar );
  8320. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8321. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8322. nodeData.snippet = snippet;
  8323. nodeData.propertyName = propertyName;
  8324. }
  8325. let snippet = propertyName;
  8326. const nodeType = this.getNodeType( builder );
  8327. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8328. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8329. }
  8330. return builder.format( snippet, nodeType, output );
  8331. }
  8332. }
  8333. /**
  8334. * Sets the sampler value.
  8335. *
  8336. * @param {boolean} value - The sampler value to set.
  8337. * @return {TextureNode} A reference to this texture node.
  8338. */
  8339. setSampler( value ) {
  8340. this.sampler = value;
  8341. return this;
  8342. }
  8343. /**
  8344. * Returns the sampler value.
  8345. *
  8346. * @return {boolean} The sampler value.
  8347. */
  8348. getSampler() {
  8349. return this.sampler;
  8350. }
  8351. // @TODO: Move to TSL
  8352. /**
  8353. * @function
  8354. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8355. *
  8356. * @param {Node} uvNode - The uv node.
  8357. * @return {TextureNode} A texture node representing the texture sample.
  8358. */
  8359. uv( uvNode ) { // @deprecated, r172
  8360. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8361. return this.sample( uvNode );
  8362. }
  8363. /**
  8364. * Samples the texture with the given uv node.
  8365. *
  8366. * @param {Node} uvNode - The uv node.
  8367. * @return {TextureNode} A texture node representing the texture sample.
  8368. */
  8369. sample( uvNode ) {
  8370. const textureNode = this.clone();
  8371. textureNode.uvNode = nodeObject( uvNode );
  8372. textureNode.referenceNode = this.getBase();
  8373. return nodeObject( textureNode );
  8374. }
  8375. /**
  8376. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8377. *
  8378. * @param {Node<uvec2>} uvNode - The uv node.
  8379. * @returns {TextureNode} A texture node representing the texture load.
  8380. */
  8381. load( uvNode ) {
  8382. return this.sample( uvNode ).setSampler( false );
  8383. }
  8384. /**
  8385. * Samples a blurred version of the texture by defining an internal bias.
  8386. *
  8387. * @param {Node<float>} amountNode - How blurred the texture should be.
  8388. * @return {TextureNode} A texture node representing the texture sample.
  8389. */
  8390. blur( amountNode ) {
  8391. const textureNode = this.clone();
  8392. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8393. textureNode.referenceNode = this.getBase();
  8394. const map = textureNode.value;
  8395. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8396. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8397. textureNode.biasNode = null;
  8398. }
  8399. return nodeObject( textureNode );
  8400. }
  8401. /**
  8402. * Samples a specific mip of the texture.
  8403. *
  8404. * @param {Node<int>} levelNode - The mip level to sample.
  8405. * @return {TextureNode} A texture node representing the texture sample.
  8406. */
  8407. level( levelNode ) {
  8408. const textureNode = this.clone();
  8409. textureNode.levelNode = nodeObject( levelNode );
  8410. textureNode.referenceNode = this.getBase();
  8411. return nodeObject( textureNode );
  8412. }
  8413. /**
  8414. * Returns the texture size of the requested level.
  8415. *
  8416. * @param {Node<int>} levelNode - The level to compute the size for.
  8417. * @return {TextureSizeNode} The texture size.
  8418. */
  8419. size( levelNode ) {
  8420. return textureSize( this, levelNode );
  8421. }
  8422. /**
  8423. * Samples the texture with the given bias.
  8424. *
  8425. * @param {Node<float>} biasNode - The bias node.
  8426. * @return {TextureNode} A texture node representing the texture sample.
  8427. */
  8428. bias( biasNode ) {
  8429. const textureNode = this.clone();
  8430. textureNode.biasNode = nodeObject( biasNode );
  8431. textureNode.referenceNode = this.getBase();
  8432. return nodeObject( textureNode );
  8433. }
  8434. /**
  8435. * Returns the base texture of this node.
  8436. * @return {TextureNode} The base texture node.
  8437. */
  8438. getBase() {
  8439. return this.referenceNode ? this.referenceNode.getBase() : this;
  8440. }
  8441. /**
  8442. * Samples the texture by executing a compare operation.
  8443. *
  8444. * @param {Node<float>} compareNode - The node that defines the compare value.
  8445. * @return {TextureNode} A texture node representing the texture sample.
  8446. */
  8447. compare( compareNode ) {
  8448. const textureNode = this.clone();
  8449. textureNode.compareNode = nodeObject( compareNode );
  8450. textureNode.referenceNode = this.getBase();
  8451. return nodeObject( textureNode );
  8452. }
  8453. /**
  8454. * Samples the texture using an explicit gradient.
  8455. *
  8456. * @param {Node<vec2>} gradNodeX - The gradX node.
  8457. * @param {Node<vec2>} gradNodeY - The gradY node.
  8458. * @return {TextureNode} A texture node representing the texture sample.
  8459. */
  8460. grad( gradNodeX, gradNodeY ) {
  8461. const textureNode = this.clone();
  8462. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8463. textureNode.referenceNode = this.getBase();
  8464. return nodeObject( textureNode );
  8465. }
  8466. /**
  8467. * Samples the texture by defining a depth node.
  8468. *
  8469. * @param {Node<int>} depthNode - The depth node.
  8470. * @return {TextureNode} A texture node representing the texture sample.
  8471. */
  8472. depth( depthNode ) {
  8473. const textureNode = this.clone();
  8474. textureNode.depthNode = nodeObject( depthNode );
  8475. textureNode.referenceNode = this.getBase();
  8476. return nodeObject( textureNode );
  8477. }
  8478. /**
  8479. * Samples the texture by defining an offset node.
  8480. *
  8481. * @param {Node<ivec2>} offsetNode - The offset node.
  8482. * @return {TextureNode} A texture node representing the texture sample.
  8483. */
  8484. offset( offsetNode ) {
  8485. const textureNode = this.clone();
  8486. textureNode.offsetNode = nodeObject( offsetNode );
  8487. textureNode.referenceNode = this.getBase();
  8488. return nodeObject( textureNode );
  8489. }
  8490. // --
  8491. serialize( data ) {
  8492. super.serialize( data );
  8493. data.value = this.value.toJSON( data.meta ).uuid;
  8494. data.sampler = this.sampler;
  8495. data.updateMatrix = this.updateMatrix;
  8496. data.updateType = this.updateType;
  8497. }
  8498. deserialize( data ) {
  8499. super.deserialize( data );
  8500. this.value = data.meta.textures[ data.value ];
  8501. this.sampler = data.sampler;
  8502. this.updateMatrix = data.updateMatrix;
  8503. this.updateType = data.updateType;
  8504. }
  8505. /**
  8506. * The update is used to implement the update of the uv transformation matrix.
  8507. */
  8508. update() {
  8509. const texture = this.value;
  8510. const matrixUniform = this._matrixUniform;
  8511. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8512. if ( texture.matrixAutoUpdate === true ) {
  8513. texture.updateMatrix();
  8514. }
  8515. //
  8516. const flipYUniform = this._flipYUniform;
  8517. if ( flipYUniform !== null ) {
  8518. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8519. }
  8520. }
  8521. /**
  8522. * Clones the texture node.
  8523. *
  8524. * @return {TextureNode} The cloned texture node.
  8525. */
  8526. clone() {
  8527. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8528. newNode.sampler = this.sampler;
  8529. newNode.depthNode = this.depthNode;
  8530. newNode.compareNode = this.compareNode;
  8531. newNode.gradNode = this.gradNode;
  8532. newNode.offsetNode = this.offsetNode;
  8533. return newNode;
  8534. }
  8535. }
  8536. /**
  8537. * TSL function for creating a texture node.
  8538. *
  8539. * @tsl
  8540. * @function
  8541. * @param {?Texture} value - The texture.
  8542. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8543. * @param {?Node<int>} [levelNode=null] - The level node.
  8544. * @param {?Node<float>} [biasNode=null] - The bias node.
  8545. * @returns {TextureNode}
  8546. */
  8547. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8548. /**
  8549. * TSL function for creating a texture node or sample a texture node already existing.
  8550. *
  8551. * @tsl
  8552. * @function
  8553. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8554. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8555. * @param {?Node<int>} [levelNode=null] - The level node.
  8556. * @param {?Node<float>} [biasNode=null] - The bias node.
  8557. * @returns {TextureNode}
  8558. */
  8559. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8560. let textureNode;
  8561. if ( value && value.isTextureNode === true ) {
  8562. textureNode = nodeObject( value.clone() );
  8563. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8564. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8565. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8566. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8567. } else {
  8568. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8569. }
  8570. return textureNode;
  8571. };
  8572. /**
  8573. * TSL function for creating a uniform texture node.
  8574. *
  8575. * @tsl
  8576. * @function
  8577. * @param {?Texture} value - The texture.
  8578. * @returns {TextureNode}
  8579. */
  8580. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8581. /**
  8582. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8583. *
  8584. * @tsl
  8585. * @function
  8586. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8587. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8588. * @param {?Node<int>} [levelNode=null] - The level node.
  8589. * @param {?Node<float>} [biasNode=null] - The bias node.
  8590. * @returns {TextureNode}
  8591. */
  8592. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8593. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8594. /**
  8595. * Converts a texture or texture node to a sampler.
  8596. *
  8597. * @tsl
  8598. * @function
  8599. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8600. * @returns {Node}
  8601. */
  8602. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8603. /**
  8604. * Converts a texture or texture node to a sampler comparison.
  8605. *
  8606. * @tsl
  8607. * @function
  8608. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8609. * @returns {Node}
  8610. */
  8611. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8612. /**
  8613. * A special type of uniform node which represents array-like data
  8614. * as uniform buffers. The access usually happens via `element()`
  8615. * which returns an instance of {@link ArrayElementNode}. For example:
  8616. *
  8617. * ```js
  8618. * const bufferNode = buffer( array, 'mat4', count );
  8619. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8620. * ```
  8621. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8622. * since it handles more input types and automatically cares about buffer paddings.
  8623. *
  8624. * @augments UniformNode
  8625. */
  8626. class BufferNode extends UniformNode {
  8627. static get type() {
  8628. return 'BufferNode';
  8629. }
  8630. /**
  8631. * Constructs a new buffer node.
  8632. *
  8633. * @param {Array<number>} value - Array-like buffer data.
  8634. * @param {string} bufferType - The data type of the buffer.
  8635. * @param {number} [bufferCount=0] - The count of buffer elements.
  8636. */
  8637. constructor( value, bufferType, bufferCount = 0 ) {
  8638. super( value, bufferType );
  8639. /**
  8640. * This flag can be used for type testing.
  8641. *
  8642. * @type {boolean}
  8643. * @readonly
  8644. * @default true
  8645. */
  8646. this.isBufferNode = true;
  8647. /**
  8648. * The data type of the buffer.
  8649. *
  8650. * @type {string}
  8651. */
  8652. this.bufferType = bufferType;
  8653. /**
  8654. * The uniform node that holds the value of the reference node.
  8655. *
  8656. * @type {number}
  8657. * @default 0
  8658. */
  8659. this.bufferCount = bufferCount;
  8660. }
  8661. /**
  8662. * The data type of the buffer elements.
  8663. *
  8664. * @param {NodeBuilder} builder - The current node builder.
  8665. * @return {string} The element type.
  8666. */
  8667. getElementType( builder ) {
  8668. return this.getNodeType( builder );
  8669. }
  8670. /**
  8671. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8672. *
  8673. * @param {NodeBuilder} builder - The current node builder.
  8674. * @return {string} The input type.
  8675. */
  8676. getInputType( /*builder*/ ) {
  8677. return 'buffer';
  8678. }
  8679. }
  8680. /**
  8681. * TSL function for creating a buffer node.
  8682. *
  8683. * @tsl
  8684. * @function
  8685. * @param {Array<number>} value - Array-like buffer data.
  8686. * @param {string} type - The data type of a buffer element.
  8687. * @param {number} count - The count of buffer elements.
  8688. * @returns {BufferNode}
  8689. */
  8690. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8691. /**
  8692. * Represents the element access on uniform array nodes.
  8693. *
  8694. * @augments ArrayElementNode
  8695. */
  8696. class UniformArrayElementNode extends ArrayElementNode {
  8697. static get type() {
  8698. return 'UniformArrayElementNode';
  8699. }
  8700. /**
  8701. * Constructs a new buffer node.
  8702. *
  8703. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8704. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8705. */
  8706. constructor( uniformArrayNode, indexNode ) {
  8707. super( uniformArrayNode, indexNode );
  8708. /**
  8709. * This flag can be used for type testing.
  8710. *
  8711. * @type {boolean}
  8712. * @readonly
  8713. * @default true
  8714. */
  8715. this.isArrayBufferElementNode = true;
  8716. }
  8717. generate( builder ) {
  8718. const snippet = super.generate( builder );
  8719. const type = this.getNodeType();
  8720. const paddedType = this.node.getPaddedType();
  8721. return builder.format( snippet, paddedType, type );
  8722. }
  8723. }
  8724. /**
  8725. * Similar to {@link BufferNode} this module represents array-like data as
  8726. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8727. * data types in the array (e.g `three.js` primitives) and automatically
  8728. * manage buffer padding. It should be the first choice when working with
  8729. * uniforms buffers.
  8730. * ```js
  8731. * const tintColors = uniformArray( [
  8732. * new Color( 1, 0, 0 ),
  8733. * new Color( 0, 1, 0 ),
  8734. * new Color( 0, 0, 1 )
  8735. * ], 'color' );
  8736. *
  8737. * const redColor = tintColors.element( 0 );
  8738. *
  8739. * @augments BufferNode
  8740. */
  8741. class UniformArrayNode extends BufferNode {
  8742. static get type() {
  8743. return 'UniformArrayNode';
  8744. }
  8745. /**
  8746. * Constructs a new uniform array node.
  8747. *
  8748. * @param {Array<any>} value - Array holding the buffer data.
  8749. * @param {?string} [elementType=null] - The data type of a buffer element.
  8750. */
  8751. constructor( value, elementType = null ) {
  8752. super( null );
  8753. /**
  8754. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8755. * hold number primitives as well as three.js objects like vectors, matrices
  8756. * or colors.
  8757. *
  8758. * @type {Array<any>}
  8759. */
  8760. this.array = value;
  8761. /**
  8762. * The data type of an array element.
  8763. *
  8764. * @type {string}
  8765. */
  8766. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8767. /**
  8768. * The padded type. Uniform buffers must conform to a certain buffer layout
  8769. * so a separate type is computed to ensure correct buffer size.
  8770. *
  8771. * @type {string}
  8772. */
  8773. this.paddedType = this.getPaddedType();
  8774. /**
  8775. * Overwritten since uniform array nodes are updated per render.
  8776. *
  8777. * @type {string}
  8778. * @default 'render'
  8779. */
  8780. this.updateType = NodeUpdateType.RENDER;
  8781. /**
  8782. * This flag can be used for type testing.
  8783. *
  8784. * @type {boolean}
  8785. * @readonly
  8786. * @default true
  8787. */
  8788. this.isArrayBufferNode = true;
  8789. }
  8790. /**
  8791. * This method is overwritten since the node type is inferred from the
  8792. * {@link UniformArrayNode#paddedType}.
  8793. *
  8794. * @param {NodeBuilder} builder - The current node builder.
  8795. * @return {string} The node type.
  8796. */
  8797. getNodeType( /*builder*/ ) {
  8798. return this.paddedType;
  8799. }
  8800. /**
  8801. * The data type of the array elements.
  8802. *
  8803. * @param {NodeBuilder} builder - The current node builder.
  8804. * @return {string} The element type.
  8805. */
  8806. getElementType() {
  8807. return this.elementType;
  8808. }
  8809. /**
  8810. * Returns the padded type based on the element type.
  8811. *
  8812. * @return {string} The padded type.
  8813. */
  8814. getPaddedType() {
  8815. const elementType = this.elementType;
  8816. let paddedType = 'vec4';
  8817. if ( elementType === 'mat2' ) {
  8818. paddedType = 'mat2';
  8819. } else if ( /mat/.test( elementType ) === true ) {
  8820. paddedType = 'mat4';
  8821. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8822. paddedType = 'ivec4';
  8823. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8824. paddedType = 'uvec4';
  8825. }
  8826. return paddedType;
  8827. }
  8828. /**
  8829. * The update makes sure to correctly transfer the data from the (complex) objects
  8830. * in the array to the internal, correctly padded value buffer.
  8831. *
  8832. * @param {NodeFrame} frame - A reference to the current node frame.
  8833. */
  8834. update( /*frame*/ ) {
  8835. const { array, value } = this;
  8836. const elementType = this.elementType;
  8837. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8838. for ( let i = 0; i < array.length; i ++ ) {
  8839. const index = i * 4;
  8840. value[ index ] = array[ i ];
  8841. }
  8842. } else if ( elementType === 'color' ) {
  8843. for ( let i = 0; i < array.length; i ++ ) {
  8844. const index = i * 4;
  8845. const vector = array[ i ];
  8846. value[ index ] = vector.r;
  8847. value[ index + 1 ] = vector.g;
  8848. value[ index + 2 ] = vector.b || 0;
  8849. //value[ index + 3 ] = vector.a || 0;
  8850. }
  8851. } else if ( elementType === 'mat2' ) {
  8852. for ( let i = 0; i < array.length; i ++ ) {
  8853. const index = i * 4;
  8854. const matrix = array[ i ];
  8855. value[ index ] = matrix.elements[ 0 ];
  8856. value[ index + 1 ] = matrix.elements[ 1 ];
  8857. value[ index + 2 ] = matrix.elements[ 2 ];
  8858. value[ index + 3 ] = matrix.elements[ 3 ];
  8859. }
  8860. } else if ( elementType === 'mat3' ) {
  8861. for ( let i = 0; i < array.length; i ++ ) {
  8862. const index = i * 16;
  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 + 4 ] = matrix.elements[ 3 ];
  8868. value[ index + 5 ] = matrix.elements[ 4 ];
  8869. value[ index + 6 ] = matrix.elements[ 5 ];
  8870. value[ index + 8 ] = matrix.elements[ 6 ];
  8871. value[ index + 9 ] = matrix.elements[ 7 ];
  8872. value[ index + 10 ] = matrix.elements[ 8 ];
  8873. value[ index + 15 ] = 1;
  8874. }
  8875. } else if ( elementType === 'mat4' ) {
  8876. for ( let i = 0; i < array.length; i ++ ) {
  8877. const index = i * 16;
  8878. const matrix = array[ i ];
  8879. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8880. value[ index + i ] = matrix.elements[ i ];
  8881. }
  8882. }
  8883. } else {
  8884. for ( let i = 0; i < array.length; i ++ ) {
  8885. const index = i * 4;
  8886. const vector = array[ i ];
  8887. value[ index ] = vector.x;
  8888. value[ index + 1 ] = vector.y;
  8889. value[ index + 2 ] = vector.z || 0;
  8890. value[ index + 3 ] = vector.w || 0;
  8891. }
  8892. }
  8893. }
  8894. /**
  8895. * Implement the value buffer creation based on the array data.
  8896. *
  8897. * @param {NodeBuilder} builder - A reference to the current node builder.
  8898. * @return {null}
  8899. */
  8900. setup( builder ) {
  8901. const length = this.array.length;
  8902. const elementType = this.elementType;
  8903. let arrayType = Float32Array;
  8904. const paddedType = this.paddedType;
  8905. const paddedElementLength = builder.getTypeLength( paddedType );
  8906. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8907. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8908. this.value = new arrayType( length * paddedElementLength );
  8909. this.bufferCount = length;
  8910. this.bufferType = paddedType;
  8911. return super.setup( builder );
  8912. }
  8913. /**
  8914. * Overwrites the default `element()` method to provide element access
  8915. * based on {@link UniformArrayNode}.
  8916. *
  8917. * @param {IndexNode} indexNode - The index node.
  8918. * @return {UniformArrayElementNode}
  8919. */
  8920. element( indexNode ) {
  8921. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8922. }
  8923. }
  8924. /**
  8925. * TSL function for creating an uniform array node.
  8926. *
  8927. * @tsl
  8928. * @function
  8929. * @param {Array<any>} values - Array-like data.
  8930. * @param {?string} [nodeType] - The data type of the array elements.
  8931. * @returns {UniformArrayNode}
  8932. */
  8933. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8934. /**
  8935. * The node allows to set values for built-in shader variables. That is
  8936. * required for features like hardware-accelerated vertex clipping.
  8937. *
  8938. * @augments Node
  8939. */
  8940. class BuiltinNode extends Node {
  8941. /**
  8942. * Constructs a new builtin node.
  8943. *
  8944. * @param {string} name - The name of the built-in shader variable.
  8945. */
  8946. constructor( name ) {
  8947. super( 'float' );
  8948. /**
  8949. * The name of the built-in shader variable.
  8950. *
  8951. * @type {string}
  8952. */
  8953. this.name = name;
  8954. /**
  8955. * This flag can be used for type testing.
  8956. *
  8957. * @type {boolean}
  8958. * @readonly
  8959. * @default true
  8960. */
  8961. this.isBuiltinNode = true;
  8962. }
  8963. /**
  8964. * Generates the code snippet of the builtin node.
  8965. *
  8966. * @param {NodeBuilder} builder - The current node builder.
  8967. * @return {string} The generated code snippet.
  8968. */
  8969. generate( /* builder */ ) {
  8970. return this.name;
  8971. }
  8972. }
  8973. /**
  8974. * TSL function for creating a builtin node.
  8975. *
  8976. * @tsl
  8977. * @function
  8978. * @param {string} name - The name of the built-in shader variable.
  8979. * @returns {BuiltinNode}
  8980. */
  8981. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8982. let _screenSizeVec, _viewportVec;
  8983. /**
  8984. * This node provides a collection of screen related metrics.
  8985. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8986. * resolution or viewport data as well as fragment or uv coordinates.
  8987. *
  8988. * @augments Node
  8989. */
  8990. class ScreenNode extends Node {
  8991. static get type() {
  8992. return 'ScreenNode';
  8993. }
  8994. /**
  8995. * Constructs a new screen node.
  8996. *
  8997. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  8998. */
  8999. constructor( scope ) {
  9000. super();
  9001. /**
  9002. * The node represents different metric depending on which scope is selected.
  9003. *
  9004. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9005. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9006. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9007. * - `ScreenNode.UV`: Normalized coordinates.
  9008. * - `ScreenNode.DPR`: Device pixel ratio.
  9009. *
  9010. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9011. */
  9012. this.scope = scope;
  9013. /**
  9014. * This output node.
  9015. *
  9016. * @type {?Node}
  9017. * @default null
  9018. */
  9019. this._output = null;
  9020. /**
  9021. * This flag can be used for type testing.
  9022. *
  9023. * @type {boolean}
  9024. * @readonly
  9025. * @default true
  9026. */
  9027. this.isViewportNode = true;
  9028. }
  9029. /**
  9030. * This method is overwritten since the node type depends on the selected scope.
  9031. *
  9032. * @return {('float'|'vec2'|'vec4')} The node type.
  9033. */
  9034. getNodeType() {
  9035. if ( this.scope === ScreenNode.DPR ) return 'float';
  9036. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9037. else return 'vec2';
  9038. }
  9039. /**
  9040. * This method is overwritten since the node's update type depends on the selected scope.
  9041. *
  9042. * @return {NodeUpdateType} The update type.
  9043. */
  9044. getUpdateType() {
  9045. let updateType = NodeUpdateType.NONE;
  9046. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9047. updateType = NodeUpdateType.RENDER;
  9048. }
  9049. this.updateType = updateType;
  9050. return updateType;
  9051. }
  9052. /**
  9053. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9054. * from the current renderer.
  9055. *
  9056. * @param {NodeFrame} frame - A reference to the current node frame.
  9057. */
  9058. update( { renderer } ) {
  9059. const renderTarget = renderer.getRenderTarget();
  9060. if ( this.scope === ScreenNode.VIEWPORT ) {
  9061. if ( renderTarget !== null ) {
  9062. _viewportVec.copy( renderTarget.viewport );
  9063. } else {
  9064. renderer.getViewport( _viewportVec );
  9065. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9066. }
  9067. } else if ( this.scope === ScreenNode.DPR ) {
  9068. this._output.value = renderer.getPixelRatio();
  9069. } else {
  9070. if ( renderTarget !== null ) {
  9071. _screenSizeVec.width = renderTarget.width;
  9072. _screenSizeVec.height = renderTarget.height;
  9073. } else {
  9074. renderer.getDrawingBufferSize( _screenSizeVec );
  9075. }
  9076. }
  9077. }
  9078. setup( /*builder*/ ) {
  9079. const scope = this.scope;
  9080. let output = null;
  9081. if ( scope === ScreenNode.SIZE ) {
  9082. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9083. } else if ( scope === ScreenNode.VIEWPORT ) {
  9084. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9085. } else if ( scope === ScreenNode.DPR ) {
  9086. output = uniform( 1 );
  9087. } else {
  9088. output = vec2( screenCoordinate.div( screenSize ) );
  9089. }
  9090. this._output = output;
  9091. return output;
  9092. }
  9093. generate( builder ) {
  9094. if ( this.scope === ScreenNode.COORDINATE ) {
  9095. let coord = builder.getFragCoord();
  9096. if ( builder.isFlipY() ) {
  9097. // follow webgpu standards
  9098. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9099. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9100. }
  9101. return coord;
  9102. }
  9103. return super.generate( builder );
  9104. }
  9105. }
  9106. ScreenNode.COORDINATE = 'coordinate';
  9107. ScreenNode.VIEWPORT = 'viewport';
  9108. ScreenNode.SIZE = 'size';
  9109. ScreenNode.UV = 'uv';
  9110. ScreenNode.DPR = 'dpr';
  9111. // Screen
  9112. /**
  9113. * TSL object that represents the current DPR.
  9114. *
  9115. * @tsl
  9116. * @type {ScreenNode<float>}
  9117. */
  9118. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9119. /**
  9120. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9121. *
  9122. * @tsl
  9123. * @type {ScreenNode<vec2>}
  9124. */
  9125. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9126. /**
  9127. * TSL object that represents the screen resolution in physical pixel units.
  9128. *
  9129. * @tsl
  9130. * @type {ScreenNode<vec2>}
  9131. */
  9132. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9133. /**
  9134. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9135. *
  9136. * @tsl
  9137. * @type {ScreenNode<vec2>}
  9138. */
  9139. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9140. // Viewport
  9141. /**
  9142. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9143. *
  9144. * @tsl
  9145. * @type {ScreenNode<vec4>}
  9146. */
  9147. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9148. /**
  9149. * TSL object that represents the viewport resolution in physical pixel units.
  9150. *
  9151. * @tsl
  9152. * @type {ScreenNode<vec2>}
  9153. */
  9154. const viewportSize = viewport.zw;
  9155. /**
  9156. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9157. *
  9158. * @tsl
  9159. * @type {ScreenNode<vec2>}
  9160. */
  9161. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9162. /**
  9163. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9164. *
  9165. * @tsl
  9166. * @type {ScreenNode<vec2>}
  9167. */
  9168. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9169. // Deprecated
  9170. /**
  9171. * @deprecated since r169. Use {@link screenSize} instead.
  9172. */
  9173. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9174. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9175. return screenSize;
  9176. }, 'vec2' ).once() )();
  9177. /**
  9178. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9179. *
  9180. * @tsl
  9181. * @type {UniformNode<uint>}
  9182. */
  9183. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9184. /**
  9185. * TSL object that represents the `near` value of the camera used for the current render.
  9186. *
  9187. * @tsl
  9188. * @type {UniformNode<float>}
  9189. */
  9190. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9191. /**
  9192. * TSL object that represents the `far` value of the camera used for the current render.
  9193. *
  9194. * @tsl
  9195. * @type {UniformNode<float>}
  9196. */
  9197. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9198. /**
  9199. * TSL object that represents the projection matrix of the camera used for the current render.
  9200. *
  9201. * @tsl
  9202. * @type {UniformNode<mat4>}
  9203. */
  9204. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9205. let cameraProjectionMatrix;
  9206. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9207. const matrices = [];
  9208. for ( const subCamera of camera.cameras ) {
  9209. matrices.push( subCamera.projectionMatrix );
  9210. }
  9211. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9212. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9213. } else {
  9214. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9215. }
  9216. return cameraProjectionMatrix;
  9217. } ).once() )();
  9218. /**
  9219. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9220. *
  9221. * @tsl
  9222. * @type {UniformNode<mat4>}
  9223. */
  9224. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9225. let cameraProjectionMatrixInverse;
  9226. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9227. const matrices = [];
  9228. for ( const subCamera of camera.cameras ) {
  9229. matrices.push( subCamera.projectionMatrixInverse );
  9230. }
  9231. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9232. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9233. } else {
  9234. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9235. }
  9236. return cameraProjectionMatrixInverse;
  9237. } ).once() )();
  9238. /**
  9239. * TSL object that represents the view matrix of the camera used for the current render.
  9240. *
  9241. * @tsl
  9242. * @type {UniformNode<mat4>}
  9243. */
  9244. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9245. let cameraViewMatrix;
  9246. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9247. const matrices = [];
  9248. for ( const subCamera of camera.cameras ) {
  9249. matrices.push( subCamera.matrixWorldInverse );
  9250. }
  9251. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9252. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9253. } else {
  9254. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9255. }
  9256. return cameraViewMatrix;
  9257. } ).once() )();
  9258. /**
  9259. * TSL object that represents the world matrix of the camera used for the current render.
  9260. *
  9261. * @tsl
  9262. * @type {UniformNode<mat4>}
  9263. */
  9264. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9265. let cameraWorldMatrix;
  9266. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9267. const matrices = [];
  9268. for ( const subCamera of camera.cameras ) {
  9269. matrices.push( subCamera.matrixWorld );
  9270. }
  9271. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9272. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9273. } else {
  9274. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9275. }
  9276. return cameraWorldMatrix;
  9277. } ).once() )();
  9278. /**
  9279. * TSL object that represents the normal matrix of the camera used for the current render.
  9280. *
  9281. * @tsl
  9282. * @type {UniformNode<mat3>}
  9283. */
  9284. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9285. let cameraNormalMatrix;
  9286. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9287. const matrices = [];
  9288. for ( const subCamera of camera.cameras ) {
  9289. matrices.push( subCamera.normalMatrix );
  9290. }
  9291. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9292. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9293. } else {
  9294. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9295. }
  9296. return cameraNormalMatrix;
  9297. } ).once() )();
  9298. /**
  9299. * TSL object that represents the position in world space of the camera used for the current render.
  9300. *
  9301. * @tsl
  9302. * @type {UniformNode<vec3>}
  9303. */
  9304. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9305. let cameraPosition;
  9306. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9307. const positions = [];
  9308. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9309. positions.push( new Vector3() );
  9310. }
  9311. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9312. const subCameras = camera.cameras;
  9313. const array = self.array;
  9314. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9315. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9316. }
  9317. } );
  9318. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9319. } else {
  9320. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9321. }
  9322. return cameraPosition;
  9323. } ).once() )();
  9324. /**
  9325. * TSL object that represents the viewport of the camera used for the current render.
  9326. *
  9327. * @tsl
  9328. * @type {UniformNode<vec4>}
  9329. */
  9330. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9331. let cameraViewport;
  9332. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9333. const viewports = [];
  9334. for ( const subCamera of camera.cameras ) {
  9335. viewports.push( subCamera.viewport );
  9336. }
  9337. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9338. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9339. } else {
  9340. // Fallback for single camera
  9341. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9342. }
  9343. return cameraViewport;
  9344. } ).once() )();
  9345. const _sphere = /*@__PURE__*/ new Sphere();
  9346. /**
  9347. * This node can be used to access transformation related metrics of 3D objects.
  9348. * Depending on the selected scope, a different metric is represented as a uniform
  9349. * in the shader. The following scopes are supported:
  9350. *
  9351. * - `POSITION`: The object's position in world space.
  9352. * - `VIEW_POSITION`: The object's position in view/camera space.
  9353. * - `DIRECTION`: The object's direction in world space.
  9354. * - `SCALE`: The object's scale in world space.
  9355. * - `WORLD_MATRIX`: The object's matrix in world space.
  9356. *
  9357. * @augments Node
  9358. */
  9359. class Object3DNode extends Node {
  9360. static get type() {
  9361. return 'Object3DNode';
  9362. }
  9363. /**
  9364. * Constructs a new object 3D node.
  9365. *
  9366. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9367. * @param {?Object3D} [object3d=null] - The 3D object.
  9368. */
  9369. constructor( scope, object3d = null ) {
  9370. super();
  9371. /**
  9372. * The node reports a different type of transformation depending on the scope.
  9373. *
  9374. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9375. */
  9376. this.scope = scope;
  9377. /**
  9378. * The 3D object.
  9379. *
  9380. * @type {?Object3D}
  9381. * @default null
  9382. */
  9383. this.object3d = object3d;
  9384. /**
  9385. * Overwritten since this type of node is updated per object.
  9386. *
  9387. * @type {string}
  9388. * @default 'object'
  9389. */
  9390. this.updateType = NodeUpdateType.OBJECT;
  9391. /**
  9392. * Holds the value of the node as a uniform.
  9393. *
  9394. * @type {UniformNode}
  9395. */
  9396. this.uniformNode = new UniformNode( null );
  9397. }
  9398. /**
  9399. * Overwritten since the node type is inferred from the scope.
  9400. *
  9401. * @return {('mat4'|'vec3'|'float')} The node type.
  9402. */
  9403. getNodeType() {
  9404. const scope = this.scope;
  9405. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9406. return 'mat4';
  9407. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9408. return 'vec3';
  9409. } else if ( scope === Object3DNode.RADIUS ) {
  9410. return 'float';
  9411. }
  9412. }
  9413. /**
  9414. * Updates the uniform value depending on the scope.
  9415. *
  9416. * @param {NodeFrame} frame - The current node frame.
  9417. */
  9418. update( frame ) {
  9419. const object = this.object3d;
  9420. const uniformNode = this.uniformNode;
  9421. const scope = this.scope;
  9422. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9423. uniformNode.value = object.matrixWorld;
  9424. } else if ( scope === Object3DNode.POSITION ) {
  9425. uniformNode.value = uniformNode.value || new Vector3();
  9426. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9427. } else if ( scope === Object3DNode.SCALE ) {
  9428. uniformNode.value = uniformNode.value || new Vector3();
  9429. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9430. } else if ( scope === Object3DNode.DIRECTION ) {
  9431. uniformNode.value = uniformNode.value || new Vector3();
  9432. object.getWorldDirection( uniformNode.value );
  9433. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9434. const camera = frame.camera;
  9435. uniformNode.value = uniformNode.value || new Vector3();
  9436. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9437. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9438. } else if ( scope === Object3DNode.RADIUS ) {
  9439. const geometry = frame.object.geometry;
  9440. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9441. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9442. uniformNode.value = _sphere.radius;
  9443. }
  9444. }
  9445. /**
  9446. * Generates the code snippet of the uniform node. The node type of the uniform
  9447. * node also depends on the selected scope.
  9448. *
  9449. * @param {NodeBuilder} builder - The current node builder.
  9450. * @return {string} The generated code snippet.
  9451. */
  9452. generate( builder ) {
  9453. const scope = this.scope;
  9454. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9455. this.uniformNode.nodeType = 'mat4';
  9456. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9457. this.uniformNode.nodeType = 'vec3';
  9458. } else if ( scope === Object3DNode.RADIUS ) {
  9459. this.uniformNode.nodeType = 'float';
  9460. }
  9461. return this.uniformNode.build( builder );
  9462. }
  9463. serialize( data ) {
  9464. super.serialize( data );
  9465. data.scope = this.scope;
  9466. }
  9467. deserialize( data ) {
  9468. super.deserialize( data );
  9469. this.scope = data.scope;
  9470. }
  9471. }
  9472. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9473. Object3DNode.POSITION = 'position';
  9474. Object3DNode.SCALE = 'scale';
  9475. Object3DNode.VIEW_POSITION = 'viewPosition';
  9476. Object3DNode.DIRECTION = 'direction';
  9477. Object3DNode.RADIUS = 'radius';
  9478. /**
  9479. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9480. *
  9481. * @tsl
  9482. * @function
  9483. * @param {?Object3D} [object3d] - The 3D object.
  9484. * @returns {Object3DNode<vec3>}
  9485. */
  9486. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9487. /**
  9488. * TSL function for creating an object 3D node that represents the object's world matrix.
  9489. *
  9490. * @tsl
  9491. * @function
  9492. * @param {?Object3D} [object3d] - The 3D object.
  9493. * @returns {Object3DNode<mat4>}
  9494. */
  9495. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9496. /**
  9497. * TSL function for creating an object 3D node that represents the object's position in world space.
  9498. *
  9499. * @tsl
  9500. * @function
  9501. * @param {?Object3D} [object3d] - The 3D object.
  9502. * @returns {Object3DNode<vec3>}
  9503. */
  9504. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9505. /**
  9506. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9507. *
  9508. * @tsl
  9509. * @function
  9510. * @param {?Object3D} [object3d] - The 3D object.
  9511. * @returns {Object3DNode<vec3>}
  9512. */
  9513. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9514. /**
  9515. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9516. *
  9517. * @tsl
  9518. * @function
  9519. * @param {?Object3D} [object3d] - The 3D object.
  9520. * @returns {Object3DNode<vec3>}
  9521. */
  9522. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9523. /**
  9524. * TSL function for creating an object 3D node that represents the object's radius.
  9525. *
  9526. * @tsl
  9527. * @function
  9528. * @param {?Object3D} [object3d] - The 3D object.
  9529. * @returns {Object3DNode<float>}
  9530. */
  9531. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9532. /**
  9533. * This type of node is a specialized version of `Object3DNode`
  9534. * with larger set of model related metrics. Unlike `Object3DNode`,
  9535. * `ModelNode` extracts the reference to the 3D object from the
  9536. * current node frame state.
  9537. *
  9538. * @augments Object3DNode
  9539. */
  9540. class ModelNode extends Object3DNode {
  9541. static get type() {
  9542. return 'ModelNode';
  9543. }
  9544. /**
  9545. * Constructs a new object model node.
  9546. *
  9547. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9548. */
  9549. constructor( scope ) {
  9550. super( scope );
  9551. }
  9552. /**
  9553. * Extracts the model reference from the frame state and then
  9554. * updates the uniform value depending on the scope.
  9555. *
  9556. * @param {NodeFrame} frame - The current node frame.
  9557. */
  9558. update( frame ) {
  9559. this.object3d = frame.object;
  9560. super.update( frame );
  9561. }
  9562. }
  9563. /**
  9564. * TSL object that represents the object's direction in world space.
  9565. *
  9566. * @tsl
  9567. * @type {ModelNode<vec3>}
  9568. */
  9569. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9570. /**
  9571. * TSL object that represents the object's world matrix.
  9572. *
  9573. * @tsl
  9574. * @type {ModelNode<mat4>}
  9575. */
  9576. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9577. /**
  9578. * TSL object that represents the object's position in world space.
  9579. *
  9580. * @tsl
  9581. * @type {ModelNode<vec3>}
  9582. */
  9583. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9584. /**
  9585. * TSL object that represents the object's scale in world space.
  9586. *
  9587. * @tsl
  9588. * @type {ModelNode<vec3>}
  9589. */
  9590. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9591. /**
  9592. * TSL object that represents the object's position in view/camera space.
  9593. *
  9594. * @tsl
  9595. * @type {ModelNode<vec3>}
  9596. */
  9597. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9598. /**
  9599. * TSL object that represents the object's radius.
  9600. *
  9601. * @tsl
  9602. * @type {ModelNode<float>}
  9603. */
  9604. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9605. /**
  9606. * TSL object that represents the object's normal matrix.
  9607. *
  9608. * @tsl
  9609. * @type {UniformNode<mat3>}
  9610. */
  9611. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9612. /**
  9613. * TSL object that represents the object's inverse world matrix.
  9614. *
  9615. * @tsl
  9616. * @type {UniformNode<mat4>}
  9617. */
  9618. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9619. /**
  9620. * TSL object that represents the object's model view matrix.
  9621. *
  9622. * @tsl
  9623. * @type {Node<mat4>}
  9624. */
  9625. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9626. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9627. } ).once() )().toVar( 'modelViewMatrix' );
  9628. // GPU Precision
  9629. /**
  9630. * TSL object that represents the object's model view in `mediump` precision.
  9631. *
  9632. * @tsl
  9633. * @type {Node<mat4>}
  9634. */
  9635. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9636. // CPU Precision
  9637. /**
  9638. * TSL object that represents the object's model view in `highp` precision
  9639. * which is achieved by computing the matrix in JS and not in the shader.
  9640. *
  9641. * @tsl
  9642. * @type {Node<mat4>}
  9643. */
  9644. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9645. builder.context.isHighPrecisionModelViewMatrix = true;
  9646. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9647. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9648. } );
  9649. } ).once() )().toVar( 'highpModelViewMatrix' );
  9650. /**
  9651. * TSL object that represents the object's model normal view in `highp` precision
  9652. * which is achieved by computing the matrix in JS and not in the shader.
  9653. *
  9654. * @tsl
  9655. * @type {Node<mat3>}
  9656. */
  9657. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9658. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9659. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9660. if ( isHighPrecisionModelViewMatrix !== true ) {
  9661. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9662. }
  9663. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9664. } );
  9665. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9666. /**
  9667. * TSL object that represents the position attribute of the current rendered object.
  9668. *
  9669. * @tsl
  9670. * @type {AttributeNode<vec3>}
  9671. */
  9672. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9673. /**
  9674. * TSL object that represents the vertex position in local space of the current rendered object.
  9675. *
  9676. * @tsl
  9677. * @type {AttributeNode<vec3>}
  9678. */
  9679. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9680. /**
  9681. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9682. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9683. *
  9684. * @tsl
  9685. * @type {AttributeNode<vec3>}
  9686. */
  9687. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9688. /**
  9689. * TSL object that represents the vertex position in world space of the current rendered object.
  9690. *
  9691. * @tsl
  9692. * @type {VaryingNode<vec3>}
  9693. */
  9694. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9695. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9696. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9697. /**
  9698. * TSL object that represents the position world direction of the current rendered object.
  9699. *
  9700. * @tsl
  9701. * @type {Node<vec3>}
  9702. */
  9703. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9704. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9705. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9706. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9707. /**
  9708. * TSL object that represents the vertex position in view space of the current rendered object.
  9709. *
  9710. * @tsl
  9711. * @type {VaryingNode<vec3>}
  9712. */
  9713. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9714. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9715. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9716. /**
  9717. * TSL object that represents the position view direction of the current rendered object.
  9718. *
  9719. * @tsl
  9720. * @type {VaryingNode<vec3>}
  9721. */
  9722. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9723. /**
  9724. * This node can be used to evaluate whether a primitive is front or back facing.
  9725. *
  9726. * @augments Node
  9727. */
  9728. class FrontFacingNode extends Node {
  9729. static get type() {
  9730. return 'FrontFacingNode';
  9731. }
  9732. /**
  9733. * Constructs a new front facing node.
  9734. */
  9735. constructor() {
  9736. super( 'bool' );
  9737. /**
  9738. * This flag can be used for type testing.
  9739. *
  9740. * @type {boolean}
  9741. * @readonly
  9742. * @default true
  9743. */
  9744. this.isFrontFacingNode = true;
  9745. }
  9746. generate( builder ) {
  9747. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9748. //
  9749. const { material } = builder;
  9750. if ( material.side === BackSide ) {
  9751. return 'false';
  9752. }
  9753. return builder.getFrontFacing();
  9754. }
  9755. }
  9756. /**
  9757. * TSL object that represents whether a primitive is front or back facing
  9758. *
  9759. * @tsl
  9760. * @type {FrontFacingNode<bool>}
  9761. */
  9762. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9763. /**
  9764. * TSL object that represents the front facing status as a number instead of a bool.
  9765. * `1` means front facing, `-1` means back facing.
  9766. *
  9767. * @tsl
  9768. * @type {Node<float>}
  9769. */
  9770. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9771. /**
  9772. * Converts a direction vector to a face direction vector based on the material's side.
  9773. *
  9774. * If the material is set to `BackSide`, the direction is inverted.
  9775. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9776. *
  9777. * @tsl
  9778. * @param {Node<vec3>} direction - The direction vector to convert.
  9779. * @returns {Node<vec3>} The converted direction vector.
  9780. */
  9781. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9782. const side = material.side;
  9783. if ( side === BackSide ) {
  9784. direction = direction.mul( -1 );
  9785. } else if ( side === DoubleSide ) {
  9786. direction = direction.mul( faceDirection );
  9787. }
  9788. return direction;
  9789. } );
  9790. /**
  9791. * TSL object that represents the normal attribute of the current rendered object in local space.
  9792. *
  9793. * @tsl
  9794. * @type {Node<vec3>}
  9795. */
  9796. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9797. /**
  9798. * TSL object that represents the vertex normal of the current rendered object in local space.
  9799. *
  9800. * @tsl
  9801. * @type {Node<vec3>}
  9802. */
  9803. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9804. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9805. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9806. return vec3( 0, 1, 0 );
  9807. }
  9808. return normalGeometry;
  9809. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9810. /**
  9811. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9812. *
  9813. * @tsl
  9814. * @type {Node<vec3>}
  9815. */
  9816. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9817. /**
  9818. * TSL object that represents the vertex normal of the current rendered object in view space.
  9819. *
  9820. * @tsl
  9821. * @type {Node<vec3>}
  9822. */
  9823. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9824. let node;
  9825. if ( builder.material.flatShading === true ) {
  9826. node = normalFlat;
  9827. } else {
  9828. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9829. }
  9830. return node;
  9831. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9832. /**
  9833. * TSL object that represents the vertex normal of the current rendered object in world space.
  9834. *
  9835. * @tsl
  9836. * @type {Node<vec3>}
  9837. */
  9838. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9839. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9840. if ( builder.material.flatShading !== true ) {
  9841. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9842. }
  9843. return normal.normalize().toVar( 'normalWorldGeometry' );
  9844. }, 'vec3' ).once() )();
  9845. /**
  9846. * TSL object that represents the vertex normal of the current rendered object in view space.
  9847. *
  9848. * @tsl
  9849. * @type {Node<vec3>}
  9850. */
  9851. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9852. let node;
  9853. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9854. node = normalViewGeometry;
  9855. if ( material.flatShading !== true ) {
  9856. node = directionToFaceDirection( node );
  9857. }
  9858. } else {
  9859. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9860. node = context.setupNormal().context( { getUV: null } );
  9861. }
  9862. return node;
  9863. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9864. /**
  9865. * TSL object that represents the vertex normal of the current rendered object in world space.
  9866. *
  9867. * @tsl
  9868. * @type {Node<vec3>}
  9869. */
  9870. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9871. /**
  9872. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9873. *
  9874. * @tsl
  9875. * @type {Node<vec3>}
  9876. */
  9877. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9878. let node;
  9879. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9880. node = normalView;
  9881. } else {
  9882. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9883. node = context.setupClearcoatNormal().context( { getUV: null } );
  9884. }
  9885. return node;
  9886. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9887. /**
  9888. * Transforms the normal with the given matrix.
  9889. *
  9890. * @tsl
  9891. * @function
  9892. * @param {Node<vec3>} normal - The normal.
  9893. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9894. * @return {Node<vec3>} The transformed normal.
  9895. */
  9896. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9897. const m = mat3( matrix );
  9898. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9899. return m.mul( transformedNormal ).xyz;
  9900. } );
  9901. /**
  9902. * Transforms the given normal from local to view space.
  9903. *
  9904. * @tsl
  9905. * @function
  9906. * @param {Node<vec3>} normal - The normal.
  9907. * @param {NodeBuilder} builder - The current node builder.
  9908. * @return {Node<vec3>} The transformed normal.
  9909. */
  9910. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9911. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9912. if ( modelNormalViewMatrix !== null ) {
  9913. return modelNormalViewMatrix.transformDirection( normal );
  9914. }
  9915. //
  9916. const transformedNormal = modelNormalMatrix.mul( normal );
  9917. return cameraViewMatrix.transformDirection( transformedNormal );
  9918. } );
  9919. // Deprecated
  9920. /**
  9921. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9922. *
  9923. * @tsl
  9924. * @type {Node<vec3>}
  9925. * @deprecated since r178. Use `normalView` instead.
  9926. */
  9927. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9928. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9929. return normalView;
  9930. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9931. /**
  9932. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9933. *
  9934. * @tsl
  9935. * @type {Node<vec3>}
  9936. * @deprecated since r178. Use `normalWorld` instead.
  9937. */
  9938. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9939. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9940. return normalWorld;
  9941. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9942. /**
  9943. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9944. *
  9945. * @tsl
  9946. * @type {Node<vec3>}
  9947. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9948. */
  9949. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9950. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9951. return clearcoatNormalView;
  9952. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9953. const _e1$1 = /*@__PURE__*/ new Euler();
  9954. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9955. /**
  9956. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9957. *
  9958. * @tsl
  9959. * @type {UniformNode<float>}
  9960. */
  9961. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9962. /**
  9963. * TSL object that represents the intensity of environment maps of PBR materials.
  9964. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9965. *
  9966. * @tsl
  9967. * @type {Node<float>}
  9968. */
  9969. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9970. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9971. } );
  9972. /**
  9973. * TSL object that represents the rotation of environment maps.
  9974. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9975. * rotation of `scene.environment` instead.
  9976. *
  9977. * @tsl
  9978. * @type {Node<mat4>}
  9979. */
  9980. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9981. return frame.material;
  9982. } ).onObjectUpdate( function ( { material, scene } ) {
  9983. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9984. if ( rotation ) {
  9985. _e1$1.copy( rotation );
  9986. _m1$1.makeRotationFromEuler( _e1$1 );
  9987. } else {
  9988. _m1$1.identity();
  9989. }
  9990. return _m1$1;
  9991. } );
  9992. /**
  9993. * The reflect vector in view space.
  9994. *
  9995. * @tsl
  9996. * @type {Node<vec3>}
  9997. */
  9998. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9999. /**
  10000. * The refract vector in view space.
  10001. *
  10002. * @tsl
  10003. * @type {Node<vec3>}
  10004. */
  10005. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10006. /**
  10007. * Used for sampling cube maps when using cube reflection mapping.
  10008. *
  10009. * @tsl
  10010. * @type {Node<vec3>}
  10011. */
  10012. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10013. /**
  10014. * Used for sampling cube maps when using cube refraction mapping.
  10015. *
  10016. * @tsl
  10017. * @type {Node<vec3>}
  10018. */
  10019. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10020. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10021. /**
  10022. * This type of uniform node represents a cube texture.
  10023. *
  10024. * @augments TextureNode
  10025. */
  10026. class CubeTextureNode extends TextureNode {
  10027. static get type() {
  10028. return 'CubeTextureNode';
  10029. }
  10030. /**
  10031. * Constructs a new cube texture node.
  10032. *
  10033. * @param {CubeTexture} value - The cube texture.
  10034. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10035. * @param {?Node<int>} [levelNode=null] - The level node.
  10036. * @param {?Node<float>} [biasNode=null] - The bias node.
  10037. */
  10038. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10039. super( value, uvNode, levelNode, biasNode );
  10040. /**
  10041. * This flag can be used for type testing.
  10042. *
  10043. * @type {boolean}
  10044. * @readonly
  10045. * @default true
  10046. */
  10047. this.isCubeTextureNode = true;
  10048. }
  10049. /**
  10050. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10051. *
  10052. * @param {NodeBuilder} builder - The current node builder.
  10053. * @return {string} The input type.
  10054. */
  10055. getInputType( /*builder*/ ) {
  10056. return 'cubeTexture';
  10057. }
  10058. /**
  10059. * Returns a default uvs based on the mapping type of the cube texture.
  10060. *
  10061. * @return {Node<vec3>} The default uv attribute.
  10062. */
  10063. getDefaultUV() {
  10064. const texture = this.value;
  10065. if ( texture.mapping === CubeReflectionMapping ) {
  10066. return reflectVector;
  10067. } else if ( texture.mapping === CubeRefractionMapping ) {
  10068. return refractVector;
  10069. } else {
  10070. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10071. return vec3( 0, 0, 0 );
  10072. }
  10073. }
  10074. /**
  10075. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10076. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10077. *
  10078. * @param {boolean} value - The update toggle.
  10079. */
  10080. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10081. /**
  10082. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10083. * to modify the uv node for correct sampling.
  10084. *
  10085. * @param {NodeBuilder} builder - The current node builder.
  10086. * @param {Node} uvNode - The uv node to setup.
  10087. * @return {Node} The updated uv node.
  10088. */
  10089. setupUV( builder, uvNode ) {
  10090. const texture = this.value;
  10091. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10092. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10093. }
  10094. return materialEnvRotation.mul( uvNode );
  10095. }
  10096. /**
  10097. * Generates the uv code snippet.
  10098. *
  10099. * @param {NodeBuilder} builder - The current node builder.
  10100. * @param {Node} cubeUV - The uv node to generate code for.
  10101. * @return {string} The generated code snippet.
  10102. */
  10103. generateUV( builder, cubeUV ) {
  10104. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10105. }
  10106. }
  10107. /**
  10108. * TSL function for creating a cube texture node.
  10109. *
  10110. * @tsl
  10111. * @function
  10112. * @param {CubeTexture} value - The cube texture.
  10113. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10114. * @param {?Node<int>} [levelNode=null] - The level node.
  10115. * @param {?Node<float>} [biasNode=null] - The bias node.
  10116. * @returns {CubeTextureNode}
  10117. */
  10118. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10119. /**
  10120. * TSL function for creating a cube texture uniform node.
  10121. *
  10122. * @tsl
  10123. * @function
  10124. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10125. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10126. * @param {?Node<int>} [levelNode=null] - The level node.
  10127. * @param {?Node<float>} [biasNode=null] - The bias node.
  10128. * @returns {CubeTextureNode}
  10129. */
  10130. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10131. let textureNode;
  10132. if ( value && value.isCubeTextureNode === true ) {
  10133. textureNode = nodeObject( value.clone() );
  10134. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10135. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10136. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10137. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10138. } else {
  10139. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10140. }
  10141. return textureNode;
  10142. };
  10143. /**
  10144. * TSL function for creating a uniform cube texture node.
  10145. *
  10146. * @tsl
  10147. * @function
  10148. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10149. * @returns {CubeTextureNode}
  10150. */
  10151. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10152. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10153. /**
  10154. * This class is only relevant if the referenced property is array-like.
  10155. * In this case, `ReferenceElementNode` allows to refer to a specific
  10156. * element inside the data structure via an index.
  10157. *
  10158. * @augments ArrayElementNode
  10159. */
  10160. class ReferenceElementNode extends ArrayElementNode {
  10161. static get type() {
  10162. return 'ReferenceElementNode';
  10163. }
  10164. /**
  10165. * Constructs a new reference element node.
  10166. *
  10167. * @param {?ReferenceNode} referenceNode - The reference node.
  10168. * @param {Node} indexNode - The index node that defines the element access.
  10169. */
  10170. constructor( referenceNode, indexNode ) {
  10171. super( referenceNode, indexNode );
  10172. /**
  10173. * Similar to {@link ReferenceNode#reference}, an additional
  10174. * property references to the current node.
  10175. *
  10176. * @type {?ReferenceNode}
  10177. * @default null
  10178. */
  10179. this.referenceNode = referenceNode;
  10180. /**
  10181. * This flag can be used for type testing.
  10182. *
  10183. * @type {boolean}
  10184. * @readonly
  10185. * @default true
  10186. */
  10187. this.isReferenceElementNode = true;
  10188. }
  10189. /**
  10190. * This method is overwritten since the node type is inferred from
  10191. * the uniform type of the reference node.
  10192. *
  10193. * @return {string} The node type.
  10194. */
  10195. getNodeType() {
  10196. return this.referenceNode.uniformType;
  10197. }
  10198. generate( builder ) {
  10199. const snippet = super.generate( builder );
  10200. const arrayType = this.referenceNode.getNodeType();
  10201. const elementType = this.getNodeType();
  10202. return builder.format( snippet, arrayType, elementType );
  10203. }
  10204. }
  10205. /**
  10206. * This type of node establishes a reference to a property of another object.
  10207. * In this way, the value of the node is automatically linked to the value of
  10208. * referenced object. Reference nodes internally represent the linked value
  10209. * as a uniform.
  10210. *
  10211. * @augments Node
  10212. */
  10213. class ReferenceNode extends Node {
  10214. static get type() {
  10215. return 'ReferenceNode';
  10216. }
  10217. /**
  10218. * Constructs a new reference node.
  10219. *
  10220. * @param {string} property - The name of the property the node refers to.
  10221. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10222. * @param {?Object} [object=null] - The object the property belongs to.
  10223. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10224. */
  10225. constructor( property, uniformType, object = null, count = null ) {
  10226. super();
  10227. /**
  10228. * The name of the property the node refers to.
  10229. *
  10230. * @type {string}
  10231. */
  10232. this.property = property;
  10233. /**
  10234. * The uniform type that should be used to represent the property value.
  10235. *
  10236. * @type {string}
  10237. */
  10238. this.uniformType = uniformType;
  10239. /**
  10240. * The object the property belongs to.
  10241. *
  10242. * @type {?Object}
  10243. * @default null
  10244. */
  10245. this.object = object;
  10246. /**
  10247. * When the linked property is an array, this parameter defines its length.
  10248. *
  10249. * @type {?number}
  10250. * @default null
  10251. */
  10252. this.count = count;
  10253. /**
  10254. * The property name might have dots so nested properties can be referred.
  10255. * The hierarchy of the names is stored inside this array.
  10256. *
  10257. * @type {Array<string>}
  10258. */
  10259. this.properties = property.split( '.' );
  10260. /**
  10261. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10262. * since the final reference might be updated from calling code.
  10263. *
  10264. * @type {?Object}
  10265. * @default null
  10266. */
  10267. this.reference = object;
  10268. /**
  10269. * The uniform node that holds the value of the reference node.
  10270. *
  10271. * @type {UniformNode}
  10272. * @default null
  10273. */
  10274. this.node = null;
  10275. /**
  10276. * The uniform group of the internal uniform.
  10277. *
  10278. * @type {UniformGroupNode}
  10279. * @default null
  10280. */
  10281. this.group = null;
  10282. /**
  10283. * An optional label of the internal uniform node.
  10284. *
  10285. * @type {?string}
  10286. * @default null
  10287. */
  10288. this.name = null;
  10289. /**
  10290. * Overwritten since reference nodes are updated per object.
  10291. *
  10292. * @type {string}
  10293. * @default 'object'
  10294. */
  10295. this.updateType = NodeUpdateType.OBJECT;
  10296. }
  10297. /**
  10298. * When the referred property is array-like, this method can be used
  10299. * to access elements via an index node.
  10300. *
  10301. * @param {IndexNode} indexNode - indexNode.
  10302. * @return {ReferenceElementNode} A reference to an element.
  10303. */
  10304. element( indexNode ) {
  10305. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10306. }
  10307. /**
  10308. * Sets the uniform group for this reference node.
  10309. *
  10310. * @param {UniformGroupNode} group - The uniform group to set.
  10311. * @return {ReferenceNode} A reference to this node.
  10312. */
  10313. setGroup( group ) {
  10314. this.group = group;
  10315. return this;
  10316. }
  10317. /**
  10318. * Sets the name for the internal uniform.
  10319. *
  10320. * @param {string} name - The label to set.
  10321. * @return {ReferenceNode} A reference to this node.
  10322. */
  10323. setName( name ) {
  10324. this.name = name;
  10325. return this;
  10326. }
  10327. /**
  10328. * Sets the label for the internal uniform.
  10329. *
  10330. * @deprecated
  10331. * @param {string} name - The label to set.
  10332. * @return {ReferenceNode} A reference to this node.
  10333. */
  10334. label( name ) {
  10335. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10336. return this.setName( name );
  10337. }
  10338. /**
  10339. * Sets the node type which automatically defines the internal
  10340. * uniform type.
  10341. *
  10342. * @param {string} uniformType - The type to set.
  10343. */
  10344. setNodeType( uniformType ) {
  10345. let node = null;
  10346. if ( this.count !== null ) {
  10347. node = buffer( null, uniformType, this.count );
  10348. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10349. node = uniformArray( null, uniformType );
  10350. } else if ( uniformType === 'texture' ) {
  10351. node = texture( null );
  10352. } else if ( uniformType === 'cubeTexture' ) {
  10353. node = cubeTexture( null );
  10354. } else {
  10355. node = uniform( null, uniformType );
  10356. }
  10357. if ( this.group !== null ) {
  10358. node.setGroup( this.group );
  10359. }
  10360. if ( this.name !== null ) node.setName( this.name );
  10361. this.node = node;
  10362. }
  10363. /**
  10364. * This method is overwritten since the node type is inferred from
  10365. * the type of the reference node.
  10366. *
  10367. * @param {NodeBuilder} builder - The current node builder.
  10368. * @return {string} The node type.
  10369. */
  10370. getNodeType( builder ) {
  10371. if ( this.node === null ) {
  10372. this.updateReference( builder );
  10373. this.updateValue();
  10374. }
  10375. return this.node.getNodeType( builder );
  10376. }
  10377. /**
  10378. * Returns the property value from the given referred object.
  10379. *
  10380. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10381. * @return {any} The value.
  10382. */
  10383. getValueFromReference( object = this.reference ) {
  10384. const { properties } = this;
  10385. let value = object[ properties[ 0 ] ];
  10386. for ( let i = 1; i < properties.length; i ++ ) {
  10387. value = value[ properties[ i ] ];
  10388. }
  10389. return value;
  10390. }
  10391. /**
  10392. * Allows to update the reference based on the given state. The state is only
  10393. * evaluated {@link ReferenceNode#object} is not set.
  10394. *
  10395. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10396. * @return {Object} The updated reference.
  10397. */
  10398. updateReference( state ) {
  10399. this.reference = this.object !== null ? this.object : state.object;
  10400. return this.reference;
  10401. }
  10402. /**
  10403. * The output of the reference node is the internal uniform node.
  10404. *
  10405. * @param {NodeBuilder} builder - The current node builder.
  10406. * @return {UniformNode} The output node.
  10407. */
  10408. setup( /* builder */ ) {
  10409. this.updateValue();
  10410. return this.node;
  10411. }
  10412. /**
  10413. * Overwritten to update the internal uniform value.
  10414. *
  10415. * @param {NodeFrame} frame - A reference to the current node frame.
  10416. */
  10417. update( /*frame*/ ) {
  10418. this.updateValue();
  10419. }
  10420. /**
  10421. * Retrieves the value from the referred object property and uses it
  10422. * to updated the internal uniform.
  10423. */
  10424. updateValue() {
  10425. if ( this.node === null ) this.setNodeType( this.uniformType );
  10426. const value = this.getValueFromReference();
  10427. if ( Array.isArray( value ) ) {
  10428. this.node.array = value;
  10429. } else {
  10430. this.node.value = value;
  10431. }
  10432. }
  10433. }
  10434. /**
  10435. * TSL function for creating a reference node.
  10436. *
  10437. * @tsl
  10438. * @function
  10439. * @param {string} name - The name of the property the node refers to.
  10440. * @param {string} type - The uniform type that should be used to represent the property value.
  10441. * @param {?Object} [object] - The object the property belongs to.
  10442. * @returns {ReferenceNode}
  10443. */
  10444. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10445. /**
  10446. * TSL function for creating a reference node. Use this function if you want need a reference
  10447. * to an array-like property that should be represented as a uniform buffer.
  10448. *
  10449. * @tsl
  10450. * @function
  10451. * @param {string} name - The name of the property the node refers to.
  10452. * @param {string} type - The uniform type that should be used to represent the property value.
  10453. * @param {number} count - The number of value inside the array-like object.
  10454. * @param {Object} object - An array-like object the property belongs to.
  10455. * @returns {ReferenceNode}
  10456. */
  10457. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10458. /**
  10459. * This node is a special type of reference node which is intended
  10460. * for linking material properties with node values.
  10461. * ```js
  10462. * const opacityNode = materialReference( 'opacity', 'float', material );
  10463. * ```
  10464. * When changing `material.opacity`, the node value of `opacityNode` will
  10465. * automatically be updated.
  10466. *
  10467. * @augments ReferenceNode
  10468. */
  10469. class MaterialReferenceNode extends ReferenceNode {
  10470. static get type() {
  10471. return 'MaterialReferenceNode';
  10472. }
  10473. /**
  10474. * Constructs a new material reference node.
  10475. *
  10476. * @param {string} property - The name of the property the node refers to.
  10477. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10478. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10479. * the node refers to the material of the current rendered object.
  10480. */
  10481. constructor( property, inputType, material = null ) {
  10482. super( property, inputType, material );
  10483. /**
  10484. * The material the property belongs to. When no material is set,
  10485. * the node refers to the material of the current rendered object.
  10486. *
  10487. * @type {?Material}
  10488. * @default null
  10489. */
  10490. this.material = material;
  10491. /**
  10492. * This flag can be used for type testing.
  10493. *
  10494. * @type {boolean}
  10495. * @readonly
  10496. * @default true
  10497. */
  10498. this.isMaterialReferenceNode = true;
  10499. }
  10500. /**
  10501. * Updates the reference based on the given state. The state is only evaluated
  10502. * {@link MaterialReferenceNode#material} is not set.
  10503. *
  10504. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10505. * @return {Object} The updated reference.
  10506. */
  10507. updateReference( state ) {
  10508. this.reference = this.material !== null ? this.material : state.material;
  10509. return this.reference;
  10510. }
  10511. }
  10512. /**
  10513. * TSL function for creating a material reference node.
  10514. *
  10515. * @tsl
  10516. * @function
  10517. * @param {string} name - The name of the property the node refers to.
  10518. * @param {string} type - The uniform type that should be used to represent the property value.
  10519. * @param {?Material} [material=null] - The material the property belongs to.
  10520. * When no material is set, the node refers to the material of the current rendered object.
  10521. * @returns {MaterialReferenceNode}
  10522. */
  10523. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10524. // Normal Mapping Without Precomputed Tangents
  10525. // http://www.thetenthplanet.de/archives/1180
  10526. const uv = uv$1();
  10527. const q0 = positionView.dFdx();
  10528. const q1 = positionView.dFdy();
  10529. const st0 = uv.dFdx();
  10530. const st1 = uv.dFdy();
  10531. const N = normalView;
  10532. const q1perp = q1.cross( N );
  10533. const q0perp = N.cross( q0 );
  10534. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10535. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10536. const det = T.dot( T ).max( B.dot( B ) );
  10537. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10538. /**
  10539. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10540. * Useful for normal mapping without precomputed tangents.
  10541. *
  10542. * Reference: http://www.thetenthplanet.de/archives/1180
  10543. *
  10544. * @tsl
  10545. * @type {Node<vec3>}
  10546. */
  10547. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10548. /**
  10549. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10550. * Complements the tangentViewFrame for constructing the tangent space basis.
  10551. *
  10552. * Reference: http://www.thetenthplanet.de/archives/1180
  10553. *
  10554. * @tsl
  10555. * @type {Node<vec3>}
  10556. */
  10557. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10558. /**
  10559. * TSL object that represents the tangent attribute of the current rendered object.
  10560. *
  10561. * @tsl
  10562. * @type {Node<vec4>}
  10563. */
  10564. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10565. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10566. builder.geometry.computeTangents();
  10567. }
  10568. return attribute( 'tangent', 'vec4' );
  10569. } )();
  10570. /**
  10571. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10572. *
  10573. * @tsl
  10574. * @type {Node<vec3>}
  10575. */
  10576. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10577. /**
  10578. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10579. *
  10580. * @tsl
  10581. * @type {Node<vec3>}
  10582. */
  10583. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10584. let node;
  10585. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10586. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10587. } else {
  10588. node = tangentViewFrame;
  10589. }
  10590. if ( material.flatShading !== true ) {
  10591. node = directionToFaceDirection( node );
  10592. }
  10593. return node;
  10594. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10595. /**
  10596. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10597. *
  10598. * @tsl
  10599. * @type {Node<vec3>}
  10600. */
  10601. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10602. /**
  10603. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10604. *
  10605. * @tsl
  10606. * @private
  10607. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10608. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10609. * @returns {Node<vec3>} The bitangent node.
  10610. */
  10611. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10612. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10613. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10614. bitangent = bitangent.toVarying( varyingName );
  10615. }
  10616. return bitangent;
  10617. } ).once( [ 'NORMAL' ] );
  10618. /**
  10619. * TSL object that represents the bitangent attribute of the current rendered object.
  10620. *
  10621. * @tsl
  10622. * @type {Node<vec3>}
  10623. */
  10624. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10625. /**
  10626. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10627. *
  10628. * @tsl
  10629. * @type {Node<vec3>}
  10630. */
  10631. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10632. /**
  10633. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10634. *
  10635. * @tsl
  10636. * @type {Node<vec3>}
  10637. */
  10638. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10639. let node;
  10640. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10641. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10642. } else {
  10643. node = bitangentViewFrame;
  10644. }
  10645. if ( material.flatShading !== true ) {
  10646. node = directionToFaceDirection( node );
  10647. }
  10648. return node;
  10649. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10650. /**
  10651. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10652. *
  10653. * @tsl
  10654. * @type {Node<vec3>}
  10655. */
  10656. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10657. /**
  10658. * TSL object that represents the TBN matrix in view space.
  10659. *
  10660. * @tsl
  10661. * @type {Node<mat3>}
  10662. */
  10663. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10664. /**
  10665. * TSL object that represents the parallax direction.
  10666. *
  10667. * @tsl
  10668. * @type {Node<mat3>}
  10669. */
  10670. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10671. /**
  10672. * TSL function for computing parallax uv coordinates.
  10673. *
  10674. * @tsl
  10675. * @function
  10676. * @param {Node<vec2>} uv - A uv node.
  10677. * @param {Node<vec2>} scale - A scale node.
  10678. * @returns {Node<vec2>} Parallax uv coordinates.
  10679. */
  10680. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10681. /**
  10682. * TSL function for computing bent normals.
  10683. *
  10684. * @tsl
  10685. * @function
  10686. * @returns {Node<vec3>} Bent normals.
  10687. */
  10688. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10689. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10690. let bentNormal = anisotropyB.cross( positionViewDirection );
  10691. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10692. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10693. return bentNormal;
  10694. } ).once() )();
  10695. /**
  10696. * This class can be used for applying normals maps to materials.
  10697. *
  10698. * ```js
  10699. * material.normalNode = normalMap( texture( normalTex ) );
  10700. * ```
  10701. *
  10702. * @augments TempNode
  10703. */
  10704. class NormalMapNode extends TempNode {
  10705. static get type() {
  10706. return 'NormalMapNode';
  10707. }
  10708. /**
  10709. * Constructs a new normal map node.
  10710. *
  10711. * @param {Node<vec3>} node - Represents the normal map data.
  10712. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10713. */
  10714. constructor( node, scaleNode = null ) {
  10715. super( 'vec3' );
  10716. /**
  10717. * Represents the normal map data.
  10718. *
  10719. * @type {Node<vec3>}
  10720. */
  10721. this.node = node;
  10722. /**
  10723. * Controls the intensity of the effect.
  10724. *
  10725. * @type {?Node<vec2>}
  10726. * @default null
  10727. */
  10728. this.scaleNode = scaleNode;
  10729. /**
  10730. * The normal map type.
  10731. *
  10732. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10733. * @default TangentSpaceNormalMap
  10734. */
  10735. this.normalMapType = TangentSpaceNormalMap;
  10736. }
  10737. setup( { material } ) {
  10738. const { normalMapType, scaleNode } = this;
  10739. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10740. if ( scaleNode !== null ) {
  10741. let scale = scaleNode;
  10742. if ( material.flatShading === true ) {
  10743. scale = directionToFaceDirection( scale );
  10744. }
  10745. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10746. }
  10747. let output = null;
  10748. if ( normalMapType === ObjectSpaceNormalMap ) {
  10749. output = transformNormalToView( normalMap );
  10750. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10751. output = TBNViewMatrix.mul( normalMap ).normalize();
  10752. } else {
  10753. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10754. output = normalView; // Fallback to default normal view
  10755. }
  10756. return output;
  10757. }
  10758. }
  10759. /**
  10760. * TSL function for creating a normal map node.
  10761. *
  10762. * @tsl
  10763. * @function
  10764. * @param {Node<vec3>} node - Represents the normal map data.
  10765. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10766. * @returns {NormalMapNode}
  10767. */
  10768. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10769. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10770. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10771. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10772. // It's used to preserve the same TextureNode instance
  10773. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10774. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10775. return vec2(
  10776. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10777. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10778. ).mul( bumpScale );
  10779. } );
  10780. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10781. const perturbNormalArb = Fn( ( inputs ) => {
  10782. const { surf_pos, surf_norm, dHdxy } = inputs;
  10783. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10784. const vSigmaX = surf_pos.dFdx().normalize();
  10785. const vSigmaY = surf_pos.dFdy().normalize();
  10786. const vN = surf_norm; // normalized
  10787. const R1 = vSigmaY.cross( vN );
  10788. const R2 = vN.cross( vSigmaX );
  10789. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10790. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10791. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10792. } );
  10793. /**
  10794. * This class can be used for applying bump maps to materials.
  10795. *
  10796. * ```js
  10797. * material.normalNode = bumpMap( texture( bumpTex ) );
  10798. * ```
  10799. *
  10800. * @augments TempNode
  10801. */
  10802. class BumpMapNode extends TempNode {
  10803. static get type() {
  10804. return 'BumpMapNode';
  10805. }
  10806. /**
  10807. * Constructs a new bump map node.
  10808. *
  10809. * @param {Node<float>} textureNode - Represents the bump map data.
  10810. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10811. */
  10812. constructor( textureNode, scaleNode = null ) {
  10813. super( 'vec3' );
  10814. /**
  10815. * Represents the bump map data.
  10816. *
  10817. * @type {Node<float>}
  10818. */
  10819. this.textureNode = textureNode;
  10820. /**
  10821. * Controls the intensity of the bump effect.
  10822. *
  10823. * @type {?Node<float>}
  10824. * @default null
  10825. */
  10826. this.scaleNode = scaleNode;
  10827. }
  10828. setup() {
  10829. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10830. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10831. return perturbNormalArb( {
  10832. surf_pos: positionView,
  10833. surf_norm: normalView,
  10834. dHdxy
  10835. } );
  10836. }
  10837. }
  10838. /**
  10839. * TSL function for creating a bump map node.
  10840. *
  10841. * @tsl
  10842. * @function
  10843. * @param {Node<float>} textureNode - Represents the bump map data.
  10844. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10845. * @returns {BumpMapNode}
  10846. */
  10847. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10848. const _propertyCache = new Map();
  10849. /**
  10850. * This class should simplify the node access to material properties.
  10851. * It internal uses reference nodes to make sure changes to material
  10852. * properties are automatically reflected to predefined TSL objects
  10853. * like e.g. `materialColor`.
  10854. *
  10855. * @augments Node
  10856. */
  10857. class MaterialNode extends Node {
  10858. static get type() {
  10859. return 'MaterialNode';
  10860. }
  10861. /**
  10862. * Constructs a new material node.
  10863. *
  10864. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10865. */
  10866. constructor( scope ) {
  10867. super();
  10868. /**
  10869. * The scope defines what material property is referred by the node.
  10870. *
  10871. * @type {string}
  10872. */
  10873. this.scope = scope;
  10874. }
  10875. /**
  10876. * Returns a cached reference node for the given property and type.
  10877. *
  10878. * @param {string} property - The name of the material property.
  10879. * @param {string} type - The uniform type of the property.
  10880. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10881. */
  10882. getCache( property, type ) {
  10883. let node = _propertyCache.get( property );
  10884. if ( node === undefined ) {
  10885. node = materialReference( property, type );
  10886. _propertyCache.set( property, node );
  10887. }
  10888. return node;
  10889. }
  10890. /**
  10891. * Returns a float-typed material reference node for the given property name.
  10892. *
  10893. * @param {string} property - The name of the material property.
  10894. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10895. */
  10896. getFloat( property ) {
  10897. return this.getCache( property, 'float' );
  10898. }
  10899. /**
  10900. * Returns a color-typed material reference node for the given property name.
  10901. *
  10902. * @param {string} property - The name of the material property.
  10903. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10904. */
  10905. getColor( property ) {
  10906. return this.getCache( property, 'color' );
  10907. }
  10908. /**
  10909. * Returns a texture-typed material reference node for the given property name.
  10910. *
  10911. * @param {string} property - The name of the material property.
  10912. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10913. */
  10914. getTexture( property ) {
  10915. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10916. }
  10917. /**
  10918. * The node setup is done depending on the selected scope. Multiple material properties
  10919. * might be grouped into a single node composition if they logically belong together.
  10920. *
  10921. * @param {NodeBuilder} builder - The current node builder.
  10922. * @return {Node} The node representing the selected scope.
  10923. */
  10924. setup( builder ) {
  10925. const material = builder.context.material;
  10926. const scope = this.scope;
  10927. let node = null;
  10928. if ( scope === MaterialNode.COLOR ) {
  10929. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10930. if ( material.map && material.map.isTexture === true ) {
  10931. node = colorNode.mul( this.getTexture( 'map' ) );
  10932. } else {
  10933. node = colorNode;
  10934. }
  10935. } else if ( scope === MaterialNode.OPACITY ) {
  10936. const opacityNode = this.getFloat( scope );
  10937. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10938. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10939. } else {
  10940. node = opacityNode;
  10941. }
  10942. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10943. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10944. node = this.getTexture( 'specular' ).r;
  10945. } else {
  10946. node = float( 1 );
  10947. }
  10948. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10949. const specularIntensityNode = this.getFloat( scope );
  10950. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10951. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10952. } else {
  10953. node = specularIntensityNode;
  10954. }
  10955. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10956. const specularColorNode = this.getColor( scope );
  10957. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10958. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10959. } else {
  10960. node = specularColorNode;
  10961. }
  10962. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10963. const roughnessNode = this.getFloat( scope );
  10964. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10965. node = roughnessNode.mul( this.getTexture( scope ).g );
  10966. } else {
  10967. node = roughnessNode;
  10968. }
  10969. } else if ( scope === MaterialNode.METALNESS ) {
  10970. const metalnessNode = this.getFloat( scope );
  10971. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10972. node = metalnessNode.mul( this.getTexture( scope ).b );
  10973. } else {
  10974. node = metalnessNode;
  10975. }
  10976. } else if ( scope === MaterialNode.EMISSIVE ) {
  10977. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10978. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10979. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10980. node = emissiveNode.mul( this.getTexture( scope ) );
  10981. } else {
  10982. node = emissiveNode;
  10983. }
  10984. } else if ( scope === MaterialNode.NORMAL ) {
  10985. if ( material.normalMap ) {
  10986. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10987. node.normalMapType = material.normalMapType;
  10988. } else if ( material.bumpMap ) {
  10989. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10990. } else {
  10991. node = normalView;
  10992. }
  10993. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10994. const clearcoatNode = this.getFloat( scope );
  10995. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10996. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10997. } else {
  10998. node = clearcoatNode;
  10999. }
  11000. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11001. const clearcoatRoughnessNode = this.getFloat( scope );
  11002. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11003. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11004. } else {
  11005. node = clearcoatRoughnessNode;
  11006. }
  11007. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11008. if ( material.clearcoatNormalMap ) {
  11009. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11010. } else {
  11011. node = normalView;
  11012. }
  11013. } else if ( scope === MaterialNode.SHEEN ) {
  11014. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11015. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11016. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11017. } else {
  11018. node = sheenNode;
  11019. }
  11020. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11021. const sheenRoughnessNode = this.getFloat( scope );
  11022. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11023. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11024. } else {
  11025. node = sheenRoughnessNode;
  11026. }
  11027. node = node.clamp( 0.07, 1.0 );
  11028. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11029. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11030. const anisotropyPolar = this.getTexture( scope );
  11031. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11032. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11033. } else {
  11034. node = materialAnisotropyVector;
  11035. }
  11036. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11037. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11038. if ( material.iridescenceThicknessMap ) {
  11039. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11040. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11041. } else {
  11042. node = iridescenceThicknessMaximum;
  11043. }
  11044. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11045. const transmissionNode = this.getFloat( scope );
  11046. if ( material.transmissionMap ) {
  11047. node = transmissionNode.mul( this.getTexture( scope ).r );
  11048. } else {
  11049. node = transmissionNode;
  11050. }
  11051. } else if ( scope === MaterialNode.THICKNESS ) {
  11052. const thicknessNode = this.getFloat( scope );
  11053. if ( material.thicknessMap ) {
  11054. node = thicknessNode.mul( this.getTexture( scope ).g );
  11055. } else {
  11056. node = thicknessNode;
  11057. }
  11058. } else if ( scope === MaterialNode.IOR ) {
  11059. node = this.getFloat( scope );
  11060. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11061. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11062. } else if ( scope === MaterialNode.AO ) {
  11063. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11064. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11065. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11066. } else {
  11067. const outputType = this.getNodeType( builder );
  11068. node = this.getCache( scope, outputType );
  11069. }
  11070. return node;
  11071. }
  11072. }
  11073. MaterialNode.ALPHA_TEST = 'alphaTest';
  11074. MaterialNode.COLOR = 'color';
  11075. MaterialNode.OPACITY = 'opacity';
  11076. MaterialNode.SHININESS = 'shininess';
  11077. MaterialNode.SPECULAR = 'specular';
  11078. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11079. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11080. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11081. MaterialNode.REFLECTIVITY = 'reflectivity';
  11082. MaterialNode.ROUGHNESS = 'roughness';
  11083. MaterialNode.METALNESS = 'metalness';
  11084. MaterialNode.NORMAL = 'normal';
  11085. MaterialNode.CLEARCOAT = 'clearcoat';
  11086. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11087. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11088. MaterialNode.EMISSIVE = 'emissive';
  11089. MaterialNode.ROTATION = 'rotation';
  11090. MaterialNode.SHEEN = 'sheen';
  11091. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11092. MaterialNode.ANISOTROPY = 'anisotropy';
  11093. MaterialNode.IRIDESCENCE = 'iridescence';
  11094. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11095. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11096. MaterialNode.IOR = 'ior';
  11097. MaterialNode.TRANSMISSION = 'transmission';
  11098. MaterialNode.THICKNESS = 'thickness';
  11099. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11100. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11101. MaterialNode.LINE_SCALE = 'scale';
  11102. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11103. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11104. MaterialNode.LINE_WIDTH = 'linewidth';
  11105. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11106. MaterialNode.POINT_SIZE = 'size';
  11107. MaterialNode.DISPERSION = 'dispersion';
  11108. MaterialNode.LIGHT_MAP = 'light';
  11109. MaterialNode.AO = 'ao';
  11110. /**
  11111. * TSL object that represents alpha test of the current material.
  11112. *
  11113. * @tsl
  11114. * @type {Node<float>}
  11115. */
  11116. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11117. /**
  11118. * TSL object that represents the diffuse color of the current material.
  11119. * The value is composed via `color` * `map`.
  11120. *
  11121. * @tsl
  11122. * @type {Node<vec3>}
  11123. */
  11124. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11125. /**
  11126. * TSL object that represents the shininess of the current material.
  11127. *
  11128. * @tsl
  11129. * @type {Node<float>}
  11130. */
  11131. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11132. /**
  11133. * TSL object that represents the emissive color of the current material.
  11134. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11135. *
  11136. * @tsl
  11137. * @type {Node<vec3>}
  11138. */
  11139. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11140. /**
  11141. * TSL object that represents the opacity of the current material.
  11142. * The value is composed via `opacity` * `alphaMap`.
  11143. *
  11144. * @tsl
  11145. * @type {Node<float>}
  11146. */
  11147. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11148. /**
  11149. * TSL object that represents the specular of the current material.
  11150. *
  11151. * @tsl
  11152. * @type {Node<vec3>}
  11153. */
  11154. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11155. /**
  11156. * TSL object that represents the specular intensity of the current material.
  11157. * The value is composed via `specularIntensity` * `specularMap.a`.
  11158. *
  11159. * @tsl
  11160. * @type {Node<float>}
  11161. */
  11162. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11163. /**
  11164. * TSL object that represents the specular color of the current material.
  11165. * The value is composed via `specularColor` * `specularMap.rgb`.
  11166. *
  11167. * @tsl
  11168. * @type {Node<vec3>}
  11169. */
  11170. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11171. /**
  11172. * TSL object that represents the specular strength of the current material.
  11173. * The value is composed via `specularMap.r`.
  11174. *
  11175. * @tsl
  11176. * @type {Node<float>}
  11177. */
  11178. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11179. /**
  11180. * TSL object that represents the reflectivity of the current material.
  11181. *
  11182. * @tsl
  11183. * @type {Node<float>}
  11184. */
  11185. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11186. /**
  11187. * TSL object that represents the roughness of the current material.
  11188. * The value is composed via `roughness` * `roughnessMap.g`.
  11189. *
  11190. * @tsl
  11191. * @type {Node<float>}
  11192. */
  11193. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11194. /**
  11195. * TSL object that represents the metalness of the current material.
  11196. * The value is composed via `metalness` * `metalnessMap.b`.
  11197. *
  11198. * @tsl
  11199. * @type {Node<float>}
  11200. */
  11201. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11202. /**
  11203. * TSL object that represents the normal of the current material.
  11204. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11205. *
  11206. * @tsl
  11207. * @type {Node<vec3>}
  11208. */
  11209. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11210. /**
  11211. * TSL object that represents the clearcoat of the current material.
  11212. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11213. *
  11214. * @tsl
  11215. * @type {Node<float>}
  11216. */
  11217. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11218. /**
  11219. * TSL object that represents the clearcoat roughness of the current material.
  11220. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11221. *
  11222. * @tsl
  11223. * @type {Node<float>}
  11224. */
  11225. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11226. /**
  11227. * TSL object that represents the clearcoat normal of the current material.
  11228. * The value will be either `clearcoatNormalMap` or `normalView`.
  11229. *
  11230. * @tsl
  11231. * @type {Node<vec3>}
  11232. */
  11233. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11234. /**
  11235. * TSL object that represents the rotation of the current sprite material.
  11236. *
  11237. * @tsl
  11238. * @type {Node<float>}
  11239. */
  11240. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11241. /**
  11242. * TSL object that represents the sheen color of the current material.
  11243. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11244. *
  11245. * @tsl
  11246. * @type {Node<vec3>}
  11247. */
  11248. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11249. /**
  11250. * TSL object that represents the sheen roughness of the current material.
  11251. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11252. *
  11253. * @tsl
  11254. * @type {Node<float>}
  11255. */
  11256. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11257. /**
  11258. * TSL object that represents the anisotropy of the current material.
  11259. *
  11260. * @tsl
  11261. * @type {Node<vec2>}
  11262. */
  11263. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11264. /**
  11265. * TSL object that represents the iridescence of the current material.
  11266. *
  11267. * @tsl
  11268. * @type {Node<float>}
  11269. */
  11270. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11271. /**
  11272. * TSL object that represents the iridescence IOR of the current material.
  11273. *
  11274. * @tsl
  11275. * @type {Node<float>}
  11276. */
  11277. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11278. /**
  11279. * TSL object that represents the iridescence thickness of the current material.
  11280. *
  11281. * @tsl
  11282. * @type {Node<float>}
  11283. */
  11284. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11285. /**
  11286. * TSL object that represents the transmission of the current material.
  11287. * The value is composed via `transmission` * `transmissionMap.r`.
  11288. *
  11289. * @tsl
  11290. * @type {Node<float>}
  11291. */
  11292. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11293. /**
  11294. * TSL object that represents the thickness of the current material.
  11295. * The value is composed via `thickness` * `thicknessMap.g`.
  11296. *
  11297. * @tsl
  11298. * @type {Node<float>}
  11299. */
  11300. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11301. /**
  11302. * TSL object that represents the IOR of the current material.
  11303. *
  11304. * @tsl
  11305. * @type {Node<float>}
  11306. */
  11307. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11308. /**
  11309. * TSL object that represents the attenuation distance of the current material.
  11310. *
  11311. * @tsl
  11312. * @type {Node<float>}
  11313. */
  11314. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11315. /**
  11316. * TSL object that represents the attenuation color of the current material.
  11317. *
  11318. * @tsl
  11319. * @type {Node<vec3>}
  11320. */
  11321. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11322. /**
  11323. * TSL object that represents the scale of the current dashed line material.
  11324. *
  11325. * @tsl
  11326. * @type {Node<float>}
  11327. */
  11328. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11329. /**
  11330. * TSL object that represents the dash size of the current dashed line material.
  11331. *
  11332. * @tsl
  11333. * @type {Node<float>}
  11334. */
  11335. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11336. /**
  11337. * TSL object that represents the gap size of the current dashed line material.
  11338. *
  11339. * @tsl
  11340. * @type {Node<float>}
  11341. */
  11342. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11343. /**
  11344. * TSL object that represents the line width of the current line material.
  11345. *
  11346. * @tsl
  11347. * @type {Node<float>}
  11348. */
  11349. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11350. /**
  11351. * TSL object that represents the dash offset of the current line material.
  11352. *
  11353. * @tsl
  11354. * @type {Node<float>}
  11355. */
  11356. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11357. /**
  11358. * TSL object that represents the point size of the current points material.
  11359. *
  11360. * @tsl
  11361. * @type {Node<float>}
  11362. */
  11363. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11364. /**
  11365. * TSL object that represents the dispersion of the current material.
  11366. *
  11367. * @tsl
  11368. * @type {Node<float>}
  11369. */
  11370. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11371. /**
  11372. * TSL object that represents the light map of the current material.
  11373. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11374. *
  11375. * @tsl
  11376. * @type {Node<vec3>}
  11377. */
  11378. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11379. /**
  11380. * TSL object that represents the ambient occlusion map of the current material.
  11381. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11382. *
  11383. * @tsl
  11384. * @type {Node<float>}
  11385. */
  11386. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11387. /**
  11388. * TSL object that represents the anisotropy vector of the current material.
  11389. *
  11390. * @tsl
  11391. * @type {Node<vec2>}
  11392. */
  11393. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11394. return frame.material;
  11395. } ).onRenderUpdate( function ( { material } ) {
  11396. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11397. } );
  11398. /**
  11399. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11400. *
  11401. * @tsl
  11402. * @type {VaryingNode<vec4>}
  11403. */
  11404. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11405. return builder.context.setupModelViewProjection();
  11406. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11407. /**
  11408. * This class represents shader indices of different types. The following predefined node
  11409. * objects cover frequent use cases:
  11410. *
  11411. * - `vertexIndex`: The index of a vertex within a mesh.
  11412. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11413. * - `drawIndex`: The index of a draw call.
  11414. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11415. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11416. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  11417. *
  11418. * @augments Node
  11419. */
  11420. class IndexNode extends Node {
  11421. static get type() {
  11422. return 'IndexNode';
  11423. }
  11424. /**
  11425. * Constructs a new index node.
  11426. *
  11427. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11428. */
  11429. constructor( scope ) {
  11430. super( 'uint' );
  11431. /**
  11432. * The scope of the index node.
  11433. *
  11434. * @type {string}
  11435. */
  11436. this.scope = scope;
  11437. /**
  11438. * This flag can be used for type testing.
  11439. *
  11440. * @type {boolean}
  11441. * @readonly
  11442. * @default true
  11443. */
  11444. this.isIndexNode = true;
  11445. }
  11446. generate( builder ) {
  11447. const nodeType = this.getNodeType( builder );
  11448. const scope = this.scope;
  11449. let propertyName;
  11450. if ( scope === IndexNode.VERTEX ) {
  11451. propertyName = builder.getVertexIndex();
  11452. } else if ( scope === IndexNode.INSTANCE ) {
  11453. propertyName = builder.getInstanceIndex();
  11454. } else if ( scope === IndexNode.DRAW ) {
  11455. propertyName = builder.getDrawIndex();
  11456. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11457. propertyName = builder.getInvocationLocalIndex();
  11458. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11459. propertyName = builder.getInvocationSubgroupIndex();
  11460. } else if ( scope === IndexNode.SUBGROUP ) {
  11461. propertyName = builder.getSubgroupIndex();
  11462. } else {
  11463. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11464. }
  11465. let output;
  11466. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11467. output = propertyName;
  11468. } else {
  11469. const nodeVarying = varying( this );
  11470. output = nodeVarying.build( builder, nodeType );
  11471. }
  11472. return output;
  11473. }
  11474. }
  11475. IndexNode.VERTEX = 'vertex';
  11476. IndexNode.INSTANCE = 'instance';
  11477. IndexNode.SUBGROUP = 'subgroup';
  11478. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11479. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11480. IndexNode.DRAW = 'draw';
  11481. /**
  11482. * TSL object that represents the index of a vertex within a mesh.
  11483. *
  11484. * @tsl
  11485. * @type {IndexNode}
  11486. */
  11487. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11488. /**
  11489. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11490. *
  11491. * @tsl
  11492. * @type {IndexNode}
  11493. */
  11494. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11495. /**
  11496. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11497. *
  11498. * @tsl
  11499. * @type {IndexNode}
  11500. */
  11501. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11502. /**
  11503. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11504. *
  11505. * @tsl
  11506. * @type {IndexNode}
  11507. */
  11508. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11509. /**
  11510. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11511. *
  11512. * @tsl
  11513. * @type {IndexNode}
  11514. */
  11515. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11516. /**
  11517. * TSL object that represents the index of a draw call.
  11518. *
  11519. * @tsl
  11520. * @type {IndexNode}
  11521. */
  11522. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11523. /**
  11524. * This node implements the vertex shader logic which is required
  11525. * when rendering 3D objects via instancing. The code makes sure
  11526. * vertex positions, normals and colors can be modified via instanced
  11527. * data.
  11528. *
  11529. * @augments Node
  11530. */
  11531. class InstanceNode extends Node {
  11532. static get type() {
  11533. return 'InstanceNode';
  11534. }
  11535. /**
  11536. * Constructs a new instance node.
  11537. *
  11538. * @param {number} count - The number of instances.
  11539. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11540. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11541. */
  11542. constructor( count, instanceMatrix, instanceColor = null ) {
  11543. super( 'void' );
  11544. /**
  11545. * The number of instances.
  11546. *
  11547. * @type {number}
  11548. */
  11549. this.count = count;
  11550. /**
  11551. * Instanced buffer attribute representing the transformation of instances.
  11552. *
  11553. * @type {InstancedBufferAttribute}
  11554. */
  11555. this.instanceMatrix = instanceMatrix;
  11556. /**
  11557. * Instanced buffer attribute representing the color of instances.
  11558. *
  11559. * @type {InstancedBufferAttribute}
  11560. */
  11561. this.instanceColor = instanceColor;
  11562. /**
  11563. * The node that represents the instance matrix data.
  11564. *
  11565. * @type {?Node}
  11566. */
  11567. this.instanceMatrixNode = null;
  11568. /**
  11569. * The node that represents the instance color data.
  11570. *
  11571. * @type {?Node}
  11572. * @default null
  11573. */
  11574. this.instanceColorNode = null;
  11575. /**
  11576. * The update type is set to `frame` since an update
  11577. * of instanced buffer data must be checked per frame.
  11578. *
  11579. * @type {string}
  11580. * @default 'frame'
  11581. */
  11582. this.updateType = NodeUpdateType.FRAME;
  11583. /**
  11584. * A reference to a buffer that is used by `instanceMatrixNode`.
  11585. *
  11586. * @type {?InstancedInterleavedBuffer}
  11587. */
  11588. this.buffer = null;
  11589. /**
  11590. * A reference to a buffer that is used by `instanceColorNode`.
  11591. *
  11592. * @type {?InstancedBufferAttribute}
  11593. */
  11594. this.bufferColor = null;
  11595. }
  11596. /**
  11597. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11598. * to predefined node variables for accumulation. That follows the same patterns
  11599. * like with morph and skinning nodes.
  11600. *
  11601. * @param {NodeBuilder} builder - The current node builder.
  11602. */
  11603. setup( builder ) {
  11604. const { instanceMatrix, instanceColor } = this;
  11605. const { count } = instanceMatrix;
  11606. let { instanceMatrixNode, instanceColorNode } = this;
  11607. if ( instanceMatrixNode === null ) {
  11608. // 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.
  11609. if ( count <= 1000 ) {
  11610. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11611. } else {
  11612. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11613. this.buffer = buffer;
  11614. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11615. const instanceBuffers = [
  11616. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11617. bufferFn( buffer, 'vec4', 16, 0 ),
  11618. bufferFn( buffer, 'vec4', 16, 4 ),
  11619. bufferFn( buffer, 'vec4', 16, 8 ),
  11620. bufferFn( buffer, 'vec4', 16, 12 )
  11621. ];
  11622. instanceMatrixNode = mat4( ...instanceBuffers );
  11623. }
  11624. this.instanceMatrixNode = instanceMatrixNode;
  11625. }
  11626. if ( instanceColor && instanceColorNode === null ) {
  11627. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11628. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11629. this.bufferColor = buffer;
  11630. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11631. this.instanceColorNode = instanceColorNode;
  11632. }
  11633. // POSITION
  11634. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11635. positionLocal.assign( instancePosition );
  11636. // NORMAL
  11637. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11638. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11639. // ASSIGNS
  11640. normalLocal.assign( instanceNormal );
  11641. }
  11642. // COLOR
  11643. if ( this.instanceColorNode !== null ) {
  11644. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11645. }
  11646. }
  11647. /**
  11648. * Checks if the internal buffers required an update.
  11649. *
  11650. * @param {NodeFrame} frame - The current node frame.
  11651. */
  11652. update( /*frame*/ ) {
  11653. if ( this.buffer !== null ) {
  11654. // keep update ranges in sync
  11655. this.buffer.clearUpdateRanges();
  11656. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11657. // update version if necessary
  11658. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11659. this.buffer.version = this.instanceMatrix.version;
  11660. }
  11661. }
  11662. if ( this.instanceColor && this.bufferColor !== null ) {
  11663. this.bufferColor.clearUpdateRanges();
  11664. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11665. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11666. this.bufferColor.version = this.instanceColor.version;
  11667. }
  11668. }
  11669. }
  11670. }
  11671. /**
  11672. * TSL function for creating an instance node.
  11673. *
  11674. * @tsl
  11675. * @function
  11676. * @param {number} count - The number of instances.
  11677. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11678. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11679. * @returns {InstanceNode}
  11680. */
  11681. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11682. /**
  11683. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11684. * It allows an easier setup of the instance node.
  11685. *
  11686. * @augments InstanceNode
  11687. */
  11688. class InstancedMeshNode extends InstanceNode {
  11689. static get type() {
  11690. return 'InstancedMeshNode';
  11691. }
  11692. /**
  11693. * Constructs a new instanced mesh node.
  11694. *
  11695. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11696. */
  11697. constructor( instancedMesh ) {
  11698. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11699. super( count, instanceMatrix, instanceColor );
  11700. /**
  11701. * A reference to the instanced mesh.
  11702. *
  11703. * @type {InstancedMesh}
  11704. */
  11705. this.instancedMesh = instancedMesh;
  11706. }
  11707. }
  11708. /**
  11709. * TSL function for creating an instanced mesh node.
  11710. *
  11711. * @tsl
  11712. * @function
  11713. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11714. * @returns {InstancedMeshNode}
  11715. */
  11716. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11717. /**
  11718. * This node implements the vertex shader logic which is required
  11719. * when rendering 3D objects via batching. `BatchNode` must be used
  11720. * with instances of {@link BatchedMesh}.
  11721. *
  11722. * @augments Node
  11723. */
  11724. class BatchNode extends Node {
  11725. static get type() {
  11726. return 'BatchNode';
  11727. }
  11728. /**
  11729. * Constructs a new batch node.
  11730. *
  11731. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11732. */
  11733. constructor( batchMesh ) {
  11734. super( 'void' );
  11735. /**
  11736. * A reference to batched mesh.
  11737. *
  11738. * @type {BatchedMesh}
  11739. */
  11740. this.batchMesh = batchMesh;
  11741. /**
  11742. * The batching index node.
  11743. *
  11744. * @type {?IndexNode}
  11745. * @default null
  11746. */
  11747. this.batchingIdNode = null;
  11748. }
  11749. /**
  11750. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11751. * to predefined node variables for accumulation. That follows the same patterns
  11752. * like with morph and skinning nodes.
  11753. *
  11754. * @param {NodeBuilder} builder - The current node builder.
  11755. */
  11756. setup( builder ) {
  11757. if ( this.batchingIdNode === null ) {
  11758. if ( builder.getDrawIndex() === null ) {
  11759. this.batchingIdNode = instanceIndex;
  11760. } else {
  11761. this.batchingIdNode = drawIndex;
  11762. }
  11763. }
  11764. const getIndirectIndex = Fn( ( [ id ] ) => {
  11765. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11766. const x = int( id ).mod( size );
  11767. const y = int( id ).div( size );
  11768. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11769. } ).setLayout( {
  11770. name: 'getIndirectIndex',
  11771. type: 'uint',
  11772. inputs: [
  11773. { name: 'id', type: 'int' }
  11774. ]
  11775. } );
  11776. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11777. const matricesTexture = this.batchMesh._matricesTexture;
  11778. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11779. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11780. const x = j.mod( size );
  11781. const y = j.div( size );
  11782. const batchingMatrix = mat4(
  11783. textureLoad( matricesTexture, ivec2( x, y ) ),
  11784. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11785. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11786. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11787. );
  11788. const colorsTexture = this.batchMesh._colorsTexture;
  11789. if ( colorsTexture !== null ) {
  11790. const getBatchingColor = Fn( ( [ id ] ) => {
  11791. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11792. const j = id;
  11793. const x = j.mod( size );
  11794. const y = j.div( size );
  11795. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11796. } ).setLayout( {
  11797. name: 'getBatchingColor',
  11798. type: 'vec3',
  11799. inputs: [
  11800. { name: 'id', type: 'int' }
  11801. ]
  11802. } );
  11803. const color = getBatchingColor( indirectId );
  11804. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11805. }
  11806. const bm = mat3( batchingMatrix );
  11807. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11808. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11809. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11810. normalLocal.assign( batchingNormal );
  11811. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11812. tangentLocal.mulAssign( bm );
  11813. }
  11814. }
  11815. }
  11816. /**
  11817. * TSL function for creating a batch node.
  11818. *
  11819. * @tsl
  11820. * @function
  11821. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11822. * @returns {BatchNode}
  11823. */
  11824. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11825. /**
  11826. * This class enables element access on instances of {@link StorageBufferNode}.
  11827. * In most cases, it is indirectly used when accessing elements with the
  11828. * {@link StorageBufferNode#element} method.
  11829. *
  11830. * ```js
  11831. * const position = positionStorage.element( instanceIndex );
  11832. * ```
  11833. *
  11834. * @augments ArrayElementNode
  11835. */
  11836. class StorageArrayElementNode extends ArrayElementNode {
  11837. static get type() {
  11838. return 'StorageArrayElementNode';
  11839. }
  11840. /**
  11841. * Constructs storage buffer element node.
  11842. *
  11843. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11844. * @param {Node} indexNode - The index node that defines the element access.
  11845. */
  11846. constructor( storageBufferNode, indexNode ) {
  11847. super( storageBufferNode, indexNode );
  11848. /**
  11849. * This flag can be used for type testing.
  11850. *
  11851. * @type {boolean}
  11852. * @readonly
  11853. * @default true
  11854. */
  11855. this.isStorageArrayElementNode = true;
  11856. }
  11857. /**
  11858. * The storage buffer node.
  11859. *
  11860. * @param {Node} value
  11861. * @type {StorageBufferNode}
  11862. */
  11863. set storageBufferNode( value ) {
  11864. this.node = value;
  11865. }
  11866. get storageBufferNode() {
  11867. return this.node;
  11868. }
  11869. getMemberType( builder, name ) {
  11870. const structTypeNode = this.storageBufferNode.structTypeNode;
  11871. if ( structTypeNode ) {
  11872. return structTypeNode.getMemberType( builder, name );
  11873. }
  11874. return 'void';
  11875. }
  11876. setup( builder ) {
  11877. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11878. if ( this.node.isPBO === true ) {
  11879. builder.setupPBO( this.node );
  11880. }
  11881. }
  11882. return super.setup( builder );
  11883. }
  11884. generate( builder, output ) {
  11885. let snippet;
  11886. const isAssignContext = builder.context.assign;
  11887. //
  11888. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11889. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11890. snippet = builder.generatePBO( this );
  11891. } else {
  11892. snippet = this.node.build( builder );
  11893. }
  11894. } else {
  11895. snippet = super.generate( builder );
  11896. }
  11897. if ( isAssignContext !== true ) {
  11898. const type = this.getNodeType( builder );
  11899. snippet = builder.format( snippet, type, output );
  11900. }
  11901. return snippet;
  11902. }
  11903. }
  11904. /**
  11905. * TSL function for creating a storage element node.
  11906. *
  11907. * @tsl
  11908. * @function
  11909. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11910. * @param {Node} indexNode - The index node that defines the element access.
  11911. * @returns {StorageArrayElementNode}
  11912. */
  11913. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11914. /**
  11915. * This node is used in context of compute shaders and allows to define a
  11916. * storage buffer for data. A typical workflow is to create instances of
  11917. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11918. * setup up a compute shader that writes into the buffers and then convert
  11919. * the storage buffers to attribute nodes for rendering.
  11920. *
  11921. * ```js
  11922. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11923. *
  11924. * const computeInit = Fn( () => { // the compute shader
  11925. *
  11926. * const position = positionBuffer.element( instanceIndex );
  11927. *
  11928. * // compute position data
  11929. *
  11930. * position.x = 1;
  11931. * position.y = 1;
  11932. * position.z = 1;
  11933. *
  11934. * } )().compute( particleCount );
  11935. *
  11936. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11937. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11938. *
  11939. * renderer.computeAsync( computeInit );
  11940. *
  11941. * ```
  11942. *
  11943. * @augments BufferNode
  11944. */
  11945. class StorageBufferNode extends BufferNode {
  11946. static get type() {
  11947. return 'StorageBufferNode';
  11948. }
  11949. /**
  11950. * Constructs a new storage buffer node.
  11951. *
  11952. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11953. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11954. * @param {number} [bufferCount=0] - The buffer count.
  11955. */
  11956. constructor( value, bufferType = null, bufferCount = 0 ) {
  11957. let nodeType, structTypeNode = null;
  11958. if ( bufferType && bufferType.isStruct ) {
  11959. nodeType = 'struct';
  11960. structTypeNode = bufferType.layout;
  11961. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11962. bufferCount = value.count;
  11963. }
  11964. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11965. nodeType = getTypeFromLength( value.itemSize );
  11966. bufferCount = value.count;
  11967. } else {
  11968. nodeType = bufferType;
  11969. }
  11970. super( value, nodeType, bufferCount );
  11971. /**
  11972. * This flag can be used for type testing.
  11973. *
  11974. * @type {boolean}
  11975. * @readonly
  11976. * @default true
  11977. */
  11978. this.isStorageBufferNode = true;
  11979. /**
  11980. * The buffer struct type.
  11981. *
  11982. * @type {?StructTypeNode}
  11983. * @default null
  11984. */
  11985. this.structTypeNode = structTypeNode;
  11986. /**
  11987. * The access type of the texture node.
  11988. *
  11989. * @type {string}
  11990. * @default 'readWrite'
  11991. */
  11992. this.access = NodeAccess.READ_WRITE;
  11993. /**
  11994. * Whether the node is atomic or not.
  11995. *
  11996. * @type {boolean}
  11997. * @default false
  11998. */
  11999. this.isAtomic = false;
  12000. /**
  12001. * Whether the node represents a PBO or not.
  12002. * Only relevant for WebGL.
  12003. *
  12004. * @type {boolean}
  12005. * @default false
  12006. */
  12007. this.isPBO = false;
  12008. /**
  12009. * A reference to the internal buffer attribute node.
  12010. *
  12011. * @type {?BufferAttributeNode}
  12012. * @default null
  12013. */
  12014. this._attribute = null;
  12015. /**
  12016. * A reference to the internal varying node.
  12017. *
  12018. * @type {?VaryingNode}
  12019. * @default null
  12020. */
  12021. this._varying = null;
  12022. /**
  12023. * `StorageBufferNode` sets this property to `true` by default.
  12024. *
  12025. * @type {boolean}
  12026. * @default true
  12027. */
  12028. this.global = true;
  12029. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12030. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12031. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12032. else value.isStorageBufferAttribute = true;
  12033. }
  12034. }
  12035. /**
  12036. * This method is overwritten since the buffer data might be shared
  12037. * and thus the hash should be shared as well.
  12038. *
  12039. * @param {NodeBuilder} builder - The current node builder.
  12040. * @return {string} The hash.
  12041. */
  12042. getHash( builder ) {
  12043. if ( this.bufferCount === 0 ) {
  12044. let bufferData = builder.globalCache.getData( this.value );
  12045. if ( bufferData === undefined ) {
  12046. bufferData = {
  12047. node: this
  12048. };
  12049. builder.globalCache.setData( this.value, bufferData );
  12050. }
  12051. return bufferData.node.uuid;
  12052. }
  12053. return this.uuid;
  12054. }
  12055. /**
  12056. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12057. *
  12058. * @param {NodeBuilder} builder - The current node builder.
  12059. * @return {string} The input type.
  12060. */
  12061. getInputType( /*builder*/ ) {
  12062. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12063. }
  12064. /**
  12065. * Enables element access with the given index node.
  12066. *
  12067. * @param {IndexNode} indexNode - The index node.
  12068. * @return {StorageArrayElementNode} A node representing the element access.
  12069. */
  12070. element( indexNode ) {
  12071. return storageElement( this, indexNode );
  12072. }
  12073. /**
  12074. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12075. *
  12076. * @param {boolean} value - The value so set.
  12077. * @return {StorageBufferNode} A reference to this node.
  12078. */
  12079. setPBO( value ) {
  12080. this.isPBO = value;
  12081. return this;
  12082. }
  12083. /**
  12084. * Returns the `isPBO` value.
  12085. *
  12086. * @return {boolean} Whether the node represents a PBO or not.
  12087. */
  12088. getPBO() {
  12089. return this.isPBO;
  12090. }
  12091. /**
  12092. * Defines the node access.
  12093. *
  12094. * @param {string} value - The node access.
  12095. * @return {StorageBufferNode} A reference to this node.
  12096. */
  12097. setAccess( value ) {
  12098. this.access = value;
  12099. return this;
  12100. }
  12101. /**
  12102. * Convenience method for configuring a read-only node access.
  12103. *
  12104. * @return {StorageBufferNode} A reference to this node.
  12105. */
  12106. toReadOnly() {
  12107. return this.setAccess( NodeAccess.READ_ONLY );
  12108. }
  12109. /**
  12110. * Defines whether the node is atomic or not.
  12111. *
  12112. * @param {boolean} value - The atomic flag.
  12113. * @return {StorageBufferNode} A reference to this node.
  12114. */
  12115. setAtomic( value ) {
  12116. this.isAtomic = value;
  12117. return this;
  12118. }
  12119. /**
  12120. * Convenience method for making this node atomic.
  12121. *
  12122. * @return {StorageBufferNode} A reference to this node.
  12123. */
  12124. toAtomic() {
  12125. return this.setAtomic( true );
  12126. }
  12127. /**
  12128. * Returns attribute data for this storage buffer node.
  12129. *
  12130. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12131. */
  12132. getAttributeData() {
  12133. if ( this._attribute === null ) {
  12134. this._attribute = bufferAttribute( this.value );
  12135. this._varying = varying( this._attribute );
  12136. }
  12137. return {
  12138. attribute: this._attribute,
  12139. varying: this._varying
  12140. };
  12141. }
  12142. /**
  12143. * This method is overwritten since the node type from the availability of storage buffers
  12144. * and the attribute data.
  12145. *
  12146. * @param {NodeBuilder} builder - The current node builder.
  12147. * @return {string} The node type.
  12148. */
  12149. getNodeType( builder ) {
  12150. if ( this.structTypeNode !== null ) {
  12151. return this.structTypeNode.getNodeType( builder );
  12152. }
  12153. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12154. return super.getNodeType( builder );
  12155. }
  12156. const { attribute } = this.getAttributeData();
  12157. return attribute.getNodeType( builder );
  12158. }
  12159. /**
  12160. * Returns the type of a member of the struct.
  12161. *
  12162. * @param {NodeBuilder} builder - The current node builder.
  12163. * @param {string} name - The name of the member.
  12164. * @return {string} The type of the member.
  12165. */
  12166. getMemberType( builder, name ) {
  12167. if ( this.structTypeNode !== null ) {
  12168. return this.structTypeNode.getMemberType( builder, name );
  12169. }
  12170. return 'void';
  12171. }
  12172. /**
  12173. * Generates the code snippet of the storage buffer node.
  12174. *
  12175. * @param {NodeBuilder} builder - The current node builder.
  12176. * @return {string} The generated code snippet.
  12177. */
  12178. generate( builder ) {
  12179. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12180. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12181. return super.generate( builder );
  12182. }
  12183. const { attribute, varying } = this.getAttributeData();
  12184. const output = varying.build( builder );
  12185. builder.registerTransform( output, attribute );
  12186. return output;
  12187. }
  12188. }
  12189. /**
  12190. * TSL function for creating a storage buffer node.
  12191. *
  12192. * @tsl
  12193. * @function
  12194. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12195. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12196. * @param {number} [count=0] - The buffer count.
  12197. * @returns {StorageBufferNode}
  12198. */
  12199. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12200. /**
  12201. * @tsl
  12202. * @function
  12203. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12204. *
  12205. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12206. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12207. * @param {number} count - The buffer count.
  12208. * @returns {StorageBufferNode}
  12209. */
  12210. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12211. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12212. return storage( value, type, count ).setPBO( true );
  12213. };
  12214. const _frameId = new WeakMap();
  12215. /**
  12216. * This node implements the vertex transformation shader logic which is required
  12217. * for skinning/skeletal animation.
  12218. *
  12219. * @augments Node
  12220. */
  12221. class SkinningNode extends Node {
  12222. static get type() {
  12223. return 'SkinningNode';
  12224. }
  12225. /**
  12226. * Constructs a new skinning node.
  12227. *
  12228. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12229. */
  12230. constructor( skinnedMesh ) {
  12231. super( 'void' );
  12232. /**
  12233. * The skinned mesh.
  12234. *
  12235. * @type {SkinnedMesh}
  12236. */
  12237. this.skinnedMesh = skinnedMesh;
  12238. /**
  12239. * The update type overwritten since skinning nodes are updated per object.
  12240. *
  12241. * @type {string}
  12242. */
  12243. this.updateType = NodeUpdateType.OBJECT;
  12244. //
  12245. /**
  12246. * The skin index attribute.
  12247. *
  12248. * @type {AttributeNode}
  12249. */
  12250. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12251. /**
  12252. * The skin weight attribute.
  12253. *
  12254. * @type {AttributeNode}
  12255. */
  12256. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12257. /**
  12258. * The bind matrix node.
  12259. *
  12260. * @type {Node<mat4>}
  12261. */
  12262. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12263. /**
  12264. * The bind matrix inverse node.
  12265. *
  12266. * @type {Node<mat4>}
  12267. */
  12268. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12269. /**
  12270. * The bind matrices as a uniform buffer node.
  12271. *
  12272. * @type {Node}
  12273. */
  12274. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12275. /**
  12276. * The current vertex position in local space.
  12277. *
  12278. * @type {Node<vec3>}
  12279. */
  12280. this.positionNode = positionLocal;
  12281. /**
  12282. * The result of vertex position in local space.
  12283. *
  12284. * @type {Node<vec3>}
  12285. */
  12286. this.toPositionNode = positionLocal;
  12287. /**
  12288. * The previous bind matrices as a uniform buffer node.
  12289. * Required for computing motion vectors.
  12290. *
  12291. * @type {?Node}
  12292. * @default null
  12293. */
  12294. this.previousBoneMatricesNode = null;
  12295. }
  12296. /**
  12297. * Transforms the given vertex position via skinning.
  12298. *
  12299. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12300. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12301. * @return {Node<vec3>} The transformed vertex position.
  12302. */
  12303. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12304. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12305. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12306. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12307. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12308. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12309. // POSITION
  12310. const skinVertex = bindMatrixNode.mul( position );
  12311. const skinned = add(
  12312. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12313. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12314. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12315. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12316. );
  12317. return bindMatrixInverseNode.mul( skinned ).xyz;
  12318. }
  12319. /**
  12320. * Transforms the given vertex normal via skinning.
  12321. *
  12322. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12323. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12324. * @return {Node<vec3>} The transformed vertex normal.
  12325. */
  12326. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12327. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12328. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12329. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12330. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12331. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12332. // NORMAL
  12333. let skinMatrix = add(
  12334. skinWeightNode.x.mul( boneMatX ),
  12335. skinWeightNode.y.mul( boneMatY ),
  12336. skinWeightNode.z.mul( boneMatZ ),
  12337. skinWeightNode.w.mul( boneMatW )
  12338. );
  12339. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12340. return skinMatrix.transformDirection( normal ).xyz;
  12341. }
  12342. /**
  12343. * Computes the transformed/skinned vertex position of the previous frame.
  12344. *
  12345. * @param {NodeBuilder} builder - The current node builder.
  12346. * @return {Node<vec3>} The skinned position from the previous frame.
  12347. */
  12348. getPreviousSkinnedPosition( builder ) {
  12349. const skinnedMesh = builder.object;
  12350. if ( this.previousBoneMatricesNode === null ) {
  12351. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12352. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12353. }
  12354. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12355. }
  12356. /**
  12357. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12358. * when computing motion vectors with {@link VelocityNode}.
  12359. *
  12360. * @param {NodeBuilder} builder - The current node builder.
  12361. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12362. */
  12363. needsPreviousBoneMatrices( builder ) {
  12364. const mrt = builder.renderer.getMRT();
  12365. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12366. }
  12367. /**
  12368. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12369. *
  12370. * @param {NodeBuilder} builder - The current node builder.
  12371. * @return {Node<vec3>} The transformed vertex position.
  12372. */
  12373. setup( builder ) {
  12374. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12375. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12376. }
  12377. const skinPosition = this.getSkinnedPosition();
  12378. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12379. //
  12380. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12381. const skinNormal = this.getSkinnedNormal();
  12382. normalLocal.assign( skinNormal );
  12383. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12384. tangentLocal.assign( skinNormal );
  12385. }
  12386. }
  12387. return skinPosition;
  12388. }
  12389. /**
  12390. * Generates the code snippet of the skinning node.
  12391. *
  12392. * @param {NodeBuilder} builder - The current node builder.
  12393. * @param {string} output - The current output.
  12394. * @return {string} The generated code snippet.
  12395. */
  12396. generate( builder, output ) {
  12397. if ( output !== 'void' ) {
  12398. return super.generate( builder, output );
  12399. }
  12400. }
  12401. /**
  12402. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12403. *
  12404. * @param {NodeFrame} frame - The current node frame.
  12405. */
  12406. update( frame ) {
  12407. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12408. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12409. _frameId.set( skeleton, frame.frameId );
  12410. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12411. skeleton.update();
  12412. }
  12413. }
  12414. /**
  12415. * TSL function for creating a skinning node.
  12416. *
  12417. * @tsl
  12418. * @function
  12419. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12420. * @returns {SkinningNode}
  12421. */
  12422. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12423. /**
  12424. * TSL function for computing skinning.
  12425. *
  12426. * @tsl
  12427. * @function
  12428. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12429. * @param {Node<vec3>} [toPosition=null] - The target position.
  12430. * @returns {SkinningNode}
  12431. */
  12432. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12433. const node = new SkinningNode( skinnedMesh );
  12434. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12435. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12436. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12437. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12438. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12439. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12440. node.toPositionNode = toPosition;
  12441. return nodeObject( node );
  12442. };
  12443. /**
  12444. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12445. * ```js
  12446. * Loop( count, ( { i } ) => {
  12447. *
  12448. * } );
  12449. * ```
  12450. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12451. * ```js
  12452. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12453. *
  12454. * } );
  12455. *```
  12456. * Nested loops can be defined in a compacted form:
  12457. * ```js
  12458. * Loop( 10, 5, ( { i, j } ) => {
  12459. *
  12460. * } );
  12461. * ```
  12462. * Loops that should run backwards can be defined like so:
  12463. * ```js
  12464. * Loop( { start: 10 }, () => {} );
  12465. * ```
  12466. * It is possible to execute with boolean values, similar to the `while` syntax.
  12467. * ```js
  12468. * const value = float( 0 ).toVar();
  12469. *
  12470. * Loop( value.lessThan( 10 ), () => {
  12471. *
  12472. * value.addAssign( 1 );
  12473. *
  12474. * } );
  12475. * ```
  12476. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12477. * @augments Node
  12478. */
  12479. class LoopNode extends Node {
  12480. static get type() {
  12481. return 'LoopNode';
  12482. }
  12483. /**
  12484. * Constructs a new loop node.
  12485. *
  12486. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12487. */
  12488. constructor( params = [] ) {
  12489. super();
  12490. this.params = params;
  12491. }
  12492. /**
  12493. * Returns a loop variable name based on an index. The pattern is
  12494. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12495. *
  12496. * @param {number} index - The index.
  12497. * @return {string} The loop variable name.
  12498. */
  12499. getVarName( index ) {
  12500. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12501. }
  12502. /**
  12503. * Returns properties about this node.
  12504. *
  12505. * @param {NodeBuilder} builder - The current node builder.
  12506. * @return {Object} The node properties.
  12507. */
  12508. getProperties( builder ) {
  12509. const properties = builder.getNodeProperties( this );
  12510. if ( properties.stackNode !== undefined ) return properties;
  12511. //
  12512. const inputs = {};
  12513. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12514. const param = this.params[ i ];
  12515. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12516. const type = ( param.isNode !== true && param.type ) || 'int';
  12517. inputs[ name ] = expression( name, type );
  12518. }
  12519. const stack = builder.addStack(); // TODO: cache() it
  12520. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12521. properties.stackNode = stack;
  12522. const baseParam = this.params[ 0 ];
  12523. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12524. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12525. }
  12526. builder.removeStack();
  12527. return properties;
  12528. }
  12529. /**
  12530. * This method is overwritten since the node type is inferred based on the loop configuration.
  12531. *
  12532. * @param {NodeBuilder} builder - The current node builder.
  12533. * @return {string} The node type.
  12534. */
  12535. getNodeType( builder ) {
  12536. const { returnsNode } = this.getProperties( builder );
  12537. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12538. }
  12539. setup( builder ) {
  12540. // setup properties
  12541. this.getProperties( builder );
  12542. if ( builder.fnCall ) {
  12543. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12544. shaderNodeData.hasLoop = true;
  12545. }
  12546. }
  12547. generate( builder ) {
  12548. const properties = this.getProperties( builder );
  12549. const params = this.params;
  12550. const stackNode = properties.stackNode;
  12551. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12552. const param = params[ i ];
  12553. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12554. if ( param.isNode ) {
  12555. if ( param.getNodeType( builder ) === 'bool' ) {
  12556. isWhile = true;
  12557. type = 'bool';
  12558. end = param.build( builder, type );
  12559. } else {
  12560. type = 'int';
  12561. name = this.getVarName( i );
  12562. start = '0';
  12563. end = param.build( builder, type );
  12564. condition = '<';
  12565. }
  12566. } else {
  12567. type = param.type || 'int';
  12568. name = param.name || this.getVarName( i );
  12569. start = param.start;
  12570. end = param.end;
  12571. condition = param.condition;
  12572. update = param.update;
  12573. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12574. else if ( start && start.isNode ) start = start.build( builder, type );
  12575. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12576. else if ( end && end.isNode ) end = end.build( builder, type );
  12577. if ( start !== undefined && end === undefined ) {
  12578. start = start + ' - 1';
  12579. end = '0';
  12580. condition = '>=';
  12581. } else if ( end !== undefined && start === undefined ) {
  12582. start = '0';
  12583. condition = '<';
  12584. }
  12585. if ( condition === undefined ) {
  12586. if ( Number( start ) > Number( end ) ) {
  12587. condition = '>=';
  12588. } else {
  12589. condition = '<';
  12590. }
  12591. }
  12592. }
  12593. let loopSnippet;
  12594. if ( isWhile ) {
  12595. loopSnippet = `while ( ${ end } )`;
  12596. } else {
  12597. const internalParam = { start, end};
  12598. //
  12599. const startSnippet = internalParam.start;
  12600. const endSnippet = internalParam.end;
  12601. let updateSnippet;
  12602. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12603. if ( update !== undefined && update !== null ) {
  12604. switch ( typeof update ) {
  12605. case 'function':
  12606. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12607. const snippet = flow.code.replace( /\t|;/g, '' );
  12608. updateSnippet = snippet;
  12609. break;
  12610. case 'number':
  12611. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12612. break;
  12613. case 'string':
  12614. updateSnippet = name + ' ' + update;
  12615. break;
  12616. default:
  12617. if ( update.isNode ) {
  12618. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12619. } else {
  12620. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12621. updateSnippet = 'break /* invalid update */';
  12622. }
  12623. }
  12624. } else {
  12625. if ( type === 'int' || type === 'uint' ) {
  12626. update = condition.includes( '<' ) ? '++' : '--';
  12627. } else {
  12628. update = deltaOperator() + ' 1.';
  12629. }
  12630. updateSnippet = name + ' ' + update;
  12631. }
  12632. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12633. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12634. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12635. }
  12636. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12637. }
  12638. const stackSnippet = stackNode.build( builder, 'void' );
  12639. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12640. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12641. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12642. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12643. }
  12644. builder.addFlowTab();
  12645. return returnsSnippet;
  12646. }
  12647. }
  12648. /**
  12649. * TSL function for creating a loop node.
  12650. *
  12651. * @tsl
  12652. * @function
  12653. * @param {...any} params - A list of parameters.
  12654. * @returns {LoopNode}
  12655. */
  12656. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12657. /**
  12658. * TSL function for creating a `Continue()` expression.
  12659. *
  12660. * @tsl
  12661. * @function
  12662. * @returns {ExpressionNode}
  12663. */
  12664. const Continue = () => expression( 'continue' ).toStack();
  12665. /**
  12666. * TSL function for creating a `Break()` expression.
  12667. *
  12668. * @tsl
  12669. * @function
  12670. * @returns {ExpressionNode}
  12671. */
  12672. const Break = () => expression( 'break' ).toStack();
  12673. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12674. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12675. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12676. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12677. const y = texelIndex.div( width );
  12678. const x = texelIndex.sub( y.mul( width ) );
  12679. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12680. return bufferAttrib.mul( influence );
  12681. } );
  12682. function getEntry( geometry ) {
  12683. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12684. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12685. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12686. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12687. // into an array of data textures. Each layer represents a single morph target.
  12688. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12689. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12690. let entry = _morphTextures.get( geometry );
  12691. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12692. if ( entry !== undefined ) entry.texture.dispose();
  12693. const morphTargets = geometry.morphAttributes.position || [];
  12694. const morphNormals = geometry.morphAttributes.normal || [];
  12695. const morphColors = geometry.morphAttributes.color || [];
  12696. let vertexDataCount = 0;
  12697. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12698. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12699. if ( hasMorphColors === true ) vertexDataCount = 3;
  12700. let width = geometry.attributes.position.count * vertexDataCount;
  12701. let height = 1;
  12702. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12703. if ( width > maxTextureSize ) {
  12704. height = Math.ceil( width / maxTextureSize );
  12705. width = maxTextureSize;
  12706. }
  12707. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12708. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12709. bufferTexture.type = FloatType;
  12710. bufferTexture.needsUpdate = true;
  12711. // fill buffer
  12712. const vertexDataStride = vertexDataCount * 4;
  12713. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12714. const morphTarget = morphTargets[ i ];
  12715. const morphNormal = morphNormals[ i ];
  12716. const morphColor = morphColors[ i ];
  12717. const offset = width * height * 4 * i;
  12718. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12719. const stride = j * vertexDataStride;
  12720. if ( hasMorphPosition === true ) {
  12721. _morphVec4.fromBufferAttribute( morphTarget, j );
  12722. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12723. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12724. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12725. buffer[ offset + stride + 3 ] = 0;
  12726. }
  12727. if ( hasMorphNormals === true ) {
  12728. _morphVec4.fromBufferAttribute( morphNormal, j );
  12729. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12730. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12731. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12732. buffer[ offset + stride + 7 ] = 0;
  12733. }
  12734. if ( hasMorphColors === true ) {
  12735. _morphVec4.fromBufferAttribute( morphColor, j );
  12736. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12737. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12738. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12739. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12740. }
  12741. }
  12742. }
  12743. entry = {
  12744. count: morphTargetsCount,
  12745. texture: bufferTexture,
  12746. stride: vertexDataCount,
  12747. size: new Vector2( width, height )
  12748. };
  12749. _morphTextures.set( geometry, entry );
  12750. function disposeTexture() {
  12751. bufferTexture.dispose();
  12752. _morphTextures.delete( geometry );
  12753. geometry.removeEventListener( 'dispose', disposeTexture );
  12754. }
  12755. geometry.addEventListener( 'dispose', disposeTexture );
  12756. }
  12757. return entry;
  12758. }
  12759. /**
  12760. * This node implements the vertex transformation shader logic which is required
  12761. * for morph target animation.
  12762. *
  12763. * @augments Node
  12764. */
  12765. class MorphNode extends Node {
  12766. static get type() {
  12767. return 'MorphNode';
  12768. }
  12769. /**
  12770. * Constructs a new morph node.
  12771. *
  12772. * @param {Mesh} mesh - The mesh holding the morph targets.
  12773. */
  12774. constructor( mesh ) {
  12775. super( 'void' );
  12776. /**
  12777. * The mesh holding the morph targets.
  12778. *
  12779. * @type {Mesh}
  12780. */
  12781. this.mesh = mesh;
  12782. /**
  12783. * A uniform node which represents the morph base influence value.
  12784. *
  12785. * @type {UniformNode<float>}
  12786. */
  12787. this.morphBaseInfluence = uniform( 1 );
  12788. /**
  12789. * The update type overwritten since morph nodes are updated per object.
  12790. *
  12791. * @type {string}
  12792. */
  12793. this.updateType = NodeUpdateType.OBJECT;
  12794. }
  12795. /**
  12796. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12797. *
  12798. * @param {NodeBuilder} builder - The current node builder.
  12799. */
  12800. setup( builder ) {
  12801. const { geometry } = builder;
  12802. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12803. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12804. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12805. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12806. // nodes
  12807. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12808. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12809. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12810. const width = int( size.width );
  12811. Loop( morphTargetsCount, ( { i } ) => {
  12812. const influence = float( 0 ).toVar();
  12813. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12814. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12815. } else {
  12816. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12817. }
  12818. If( influence.notEqual( 0 ), () => {
  12819. if ( hasMorphPosition === true ) {
  12820. positionLocal.addAssign( getMorph( {
  12821. bufferMap,
  12822. influence,
  12823. stride,
  12824. width,
  12825. depth: i,
  12826. offset: int( 0 )
  12827. } ) );
  12828. }
  12829. if ( hasMorphNormals === true ) {
  12830. normalLocal.addAssign( getMorph( {
  12831. bufferMap,
  12832. influence,
  12833. stride,
  12834. width,
  12835. depth: i,
  12836. offset: int( 1 )
  12837. } ) );
  12838. }
  12839. } );
  12840. } );
  12841. }
  12842. /**
  12843. * Updates the state of the morphed mesh by updating the base influence.
  12844. *
  12845. * @param {NodeFrame} frame - The current node frame.
  12846. */
  12847. update( /*frame*/ ) {
  12848. const morphBaseInfluence = this.morphBaseInfluence;
  12849. if ( this.mesh.geometry.morphTargetsRelative ) {
  12850. morphBaseInfluence.value = 1;
  12851. } else {
  12852. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12853. }
  12854. }
  12855. }
  12856. /**
  12857. * TSL function for creating a morph node.
  12858. *
  12859. * @tsl
  12860. * @function
  12861. * @param {Mesh} mesh - The mesh holding the morph targets.
  12862. * @returns {MorphNode}
  12863. */
  12864. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12865. /**
  12866. * Base class for lighting nodes.
  12867. *
  12868. * @augments Node
  12869. */
  12870. class LightingNode extends Node {
  12871. static get type() {
  12872. return 'LightingNode';
  12873. }
  12874. /**
  12875. * Constructs a new lighting node.
  12876. */
  12877. constructor() {
  12878. super( 'vec3' );
  12879. /**
  12880. * This flag can be used for type testing.
  12881. *
  12882. * @type {boolean}
  12883. * @readonly
  12884. * @default true
  12885. */
  12886. this.isLightingNode = true;
  12887. }
  12888. }
  12889. /**
  12890. * A generic class that can be used by nodes which contribute
  12891. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12892. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12893. *
  12894. * @augments LightingNode
  12895. */
  12896. class AONode extends LightingNode {
  12897. static get type() {
  12898. return 'AONode';
  12899. }
  12900. /**
  12901. * Constructs a new AO node.
  12902. *
  12903. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12904. */
  12905. constructor( aoNode = null ) {
  12906. super();
  12907. /**
  12908. * The ambient occlusion node.
  12909. *
  12910. * @type {?Node<float>}
  12911. * @default null
  12912. */
  12913. this.aoNode = aoNode;
  12914. }
  12915. setup( builder ) {
  12916. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12917. }
  12918. }
  12919. /**
  12920. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12921. * by adding lighting specific context data. It represents the runtime context of
  12922. * {@link LightsNode}.
  12923. *
  12924. * @augments ContextNode
  12925. */
  12926. class LightingContextNode extends ContextNode {
  12927. static get type() {
  12928. return 'LightingContextNode';
  12929. }
  12930. /**
  12931. * Constructs a new lighting context node.
  12932. *
  12933. * @param {LightsNode} lightsNode - The lights node.
  12934. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12935. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12936. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12937. */
  12938. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12939. super( lightsNode );
  12940. /**
  12941. * The current lighting model.
  12942. *
  12943. * @type {?LightingModel}
  12944. * @default null
  12945. */
  12946. this.lightingModel = lightingModel;
  12947. /**
  12948. * A backdrop node.
  12949. *
  12950. * @type {?Node<vec3>}
  12951. * @default null
  12952. */
  12953. this.backdropNode = backdropNode;
  12954. /**
  12955. * A backdrop alpha node.
  12956. *
  12957. * @type {?Node<float>}
  12958. * @default null
  12959. */
  12960. this.backdropAlphaNode = backdropAlphaNode;
  12961. this._value = null;
  12962. }
  12963. /**
  12964. * Returns a lighting context object.
  12965. *
  12966. * @return {{
  12967. * radiance: Node<vec3>,
  12968. * irradiance: Node<vec3>,
  12969. * iblIrradiance: Node<vec3>,
  12970. * ambientOcclusion: Node<float>,
  12971. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12972. * backdrop: Node<vec3>,
  12973. * backdropAlpha: Node<float>
  12974. * }} The lighting context object.
  12975. */
  12976. getContext() {
  12977. const { backdropNode, backdropAlphaNode } = this;
  12978. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12979. directSpecular = vec3().toVar( 'directSpecular' ),
  12980. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12981. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12982. const reflectedLight = {
  12983. directDiffuse,
  12984. directSpecular,
  12985. indirectDiffuse,
  12986. indirectSpecular
  12987. };
  12988. const context = {
  12989. radiance: vec3().toVar( 'radiance' ),
  12990. irradiance: vec3().toVar( 'irradiance' ),
  12991. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12992. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12993. reflectedLight,
  12994. backdrop: backdropNode,
  12995. backdropAlpha: backdropAlphaNode
  12996. };
  12997. return context;
  12998. }
  12999. setup( builder ) {
  13000. this.value = this._value || ( this._value = this.getContext() );
  13001. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13002. return super.setup( builder );
  13003. }
  13004. }
  13005. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13006. /**
  13007. * A generic class that can be used by nodes which contribute
  13008. * irradiance to the scene. E.g. a light map node can be used
  13009. * as input for this module. Used in {@link NodeMaterial}.
  13010. *
  13011. * @augments LightingNode
  13012. */
  13013. class IrradianceNode extends LightingNode {
  13014. static get type() {
  13015. return 'IrradianceNode';
  13016. }
  13017. /**
  13018. * Constructs a new irradiance node.
  13019. *
  13020. * @param {Node<vec3>} node - A node contributing irradiance.
  13021. */
  13022. constructor( node ) {
  13023. super();
  13024. /**
  13025. * A node contributing irradiance.
  13026. *
  13027. * @type {Node<vec3>}
  13028. */
  13029. this.node = node;
  13030. }
  13031. setup( builder ) {
  13032. builder.context.irradiance.addAssign( this.node );
  13033. }
  13034. }
  13035. const _size$5 = /*@__PURE__*/ new Vector2();
  13036. /**
  13037. * A special type of texture node which represents the data of the current viewport
  13038. * as a texture. The module extracts data from the current bound framebuffer with
  13039. * a copy operation so no extra render pass is required to produce the texture data
  13040. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13041. * variety of effects like refractive or transmissive materials.
  13042. *
  13043. * @augments TextureNode
  13044. */
  13045. class ViewportTextureNode extends TextureNode {
  13046. static get type() {
  13047. return 'ViewportTextureNode';
  13048. }
  13049. /**
  13050. * Constructs a new viewport texture node.
  13051. *
  13052. * @param {Node} [uvNode=screenUV] - The uv node.
  13053. * @param {?Node} [levelNode=null] - The level node.
  13054. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13055. */
  13056. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13057. let defaultFramebuffer = null;
  13058. if ( framebufferTexture === null ) {
  13059. defaultFramebuffer = new FramebufferTexture();
  13060. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13061. framebufferTexture = defaultFramebuffer;
  13062. } else {
  13063. defaultFramebuffer = framebufferTexture;
  13064. }
  13065. super( framebufferTexture, uvNode, levelNode );
  13066. /**
  13067. * Whether to generate mipmaps or not.
  13068. *
  13069. * @type {boolean}
  13070. * @default false
  13071. */
  13072. this.generateMipmaps = false;
  13073. /**
  13074. * The reference framebuffer texture. This is used to store the framebuffer texture
  13075. * for the current render target. If the render target changes, a new framebuffer texture
  13076. * is created automatically.
  13077. *
  13078. * @type {FramebufferTexture}
  13079. * @default null
  13080. */
  13081. this.defaultFramebuffer = defaultFramebuffer;
  13082. /**
  13083. * This flag can be used for type testing.
  13084. *
  13085. * @type {boolean}
  13086. * @readonly
  13087. * @default true
  13088. */
  13089. this.isOutputTextureNode = true;
  13090. /**
  13091. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13092. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13093. *
  13094. * @type {string}
  13095. * @default 'frame'
  13096. */
  13097. this.updateBeforeType = NodeUpdateType.FRAME;
  13098. /**
  13099. * The framebuffer texture for the current renderer context.
  13100. *
  13101. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13102. * @private
  13103. */
  13104. this._cacheTextures = new WeakMap();
  13105. }
  13106. /**
  13107. * This methods returns a texture for the given render target reference.
  13108. *
  13109. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13110. * for different render contexts.
  13111. *
  13112. * @param {?RenderTarget} [reference=null] - The render target reference.
  13113. * @return {Texture} The framebuffer texture.
  13114. */
  13115. getTextureForReference( reference = null ) {
  13116. let defaultFramebuffer;
  13117. let cacheTextures;
  13118. if ( this.referenceNode ) {
  13119. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13120. cacheTextures = this.referenceNode._cacheTextures;
  13121. } else {
  13122. defaultFramebuffer = this.defaultFramebuffer;
  13123. cacheTextures = this._cacheTextures;
  13124. }
  13125. if ( reference === null ) {
  13126. return defaultFramebuffer;
  13127. }
  13128. if ( cacheTextures.has( reference ) === false ) {
  13129. const framebufferTexture = defaultFramebuffer.clone();
  13130. cacheTextures.set( reference, framebufferTexture );
  13131. }
  13132. return cacheTextures.get( reference );
  13133. }
  13134. updateReference( frame ) {
  13135. const renderTarget = frame.renderer.getRenderTarget();
  13136. this.value = this.getTextureForReference( renderTarget );
  13137. return this.value;
  13138. }
  13139. updateBefore( frame ) {
  13140. const renderer = frame.renderer;
  13141. const renderTarget = renderer.getRenderTarget();
  13142. if ( renderTarget === null ) {
  13143. renderer.getDrawingBufferSize( _size$5 );
  13144. } else {
  13145. _size$5.set( renderTarget.width, renderTarget.height );
  13146. }
  13147. //
  13148. const framebufferTexture = this.getTextureForReference( renderTarget );
  13149. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13150. framebufferTexture.image.width = _size$5.width;
  13151. framebufferTexture.image.height = _size$5.height;
  13152. framebufferTexture.needsUpdate = true;
  13153. }
  13154. //
  13155. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13156. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13157. renderer.copyFramebufferToTexture( framebufferTexture );
  13158. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13159. }
  13160. clone() {
  13161. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13162. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13163. return viewportTextureNode;
  13164. }
  13165. }
  13166. /**
  13167. * TSL function for creating a viewport texture node.
  13168. *
  13169. * @tsl
  13170. * @function
  13171. * @param {?Node} [uvNode=screenUV] - The uv node.
  13172. * @param {?Node} [levelNode=null] - The level node.
  13173. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13174. * @returns {ViewportTextureNode}
  13175. */
  13176. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13177. /**
  13178. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13179. *
  13180. * @tsl
  13181. * @function
  13182. * @param {?Node} [uvNode=screenUV] - The uv node.
  13183. * @param {?Node} [levelNode=null] - The level node.
  13184. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13185. * @returns {ViewportTextureNode}
  13186. */
  13187. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13188. let _sharedDepthbuffer = null;
  13189. /**
  13190. * Represents the depth of the current viewport as a texture. This module
  13191. * can be used in combination with viewport texture to achieve effects
  13192. * that require depth evaluation.
  13193. *
  13194. * @augments ViewportTextureNode
  13195. */
  13196. class ViewportDepthTextureNode extends ViewportTextureNode {
  13197. static get type() {
  13198. return 'ViewportDepthTextureNode';
  13199. }
  13200. /**
  13201. * Constructs a new viewport depth texture node.
  13202. *
  13203. * @param {Node} [uvNode=screenUV] - The uv node.
  13204. * @param {?Node} [levelNode=null] - The level node.
  13205. */
  13206. constructor( uvNode = screenUV, levelNode = null ) {
  13207. if ( _sharedDepthbuffer === null ) {
  13208. _sharedDepthbuffer = new DepthTexture();
  13209. }
  13210. super( uvNode, levelNode, _sharedDepthbuffer );
  13211. }
  13212. /**
  13213. * Overwritten so the method always returns the unique shared
  13214. * depth texture.
  13215. *
  13216. * @return {DepthTexture} The shared depth texture.
  13217. */
  13218. getTextureForReference() {
  13219. return _sharedDepthbuffer;
  13220. }
  13221. }
  13222. /**
  13223. * TSL function for a viewport depth texture node.
  13224. *
  13225. * @tsl
  13226. * @function
  13227. * @param {?Node} [uvNode=screenUV] - The uv node.
  13228. * @param {?Node} [levelNode=null] - The level node.
  13229. * @returns {ViewportDepthTextureNode}
  13230. */
  13231. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13232. /**
  13233. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13234. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13235. * fragment or for depth evaluation purposes.
  13236. *
  13237. * @augments Node
  13238. */
  13239. class ViewportDepthNode extends Node {
  13240. static get type() {
  13241. return 'ViewportDepthNode';
  13242. }
  13243. /**
  13244. * Constructs a new viewport depth node.
  13245. *
  13246. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13247. * @param {?Node} [valueNode=null] - The value node.
  13248. */
  13249. constructor( scope, valueNode = null ) {
  13250. super( 'float' );
  13251. /**
  13252. * The node behaves differently depending on which scope is selected.
  13253. *
  13254. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13255. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13256. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13257. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13258. *
  13259. * @type {('depth'|'depthBase'|'linearDepth')}
  13260. */
  13261. this.scope = scope;
  13262. /**
  13263. * Can be used to define a custom depth value.
  13264. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13265. *
  13266. * @type {?Node}
  13267. * @default null
  13268. */
  13269. this.valueNode = valueNode;
  13270. /**
  13271. * This flag can be used for type testing.
  13272. *
  13273. * @type {boolean}
  13274. * @readonly
  13275. * @default true
  13276. */
  13277. this.isViewportDepthNode = true;
  13278. }
  13279. generate( builder ) {
  13280. const { scope } = this;
  13281. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13282. return builder.getFragDepth();
  13283. }
  13284. return super.generate( builder );
  13285. }
  13286. setup( { camera } ) {
  13287. const { scope } = this;
  13288. const value = this.valueNode;
  13289. let node = null;
  13290. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13291. if ( value !== null ) {
  13292. node = depthBase().assign( value );
  13293. }
  13294. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13295. if ( camera.isPerspectiveCamera ) {
  13296. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13297. } else {
  13298. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13299. }
  13300. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13301. if ( value !== null ) {
  13302. if ( camera.isPerspectiveCamera ) {
  13303. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13304. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13305. } else {
  13306. node = value;
  13307. }
  13308. } else {
  13309. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13310. }
  13311. }
  13312. return node;
  13313. }
  13314. }
  13315. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13316. ViewportDepthNode.DEPTH = 'depth';
  13317. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13318. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13319. /**
  13320. * TSL function for converting a viewZ value to an orthographic depth value.
  13321. *
  13322. * @tsl
  13323. * @function
  13324. * @param {Node<float>} viewZ - The viewZ node.
  13325. * @param {Node<float>} near - The camera's near value.
  13326. * @param {Node<float>} far - The camera's far value.
  13327. * @returns {Node<float>}
  13328. */
  13329. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13330. /**
  13331. * TSL function for converting an orthographic depth value to a viewZ value.
  13332. *
  13333. * @tsl
  13334. * @function
  13335. * @param {Node<float>} depth - The orthographic depth.
  13336. * @param {Node<float>} near - The camera's near value.
  13337. * @param {Node<float>} far - The camera's far value.
  13338. * @returns {Node<float>}
  13339. */
  13340. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13341. /**
  13342. * TSL function for converting a viewZ value to a perspective depth value.
  13343. *
  13344. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13345. *
  13346. * @tsl
  13347. * @function
  13348. * @param {Node<float>} viewZ - The viewZ node.
  13349. * @param {Node<float>} near - The camera's near value.
  13350. * @param {Node<float>} far - The camera's far value.
  13351. * @returns {Node<float>}
  13352. */
  13353. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13354. /**
  13355. * TSL function for converting a perspective depth value to a viewZ value.
  13356. *
  13357. * @tsl
  13358. * @function
  13359. * @param {Node<float>} depth - The perspective depth.
  13360. * @param {Node<float>} near - The camera's near value.
  13361. * @param {Node<float>} far - The camera's far value.
  13362. * @returns {Node<float>}
  13363. */
  13364. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13365. /**
  13366. * TSL function for converting a viewZ value to a logarithmic depth value.
  13367. *
  13368. * @tsl
  13369. * @function
  13370. * @param {Node<float>} viewZ - The viewZ node.
  13371. * @param {Node<float>} near - The camera's near value.
  13372. * @param {Node<float>} far - The camera's far value.
  13373. * @returns {Node<float>}
  13374. */
  13375. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13376. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13377. // The final logarithmic depth formula used here is adapted from one described in an
  13378. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13379. // which was an improvement upon an earlier formula one described in an
  13380. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13381. // Ulrich's formula is the following:
  13382. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13383. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13384. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13385. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13386. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13387. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13388. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13389. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13390. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13391. // Outerra eventually made another improvement to their original "C-constant" variant,
  13392. // but it still does not incorporate the camera near plane (for this version,
  13393. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13394. // Here we make 4 changes to Ulrich's formula:
  13395. // 1. Clamp the camera near plane so we don't divide by 0.
  13396. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13397. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13398. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13399. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13400. // so we do the same here, hence the 'viewZ.negate()' call.
  13401. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13402. near = near.max( 1e-6 ).toVar();
  13403. const numerator = log2( viewZ.negate().div( near ) );
  13404. const denominator = log2( far.div( near ) );
  13405. return numerator.div( denominator );
  13406. };
  13407. /**
  13408. * TSL function for converting a logarithmic depth value to a viewZ value.
  13409. *
  13410. * @tsl
  13411. * @function
  13412. * @param {Node<float>} depth - The logarithmic depth.
  13413. * @param {Node<float>} near - The camera's near value.
  13414. * @param {Node<float>} far - The camera's far value.
  13415. * @returns {Node<float>}
  13416. */
  13417. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13418. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13419. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13420. // a negative viewZ).
  13421. const exponent = depth.mul( log( far.div( near ) ) );
  13422. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13423. };
  13424. /**
  13425. * TSL function for defining a value for the current fragment's depth.
  13426. *
  13427. * @tsl
  13428. * @function
  13429. * @param {Node<float>} value - The depth value to set.
  13430. * @returns {ViewportDepthNode<float>}
  13431. */
  13432. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13433. /**
  13434. * TSL object that represents the depth value for the current fragment.
  13435. *
  13436. * @tsl
  13437. * @type {ViewportDepthNode}
  13438. */
  13439. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13440. /**
  13441. * TSL function for converting a perspective depth value to linear depth.
  13442. *
  13443. * @tsl
  13444. * @function
  13445. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13446. * @returns {ViewportDepthNode<float>}
  13447. */
  13448. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13449. /**
  13450. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13451. *
  13452. * @tsl
  13453. * @type {ViewportDepthNode}
  13454. */
  13455. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13456. depth.assign = ( value ) => depthBase( value );
  13457. /**
  13458. * This node is used in {@link NodeMaterial} to setup the clipping
  13459. * which can happen hardware-accelerated (if supported) and optionally
  13460. * use alpha-to-coverage for anti-aliasing clipped edges.
  13461. *
  13462. * @augments Node
  13463. */
  13464. class ClippingNode extends Node {
  13465. static get type() {
  13466. return 'ClippingNode';
  13467. }
  13468. /**
  13469. * Constructs a new clipping node.
  13470. *
  13471. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13472. * the selected scope influences the behavior of the node and what type of code is generated.
  13473. */
  13474. constructor( scope = ClippingNode.DEFAULT ) {
  13475. super();
  13476. /**
  13477. * The node's scope. Similar to other nodes, the selected scope influences
  13478. * the behavior of the node and what type of code is generated.
  13479. *
  13480. * @type {('default'|'hardware'|'alphaToCoverage')}
  13481. */
  13482. this.scope = scope;
  13483. }
  13484. /**
  13485. * Setups the node depending on the selected scope.
  13486. *
  13487. * @param {NodeBuilder} builder - The current node builder.
  13488. * @return {Node} The result node.
  13489. */
  13490. setup( builder ) {
  13491. super.setup( builder );
  13492. const clippingContext = builder.clippingContext;
  13493. const { intersectionPlanes, unionPlanes } = clippingContext;
  13494. this.hardwareClipping = builder.material.hardwareClipping;
  13495. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13496. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13497. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13498. return this.setupHardwareClipping( unionPlanes, builder );
  13499. } else {
  13500. return this.setupDefault( intersectionPlanes, unionPlanes );
  13501. }
  13502. }
  13503. /**
  13504. * Setups alpha to coverage.
  13505. *
  13506. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13507. * @param {Array<Vector4>} unionPlanes - The union planes.
  13508. * @return {Node} The result node.
  13509. */
  13510. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13511. return Fn( () => {
  13512. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13513. const distanceGradient = float().toVar( 'distanceToGradient' );
  13514. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13515. const numUnionPlanes = unionPlanes.length;
  13516. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13517. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13518. Loop( numUnionPlanes, ( { i } ) => {
  13519. const plane = clippingPlanes.element( i );
  13520. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13521. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13522. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13523. } );
  13524. }
  13525. const numIntersectionPlanes = intersectionPlanes.length;
  13526. if ( numIntersectionPlanes > 0 ) {
  13527. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13528. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13529. Loop( numIntersectionPlanes, ( { i } ) => {
  13530. const plane = clippingPlanes.element( i );
  13531. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13532. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13533. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13534. } );
  13535. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13536. }
  13537. diffuseColor.a.mulAssign( clipOpacity );
  13538. diffuseColor.a.equal( 0.0 ).discard();
  13539. } )();
  13540. }
  13541. /**
  13542. * Setups the default clipping.
  13543. *
  13544. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13545. * @param {Array<Vector4>} unionPlanes - The union planes.
  13546. * @return {Node} The result node.
  13547. */
  13548. setupDefault( intersectionPlanes, unionPlanes ) {
  13549. return Fn( () => {
  13550. const numUnionPlanes = unionPlanes.length;
  13551. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13552. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13553. Loop( numUnionPlanes, ( { i } ) => {
  13554. const plane = clippingPlanes.element( i );
  13555. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13556. } );
  13557. }
  13558. const numIntersectionPlanes = intersectionPlanes.length;
  13559. if ( numIntersectionPlanes > 0 ) {
  13560. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13561. const clipped = bool( true ).toVar( 'clipped' );
  13562. Loop( numIntersectionPlanes, ( { i } ) => {
  13563. const plane = clippingPlanes.element( i );
  13564. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13565. } );
  13566. clipped.discard();
  13567. }
  13568. } )();
  13569. }
  13570. /**
  13571. * Setups hardware clipping.
  13572. *
  13573. * @param {Array<Vector4>} unionPlanes - The union planes.
  13574. * @param {NodeBuilder} builder - The current node builder.
  13575. * @return {Node} The result node.
  13576. */
  13577. setupHardwareClipping( unionPlanes, builder ) {
  13578. const numUnionPlanes = unionPlanes.length;
  13579. builder.enableHardwareClipping( numUnionPlanes );
  13580. return Fn( () => {
  13581. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13582. const hw_clip_distances = builtin( builder.getClipDistance() );
  13583. Loop( numUnionPlanes, ( { i } ) => {
  13584. const plane = clippingPlanes.element( i );
  13585. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13586. hw_clip_distances.element( i ).assign( distance );
  13587. } );
  13588. } )();
  13589. }
  13590. }
  13591. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13592. ClippingNode.DEFAULT = 'default';
  13593. ClippingNode.HARDWARE = 'hardware';
  13594. /**
  13595. * TSL function for setting up the default clipping logic.
  13596. *
  13597. * @tsl
  13598. * @function
  13599. * @returns {ClippingNode}
  13600. */
  13601. const clipping = () => nodeObject( new ClippingNode() );
  13602. /**
  13603. * TSL function for setting up alpha to coverage.
  13604. *
  13605. * @tsl
  13606. * @function
  13607. * @returns {ClippingNode}
  13608. */
  13609. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13610. /**
  13611. * TSL function for setting up hardware-based clipping.
  13612. *
  13613. * @tsl
  13614. * @function
  13615. * @returns {ClippingNode}
  13616. */
  13617. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13618. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13619. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13620. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13621. 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 ) ) ) ) ) );
  13622. } );
  13623. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13624. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13625. } );
  13626. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13627. // Find the discretized derivatives of our coordinates
  13628. const maxDeriv = max$1(
  13629. length( dFdx( position.xyz ) ),
  13630. length( dFdy( position.xyz ) )
  13631. );
  13632. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13633. // Find two nearest log-discretized noise scales
  13634. const pixScales = vec2(
  13635. exp2( floor( log2( pixScale ) ) ),
  13636. exp2( ceil( log2( pixScale ) ) )
  13637. );
  13638. // Compute alpha thresholds at our two noise scales
  13639. const alpha = vec2(
  13640. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13641. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13642. );
  13643. // Factor to interpolate lerp with
  13644. const lerpFactor = fract( log2( pixScale ) );
  13645. // Interpolate alpha threshold from noise at two scales
  13646. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13647. // Pass into CDF to compute uniformly distrib threshold
  13648. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13649. const cases = vec3(
  13650. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13651. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13652. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13653. // Find our final, uniformly distributed alpha threshold (ατ)
  13654. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13655. // Avoids ατ == 0. Could also do ατ =1-ατ
  13656. return clamp( threshold, 1.0e-6, 1.0 );
  13657. } ).setLayout( {
  13658. name: 'getAlphaHashThreshold',
  13659. type: 'float',
  13660. inputs: [
  13661. { name: 'position', type: 'vec3' }
  13662. ]
  13663. } );
  13664. /**
  13665. * An attribute node for representing vertex colors.
  13666. *
  13667. * @augments AttributeNode
  13668. */
  13669. class VertexColorNode extends AttributeNode {
  13670. static get type() {
  13671. return 'VertexColorNode';
  13672. }
  13673. /**
  13674. * Constructs a new vertex color node.
  13675. *
  13676. * @param {number} index - The attribute index.
  13677. */
  13678. constructor( index ) {
  13679. super( null, 'vec4' );
  13680. /**
  13681. * This flag can be used for type testing.
  13682. *
  13683. * @type {boolean}
  13684. * @readonly
  13685. * @default true
  13686. */
  13687. this.isVertexColorNode = true;
  13688. /**
  13689. * The attribute index to enable more than one sets of vertex colors.
  13690. *
  13691. * @type {number}
  13692. * @default 0
  13693. */
  13694. this.index = index;
  13695. }
  13696. /**
  13697. * Overwrites the default implementation by honoring the attribute index.
  13698. *
  13699. * @param {NodeBuilder} builder - The current node builder.
  13700. * @return {string} The attribute name.
  13701. */
  13702. getAttributeName( /*builder*/ ) {
  13703. const index = this.index;
  13704. return 'color' + ( index > 0 ? index : '' );
  13705. }
  13706. generate( builder ) {
  13707. const attributeName = this.getAttributeName( builder );
  13708. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13709. let result;
  13710. if ( geometryAttribute === true ) {
  13711. result = super.generate( builder );
  13712. } else {
  13713. // Vertex color fallback should be white
  13714. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13715. }
  13716. return result;
  13717. }
  13718. serialize( data ) {
  13719. super.serialize( data );
  13720. data.index = this.index;
  13721. }
  13722. deserialize( data ) {
  13723. super.deserialize( data );
  13724. this.index = data.index;
  13725. }
  13726. }
  13727. /**
  13728. * TSL function for creating a reference node.
  13729. *
  13730. * @tsl
  13731. * @function
  13732. * @param {number} [index=0] - The attribute index.
  13733. * @returns {VertexColorNode}
  13734. */
  13735. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13736. /**
  13737. * Represents a "Color Burn" blend mode.
  13738. *
  13739. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13740. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13741. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13742. *
  13743. * @tsl
  13744. * @function
  13745. * @param {Node<vec3>} base - The base color.
  13746. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13747. * @return {Node<vec3>} The result.
  13748. */
  13749. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13750. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13751. } ).setLayout( {
  13752. name: 'blendBurn',
  13753. type: 'vec3',
  13754. inputs: [
  13755. { name: 'base', type: 'vec3' },
  13756. { name: 'blend', type: 'vec3' }
  13757. ]
  13758. } );
  13759. /**
  13760. * Represents a "Color Dodge" blend mode.
  13761. *
  13762. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13763. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13764. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13765. *
  13766. * @tsl
  13767. * @function
  13768. * @param {Node<vec3>} base - The base color.
  13769. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13770. * @return {Node<vec3>} The result.
  13771. */
  13772. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13773. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13774. } ).setLayout( {
  13775. name: 'blendDodge',
  13776. type: 'vec3',
  13777. inputs: [
  13778. { name: 'base', type: 'vec3' },
  13779. { name: 'blend', type: 'vec3' }
  13780. ]
  13781. } );
  13782. /**
  13783. * Represents a "Screen" blend mode.
  13784. *
  13785. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13786. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13787. * effects.
  13788. *
  13789. * @tsl
  13790. * @function
  13791. * @param {Node<vec3>} base - The base color.
  13792. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13793. * @return {Node<vec3>} The result.
  13794. */
  13795. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13796. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13797. } ).setLayout( {
  13798. name: 'blendScreen',
  13799. type: 'vec3',
  13800. inputs: [
  13801. { name: 'base', type: 'vec3' },
  13802. { name: 'blend', type: 'vec3' }
  13803. ]
  13804. } );
  13805. /**
  13806. * Represents a "Overlay" blend mode.
  13807. *
  13808. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13809. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13810. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13811. *
  13812. * @tsl
  13813. * @function
  13814. * @param {Node<vec3>} base - The base color.
  13815. * @param {Node<vec3>} blend - The blend color
  13816. * @return {Node<vec3>} The result.
  13817. */
  13818. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13819. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13820. } ).setLayout( {
  13821. name: 'blendOverlay',
  13822. type: 'vec3',
  13823. inputs: [
  13824. { name: 'base', type: 'vec3' },
  13825. { name: 'blend', type: 'vec3' }
  13826. ]
  13827. } );
  13828. /**
  13829. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13830. * It assumes both input colors have non-premultiplied alpha.
  13831. *
  13832. * @tsl
  13833. * @function
  13834. * @param {Node<vec4>} base - The base color.
  13835. * @param {Node<vec4>} blend - The blend color
  13836. * @return {Node<vec4>} The result.
  13837. */
  13838. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13839. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13840. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13841. } ).setLayout( {
  13842. name: 'blendColor',
  13843. type: 'vec4',
  13844. inputs: [
  13845. { name: 'base', type: 'vec4' },
  13846. { name: 'blend', type: 'vec4' }
  13847. ]
  13848. } );
  13849. /**
  13850. * Premultiplies the RGB channels of a color by its alpha channel.
  13851. *
  13852. * This function is useful for converting a non-premultiplied alpha color
  13853. * into a premultiplied alpha format, where the RGB values are scaled
  13854. * by the alpha value. Premultiplied alpha is often used in graphics
  13855. * rendering for certain operations, such as compositing and image processing.
  13856. *
  13857. * @tsl
  13858. * @function
  13859. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13860. * @return {Node<vec4>} The color with premultiplied alpha.
  13861. */
  13862. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13863. return vec4( color.rgb.mul( color.a ), color.a );
  13864. }, { color: 'vec4', return: 'vec4' } );
  13865. /**
  13866. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13867. *
  13868. * This function is useful for converting a premultiplied alpha color
  13869. * back into a non-premultiplied alpha format, where the RGB values are
  13870. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13871. * rendering for certain operations, such as compositing and image processing.
  13872. *
  13873. * @tsl
  13874. * @function
  13875. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13876. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13877. */
  13878. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13879. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13880. return vec4( color.rgb.div( color.a ), color.a );
  13881. }, { color: 'vec4', return: 'vec4' } );
  13882. // Deprecated
  13883. /**
  13884. * @tsl
  13885. * @function
  13886. * @deprecated since r171. Use {@link blendBurn} instead.
  13887. *
  13888. * @param {...any} params
  13889. * @returns {Function}
  13890. */
  13891. const burn = ( ...params ) => { // @deprecated, r171
  13892. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13893. return blendBurn( params );
  13894. };
  13895. /**
  13896. * @tsl
  13897. * @function
  13898. * @deprecated since r171. Use {@link blendDodge} instead.
  13899. *
  13900. * @param {...any} params
  13901. * @returns {Function}
  13902. */
  13903. const dodge = ( ...params ) => { // @deprecated, r171
  13904. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13905. return blendDodge( params );
  13906. };
  13907. /**
  13908. * @tsl
  13909. * @function
  13910. * @deprecated since r171. Use {@link blendScreen} instead.
  13911. *
  13912. * @param {...any} params
  13913. * @returns {Function}
  13914. */
  13915. const screen = ( ...params ) => { // @deprecated, r171
  13916. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13917. return blendScreen( params );
  13918. };
  13919. /**
  13920. * @tsl
  13921. * @function
  13922. * @deprecated since r171. Use {@link blendOverlay} instead.
  13923. *
  13924. * @param {...any} params
  13925. * @returns {Function}
  13926. */
  13927. const overlay = ( ...params ) => { // @deprecated, r171
  13928. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13929. return blendOverlay( params );
  13930. };
  13931. /**
  13932. * Base class for all node materials.
  13933. *
  13934. * @augments Material
  13935. */
  13936. class NodeMaterial extends Material {
  13937. static get type() {
  13938. return 'NodeMaterial';
  13939. }
  13940. /**
  13941. * Represents the type of the node material.
  13942. *
  13943. * @type {string}
  13944. */
  13945. get type() {
  13946. return this.constructor.type;
  13947. }
  13948. set type( _value ) { /* */ }
  13949. /**
  13950. * Constructs a new node material.
  13951. */
  13952. constructor() {
  13953. super();
  13954. /**
  13955. * This flag can be used for type testing.
  13956. *
  13957. * @type {boolean}
  13958. * @readonly
  13959. * @default true
  13960. */
  13961. this.isNodeMaterial = true;
  13962. /**
  13963. * Whether this material is affected by fog or not.
  13964. *
  13965. * @type {boolean}
  13966. * @default true
  13967. */
  13968. this.fog = true;
  13969. /**
  13970. * Whether this material is affected by lights or not.
  13971. *
  13972. * @type {boolean}
  13973. * @default false
  13974. */
  13975. this.lights = false;
  13976. /**
  13977. * Whether this material uses hardware clipping or not.
  13978. * This property is managed by the engine and should not be
  13979. * modified by apps.
  13980. *
  13981. * @type {boolean}
  13982. * @default false
  13983. */
  13984. this.hardwareClipping = false;
  13985. /**
  13986. * Node materials which set their `lights` property to `true`
  13987. * are affected by all lights of the scene. Sometimes selective
  13988. * lighting is wanted which means only _some_ lights in the scene
  13989. * affect a material. This can be achieved by creating an instance
  13990. * of {@link LightsNode} with a list of selective
  13991. * lights and assign the node to this property.
  13992. *
  13993. * ```js
  13994. * const customLightsNode = lights( [ light1, light2 ] );
  13995. * material.lightsNode = customLightsNode;
  13996. * ```
  13997. *
  13998. * @type {?LightsNode}
  13999. * @default null
  14000. */
  14001. this.lightsNode = null;
  14002. /**
  14003. * The environment of node materials can be defined by an environment
  14004. * map assigned to the `envMap` property or by `Scene.environment`
  14005. * if the node material is a PBR material. This node property allows to overwrite
  14006. * the default behavior and define the environment with a custom node.
  14007. *
  14008. * ```js
  14009. * material.envNode = pmremTexture( renderTarget.texture );
  14010. * ```
  14011. *
  14012. * @type {?Node<vec3>}
  14013. * @default null
  14014. */
  14015. this.envNode = null;
  14016. /**
  14017. * The lighting of node materials might be influenced by ambient occlusion.
  14018. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14019. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14020. * the default and define the ambient occlusion with a custom node instead.
  14021. *
  14022. * If you don't want to overwrite the diffuse color but modify the existing
  14023. * values instead, use {@link materialAO}.
  14024. *
  14025. * @type {?Node<float>}
  14026. * @default null
  14027. */
  14028. this.aoNode = null;
  14029. /**
  14030. * The diffuse color of node materials is by default inferred from the
  14031. * `color` and `map` properties. This node property allows to overwrite the default
  14032. * and define the diffuse color with a node instead.
  14033. *
  14034. * ```js
  14035. * material.colorNode = color( 0xff0000 ); // define red color
  14036. * ```
  14037. *
  14038. * If you don't want to overwrite the diffuse color but modify the existing
  14039. * values instead, use {@link materialColor}.
  14040. *
  14041. * ```js
  14042. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14043. * ```
  14044. *
  14045. * @type {?Node<vec3>}
  14046. * @default null
  14047. */
  14048. this.colorNode = null;
  14049. /**
  14050. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14051. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14052. * and define the normals with a node instead.
  14053. *
  14054. * If you don't want to overwrite the normals but modify the existing values instead,
  14055. * use {@link materialNormal}.
  14056. *
  14057. * @type {?Node<vec3>}
  14058. * @default null
  14059. */
  14060. this.normalNode = null;
  14061. /**
  14062. * The opacity of node materials is by default inferred from the `opacity`
  14063. * and `alphaMap` properties. This node property allows to overwrite the default
  14064. * and define the opacity with a node instead.
  14065. *
  14066. * If you don't want to overwrite the normals but modify the existing
  14067. * value instead, use {@link materialOpacity}.
  14068. *
  14069. * @type {?Node<float>}
  14070. * @default null
  14071. */
  14072. this.opacityNode = null;
  14073. /**
  14074. * This node can be used to implement a variety of filter-like effects. The idea is
  14075. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14076. * to create an arbitrary effect and then assign the node composition to this property.
  14077. * Everything behind the object using this material will now be affected by a filter.
  14078. *
  14079. * ```js
  14080. * const material = new NodeMaterial()
  14081. * material.transparent = true;
  14082. *
  14083. * // everything behind the object will be monochromatic
  14084. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14085. * ```
  14086. *
  14087. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14088. *
  14089. * @type {?Node<vec3>}
  14090. * @default null
  14091. */
  14092. this.backdropNode = null;
  14093. /**
  14094. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14095. *
  14096. * @type {?Node<float>}
  14097. * @default null
  14098. */
  14099. this.backdropAlphaNode = null;
  14100. /**
  14101. * The alpha test of node materials is by default inferred from the `alphaTest`
  14102. * property. This node property allows to overwrite the default and define the
  14103. * alpha test with a node instead.
  14104. *
  14105. * If you don't want to overwrite the alpha test but modify the existing
  14106. * value instead, use {@link materialAlphaTest}.
  14107. *
  14108. * @type {?Node<float>}
  14109. * @default null
  14110. */
  14111. this.alphaTestNode = null;
  14112. /**
  14113. * Discards the fragment if the mask value is `false`.
  14114. *
  14115. * @type {?Node<bool>}
  14116. * @default null
  14117. */
  14118. this.maskNode = null;
  14119. /**
  14120. * The local vertex positions are computed based on multiple factors like the
  14121. * attribute data, morphing or skinning. This node property allows to overwrite
  14122. * the default and define local vertex positions with nodes instead.
  14123. *
  14124. * If you don't want to overwrite the vertex positions but modify the existing
  14125. * values instead, use {@link positionLocal}.
  14126. *
  14127. *```js
  14128. * material.positionNode = positionLocal.add( displace );
  14129. * ```
  14130. *
  14131. * @type {?Node<vec3>}
  14132. * @default null
  14133. */
  14134. this.positionNode = null;
  14135. /**
  14136. * This node property is intended for logic which modifies geometry data once or per animation step.
  14137. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14138. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14139. * can be implemented.
  14140. *
  14141. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14142. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14143. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14144. * eventually assigned to `geometryNode`.
  14145. *
  14146. * @type {?Function}
  14147. * @default null
  14148. */
  14149. this.geometryNode = null;
  14150. /**
  14151. * Allows to overwrite depth values in the fragment shader.
  14152. *
  14153. * @type {?Node<float>}
  14154. * @default null
  14155. */
  14156. this.depthNode = null;
  14157. /**
  14158. * Allows to overwrite the position used for shadow map rendering which
  14159. * is by default {@link positionWorld}, the vertex position
  14160. * in world space.
  14161. *
  14162. * @type {?Node<float>}
  14163. * @default null
  14164. */
  14165. this.receivedShadowPositionNode = null;
  14166. /**
  14167. * Allows to overwrite the geometry position used for shadow map projection which
  14168. * is by default {@link positionLocal}, the vertex position in local space.
  14169. *
  14170. * @type {?Node<float>}
  14171. * @default null
  14172. */
  14173. this.castShadowPositionNode = null;
  14174. /**
  14175. * This node can be used to influence how an object using this node material
  14176. * receive shadows.
  14177. *
  14178. * ```js
  14179. * const totalShadows = float( 1 ).toVar();
  14180. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14181. * totalShadows.mulAssign( shadow );
  14182. * //return float( 1 ); // bypass received shadows
  14183. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14184. * } );
  14185. *
  14186. * @type {?(Function|FunctionNode<vec4>)}
  14187. * @default null
  14188. */
  14189. this.receivedShadowNode = null;
  14190. /**
  14191. * This node can be used to influence how an object using this node material
  14192. * casts shadows. To apply a color to shadows, you can simply do:
  14193. *
  14194. * ```js
  14195. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14196. * ```
  14197. *
  14198. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14199. * is also common to use the property with `Fn` function so checks are performed
  14200. * per fragment.
  14201. *
  14202. * ```js
  14203. * materialCustomShadow.castShadowNode = Fn( () => {
  14204. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14205. * return materialColor;
  14206. * } )();
  14207. * ```
  14208. *
  14209. * @type {?Node<vec4>}
  14210. * @default null
  14211. */
  14212. this.castShadowNode = null;
  14213. /**
  14214. * This node can be used to define the final output of the material.
  14215. *
  14216. * TODO: Explain the differences to `fragmentNode`.
  14217. *
  14218. * @type {?Node<vec4>}
  14219. * @default null
  14220. */
  14221. this.outputNode = null;
  14222. /**
  14223. * MRT configuration is done on renderer or pass level. This node allows to
  14224. * overwrite what values are written into MRT targets on material level. This
  14225. * can be useful for implementing selective FX features that should only affect
  14226. * specific objects.
  14227. *
  14228. * @type {?MRTNode}
  14229. * @default null
  14230. */
  14231. this.mrtNode = null;
  14232. /**
  14233. * This node property can be used if you need complete freedom in implementing
  14234. * the fragment shader. Assigning a node will replace the built-in material
  14235. * logic used in the fragment stage.
  14236. *
  14237. * @type {?Node<vec4>}
  14238. * @default null
  14239. */
  14240. this.fragmentNode = null;
  14241. /**
  14242. * This node property can be used if you need complete freedom in implementing
  14243. * the vertex shader. Assigning a node will replace the built-in material logic
  14244. * used in the vertex stage.
  14245. *
  14246. * @type {?Node<vec4>}
  14247. * @default null
  14248. */
  14249. this.vertexNode = null;
  14250. // Deprecated properties
  14251. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14252. get: () => {
  14253. return this.receivedShadowPositionNode;
  14254. },
  14255. set: ( value ) => {
  14256. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14257. this.receivedShadowPositionNode = value;
  14258. }
  14259. } );
  14260. }
  14261. /**
  14262. * Allows to define a custom cache key that influence the material key computation
  14263. * for render objects.
  14264. *
  14265. * @return {string} The custom cache key.
  14266. */
  14267. customProgramCacheKey() {
  14268. return this.type + getCacheKey$1( this );
  14269. }
  14270. /**
  14271. * Builds this material with the given node builder.
  14272. *
  14273. * @param {NodeBuilder} builder - The current node builder.
  14274. */
  14275. build( builder ) {
  14276. this.setup( builder );
  14277. }
  14278. /**
  14279. * Setups a node material observer with the given builder.
  14280. *
  14281. * @param {NodeBuilder} builder - The current node builder.
  14282. * @return {NodeMaterialObserver} The node material observer.
  14283. */
  14284. setupObserver( builder ) {
  14285. return new NodeMaterialObserver( builder );
  14286. }
  14287. /**
  14288. * Setups the vertex and fragment stage of this node material.
  14289. *
  14290. * @param {NodeBuilder} builder - The current node builder.
  14291. */
  14292. setup( builder ) {
  14293. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14294. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14295. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14296. const renderer = builder.renderer;
  14297. const renderTarget = renderer.getRenderTarget();
  14298. // < VERTEX STAGE >
  14299. builder.addStack();
  14300. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14301. const vertexNode = this.vertexNode || mvp;
  14302. builder.stack.outputNode = vertexNode;
  14303. this.setupHardwareClipping( builder );
  14304. if ( this.geometryNode !== null ) {
  14305. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14306. }
  14307. builder.addFlow( 'vertex', builder.removeStack() );
  14308. // < FRAGMENT STAGE >
  14309. builder.addStack();
  14310. let resultNode;
  14311. const clippingNode = this.setupClipping( builder );
  14312. if ( this.depthWrite === true || this.depthTest === true ) {
  14313. // only write depth if depth buffer is configured
  14314. if ( renderTarget !== null ) {
  14315. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14316. } else {
  14317. if ( renderer.depth === true ) this.setupDepth( builder );
  14318. }
  14319. }
  14320. if ( this.fragmentNode === null ) {
  14321. this.setupDiffuseColor( builder );
  14322. this.setupVariants( builder );
  14323. const outgoingLightNode = this.setupLighting( builder );
  14324. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14325. // force unsigned floats - useful for RenderTargets
  14326. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14327. resultNode = this.setupOutput( builder, basicOutput );
  14328. // OUTPUT NODE
  14329. output.assign( resultNode );
  14330. //
  14331. const isCustomOutput = this.outputNode !== null;
  14332. if ( isCustomOutput ) resultNode = this.outputNode;
  14333. // MRT
  14334. if ( renderTarget !== null ) {
  14335. const mrt = renderer.getMRT();
  14336. const materialMRT = this.mrtNode;
  14337. if ( mrt !== null ) {
  14338. if ( isCustomOutput ) output.assign( resultNode );
  14339. resultNode = mrt;
  14340. if ( materialMRT !== null ) {
  14341. resultNode = mrt.merge( materialMRT );
  14342. }
  14343. } else if ( materialMRT !== null ) {
  14344. resultNode = materialMRT;
  14345. }
  14346. }
  14347. } else {
  14348. let fragmentNode = this.fragmentNode;
  14349. if ( fragmentNode.isOutputStructNode !== true ) {
  14350. fragmentNode = vec4( fragmentNode );
  14351. }
  14352. resultNode = this.setupOutput( builder, fragmentNode );
  14353. }
  14354. builder.stack.outputNode = resultNode;
  14355. builder.addFlow( 'fragment', builder.removeStack() );
  14356. // < OBSERVER >
  14357. builder.observer = this.setupObserver( builder );
  14358. }
  14359. /**
  14360. * Setups the clipping node.
  14361. *
  14362. * @param {NodeBuilder} builder - The current node builder.
  14363. * @return {ClippingNode} The clipping node.
  14364. */
  14365. setupClipping( builder ) {
  14366. if ( builder.clippingContext === null ) return null;
  14367. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14368. let result = null;
  14369. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14370. const samples = builder.renderer.currentSamples;
  14371. if ( this.alphaToCoverage && samples > 1 ) {
  14372. // to be added to flow when the color/alpha value has been determined
  14373. result = clippingAlpha();
  14374. } else {
  14375. builder.stack.addToStack( clipping() );
  14376. }
  14377. }
  14378. return result;
  14379. }
  14380. /**
  14381. * Setups the hardware clipping if available on the current device.
  14382. *
  14383. * @param {NodeBuilder} builder - The current node builder.
  14384. */
  14385. setupHardwareClipping( builder ) {
  14386. this.hardwareClipping = false;
  14387. if ( builder.clippingContext === null ) return;
  14388. const candidateCount = builder.clippingContext.unionPlanes.length;
  14389. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14390. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14391. builder.stack.addToStack( hardwareClipping() );
  14392. this.hardwareClipping = true;
  14393. }
  14394. return;
  14395. }
  14396. /**
  14397. * Setups the depth of this material.
  14398. *
  14399. * @param {NodeBuilder} builder - The current node builder.
  14400. */
  14401. setupDepth( builder ) {
  14402. const { renderer, camera } = builder;
  14403. // Depth
  14404. let depthNode = this.depthNode;
  14405. if ( depthNode === null ) {
  14406. const mrt = renderer.getMRT();
  14407. if ( mrt && mrt.has( 'depth' ) ) {
  14408. depthNode = mrt.get( 'depth' );
  14409. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14410. if ( camera.isPerspectiveCamera ) {
  14411. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14412. } else {
  14413. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14414. }
  14415. }
  14416. }
  14417. if ( depthNode !== null ) {
  14418. depth.assign( depthNode ).toStack();
  14419. }
  14420. }
  14421. /**
  14422. * Setups the position node in view space. This method exists
  14423. * so derived node materials can modify the implementation e.g. sprite materials.
  14424. *
  14425. * @param {NodeBuilder} builder - The current node builder.
  14426. * @return {Node<vec3>} The position in view space.
  14427. */
  14428. setupPositionView( /*builder*/ ) {
  14429. return modelViewMatrix.mul( positionLocal ).xyz;
  14430. }
  14431. /**
  14432. * Setups the position in clip space.
  14433. *
  14434. * @param {NodeBuilder} builder - The current node builder.
  14435. * @return {Node<vec4>} The position in view space.
  14436. */
  14437. setupModelViewProjection( /*builder*/ ) {
  14438. return cameraProjectionMatrix.mul( positionView );
  14439. }
  14440. /**
  14441. * Setups the logic for the vertex stage.
  14442. *
  14443. * @param {NodeBuilder} builder - The current node builder.
  14444. * @return {Node<vec4>} The position in clip space.
  14445. */
  14446. setupVertex( builder ) {
  14447. builder.addStack();
  14448. this.setupPosition( builder );
  14449. builder.context.vertex = builder.removeStack();
  14450. return modelViewProjection;
  14451. }
  14452. /**
  14453. * Setups the computation of the position in local space.
  14454. *
  14455. * @param {NodeBuilder} builder - The current node builder.
  14456. * @return {Node<vec3>} The position in local space.
  14457. */
  14458. setupPosition( builder ) {
  14459. const { object, geometry } = builder;
  14460. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14461. morphReference( object ).toStack();
  14462. }
  14463. if ( object.isSkinnedMesh === true ) {
  14464. skinning( object ).toStack();
  14465. }
  14466. if ( this.displacementMap ) {
  14467. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14468. const displacementScale = materialReference( 'displacementScale', 'float' );
  14469. const displacementBias = materialReference( 'displacementBias', 'float' );
  14470. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14471. }
  14472. if ( object.isBatchedMesh ) {
  14473. batch( object ).toStack();
  14474. }
  14475. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14476. instancedMesh( object ).toStack();
  14477. }
  14478. if ( this.positionNode !== null ) {
  14479. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14480. }
  14481. return positionLocal;
  14482. }
  14483. /**
  14484. * Setups the computation of the material's diffuse color.
  14485. *
  14486. * @param {NodeBuilder} builder - The current node builder.
  14487. * @param {BufferGeometry} geometry - The geometry.
  14488. */
  14489. setupDiffuseColor( { object, geometry } ) {
  14490. // MASK
  14491. if ( this.maskNode !== null ) {
  14492. // Discard if the mask is `false`
  14493. bool( this.maskNode ).not().discard();
  14494. }
  14495. // COLOR
  14496. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14497. // VERTEX COLORS
  14498. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14499. colorNode = colorNode.mul( vertexColor() );
  14500. }
  14501. // INSTANCED COLORS
  14502. if ( object.instanceColor ) {
  14503. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14504. colorNode = instanceColor.mul( colorNode );
  14505. }
  14506. if ( object.isBatchedMesh && object._colorsTexture ) {
  14507. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14508. colorNode = batchColor.mul( colorNode );
  14509. }
  14510. // DIFFUSE COLOR
  14511. diffuseColor.assign( colorNode );
  14512. // OPACITY
  14513. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14514. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14515. // ALPHA TEST
  14516. let alphaTestNode = null;
  14517. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14518. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14519. if ( this.alphaToCoverage === true ) {
  14520. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14521. diffuseColor.a.lessThanEqual( 0 ).discard();
  14522. } else {
  14523. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14524. }
  14525. }
  14526. // ALPHA HASH
  14527. if ( this.alphaHash === true ) {
  14528. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14529. }
  14530. // OPAQUE
  14531. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14532. if ( isOpaque ) {
  14533. diffuseColor.a.assign( 1.0 );
  14534. }
  14535. }
  14536. /**
  14537. * Abstract interface method that can be implemented by derived materials
  14538. * to setup material-specific node variables.
  14539. *
  14540. * @abstract
  14541. * @param {NodeBuilder} builder - The current node builder.
  14542. */
  14543. setupVariants( /*builder*/ ) {
  14544. // Interface function.
  14545. }
  14546. /**
  14547. * Setups the outgoing light node variable
  14548. *
  14549. * @return {Node<vec3>} The outgoing light node.
  14550. */
  14551. setupOutgoingLight() {
  14552. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14553. }
  14554. /**
  14555. * Setups the normal node from the material.
  14556. *
  14557. * @return {Node<vec3>} The normal node.
  14558. */
  14559. setupNormal() {
  14560. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14561. }
  14562. /**
  14563. * Setups the environment node from the material.
  14564. *
  14565. * @param {NodeBuilder} builder - The current node builder.
  14566. * @return {Node<vec4>} The environment node.
  14567. */
  14568. setupEnvironment( /*builder*/ ) {
  14569. let node = null;
  14570. if ( this.envNode ) {
  14571. node = this.envNode;
  14572. } else if ( this.envMap ) {
  14573. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14574. }
  14575. return node;
  14576. }
  14577. /**
  14578. * Setups the light map node from the material.
  14579. *
  14580. * @param {NodeBuilder} builder - The current node builder.
  14581. * @return {Node<vec3>} The light map node.
  14582. */
  14583. setupLightMap( builder ) {
  14584. let node = null;
  14585. if ( builder.material.lightMap ) {
  14586. node = new IrradianceNode( materialLightMap );
  14587. }
  14588. return node;
  14589. }
  14590. /**
  14591. * Setups the lights node based on the scene, environment and material.
  14592. *
  14593. * @param {NodeBuilder} builder - The current node builder.
  14594. * @return {LightsNode} The lights node.
  14595. */
  14596. setupLights( builder ) {
  14597. const materialLightsNode = [];
  14598. //
  14599. const envNode = this.setupEnvironment( builder );
  14600. if ( envNode && envNode.isLightingNode ) {
  14601. materialLightsNode.push( envNode );
  14602. }
  14603. const lightMapNode = this.setupLightMap( builder );
  14604. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14605. materialLightsNode.push( lightMapNode );
  14606. }
  14607. if ( this.aoNode !== null || builder.material.aoMap ) {
  14608. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14609. materialLightsNode.push( new AONode( aoNode ) );
  14610. }
  14611. let lightsN = this.lightsNode || builder.lightsNode;
  14612. if ( materialLightsNode.length > 0 ) {
  14613. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14614. }
  14615. return lightsN;
  14616. }
  14617. /**
  14618. * This method should be implemented by most derived materials
  14619. * since it defines the material's lighting model.
  14620. *
  14621. * @abstract
  14622. * @param {NodeBuilder} builder - The current node builder.
  14623. * @return {LightingModel} The lighting model.
  14624. */
  14625. setupLightingModel( /*builder*/ ) {
  14626. // Interface function.
  14627. }
  14628. /**
  14629. * Setups the outgoing light node.
  14630. *
  14631. * @param {NodeBuilder} builder - The current node builder.
  14632. * @return {Node<vec3>} The outgoing light node.
  14633. */
  14634. setupLighting( builder ) {
  14635. const { material } = builder;
  14636. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14637. // OUTGOING LIGHT
  14638. const lights = this.lights === true || this.lightsNode !== null;
  14639. const lightsNode = lights ? this.setupLights( builder ) : null;
  14640. let outgoingLightNode = this.setupOutgoingLight( builder );
  14641. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14642. const lightingModel = this.setupLightingModel( builder ) || null;
  14643. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14644. } else if ( backdropNode !== null ) {
  14645. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14646. }
  14647. // EMISSIVE
  14648. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14649. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14650. outgoingLightNode = outgoingLightNode.add( emissive );
  14651. }
  14652. return outgoingLightNode;
  14653. }
  14654. /**
  14655. * Setup the fog.
  14656. *
  14657. * @param {NodeBuilder} builder - The current node builder.
  14658. * @param {Node<vec4>} outputNode - The existing output node.
  14659. * @return {Node<vec4>} The output node.
  14660. */
  14661. setupFog( builder, outputNode ) {
  14662. const fogNode = builder.fogNode;
  14663. if ( fogNode ) {
  14664. output.assign( outputNode );
  14665. outputNode = vec4( fogNode.toVar() );
  14666. }
  14667. return outputNode;
  14668. }
  14669. /**
  14670. * Setups premultiplied alpha.
  14671. *
  14672. * @param {NodeBuilder} builder - The current node builder.
  14673. * @param {Node<vec4>} outputNode - The existing output node.
  14674. * @return {Node<vec4>} The output node.
  14675. */
  14676. setupPremultipliedAlpha( builder, outputNode ) {
  14677. return premultiplyAlpha( outputNode );
  14678. }
  14679. /**
  14680. * Setups the output node.
  14681. *
  14682. * @param {NodeBuilder} builder - The current node builder.
  14683. * @param {Node<vec4>} outputNode - The existing output node.
  14684. * @return {Node<vec4>} The output node.
  14685. */
  14686. setupOutput( builder, outputNode ) {
  14687. // FOG
  14688. if ( this.fog === true ) {
  14689. outputNode = this.setupFog( builder, outputNode );
  14690. }
  14691. // PREMULTIPLIED ALPHA
  14692. if ( this.premultipliedAlpha === true ) {
  14693. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14694. }
  14695. return outputNode;
  14696. }
  14697. /**
  14698. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14699. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14700. * defining all material properties of the classic type in the node type.
  14701. *
  14702. * @param {Material} material - The material to copy properties with their values to this node material.
  14703. */
  14704. setDefaultValues( material ) {
  14705. // This approach is to reuse the native refreshUniforms*
  14706. // and turn available the use of features like transmission and environment in core
  14707. for ( const property in material ) {
  14708. const value = material[ property ];
  14709. if ( this[ property ] === undefined ) {
  14710. this[ property ] = value;
  14711. if ( value && value.clone ) this[ property ] = value.clone();
  14712. }
  14713. }
  14714. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14715. for ( const key in descriptors ) {
  14716. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14717. descriptors[ key ].get !== undefined ) {
  14718. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14719. }
  14720. }
  14721. }
  14722. /**
  14723. * Serializes this material to JSON.
  14724. *
  14725. * @param {?(Object|string)} meta - The meta information for serialization.
  14726. * @return {Object} The serialized node.
  14727. */
  14728. toJSON( meta ) {
  14729. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14730. if ( isRoot ) {
  14731. meta = {
  14732. textures: {},
  14733. images: {},
  14734. nodes: {}
  14735. };
  14736. }
  14737. const data = Material.prototype.toJSON.call( this, meta );
  14738. const nodeChildren = getNodeChildren( this );
  14739. data.inputNodes = {};
  14740. for ( const { property, childNode } of nodeChildren ) {
  14741. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14742. }
  14743. // TODO: Copied from Object3D.toJSON
  14744. function extractFromCache( cache ) {
  14745. const values = [];
  14746. for ( const key in cache ) {
  14747. const data = cache[ key ];
  14748. delete data.metadata;
  14749. values.push( data );
  14750. }
  14751. return values;
  14752. }
  14753. if ( isRoot ) {
  14754. const textures = extractFromCache( meta.textures );
  14755. const images = extractFromCache( meta.images );
  14756. const nodes = extractFromCache( meta.nodes );
  14757. if ( textures.length > 0 ) data.textures = textures;
  14758. if ( images.length > 0 ) data.images = images;
  14759. if ( nodes.length > 0 ) data.nodes = nodes;
  14760. }
  14761. return data;
  14762. }
  14763. /**
  14764. * Copies the properties of the given node material to this instance.
  14765. *
  14766. * @param {NodeMaterial} source - The material to copy.
  14767. * @return {NodeMaterial} A reference to this node material.
  14768. */
  14769. copy( source ) {
  14770. this.lightsNode = source.lightsNode;
  14771. this.envNode = source.envNode;
  14772. this.colorNode = source.colorNode;
  14773. this.normalNode = source.normalNode;
  14774. this.opacityNode = source.opacityNode;
  14775. this.backdropNode = source.backdropNode;
  14776. this.backdropAlphaNode = source.backdropAlphaNode;
  14777. this.alphaTestNode = source.alphaTestNode;
  14778. this.maskNode = source.maskNode;
  14779. this.positionNode = source.positionNode;
  14780. this.geometryNode = source.geometryNode;
  14781. this.depthNode = source.depthNode;
  14782. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14783. this.castShadowPositionNode = source.castShadowPositionNode;
  14784. this.receivedShadowNode = source.receivedShadowNode;
  14785. this.castShadowNode = source.castShadowNode;
  14786. this.outputNode = source.outputNode;
  14787. this.mrtNode = source.mrtNode;
  14788. this.fragmentNode = source.fragmentNode;
  14789. this.vertexNode = source.vertexNode;
  14790. return super.copy( source );
  14791. }
  14792. }
  14793. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14794. /**
  14795. * Node material version of {@link LineBasicMaterial}.
  14796. *
  14797. * @augments NodeMaterial
  14798. */
  14799. class LineBasicNodeMaterial extends NodeMaterial {
  14800. static get type() {
  14801. return 'LineBasicNodeMaterial';
  14802. }
  14803. /**
  14804. * Constructs a new line basic node material.
  14805. *
  14806. * @param {Object} [parameters] - The configuration parameter.
  14807. */
  14808. constructor( parameters ) {
  14809. super();
  14810. /**
  14811. * This flag can be used for type testing.
  14812. *
  14813. * @type {boolean}
  14814. * @readonly
  14815. * @default true
  14816. */
  14817. this.isLineBasicNodeMaterial = true;
  14818. this.setDefaultValues( _defaultValues$d );
  14819. this.setValues( parameters );
  14820. }
  14821. }
  14822. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14823. /**
  14824. * Node material version of {@link LineDashedMaterial}.
  14825. *
  14826. * @augments NodeMaterial
  14827. */
  14828. class LineDashedNodeMaterial extends NodeMaterial {
  14829. static get type() {
  14830. return 'LineDashedNodeMaterial';
  14831. }
  14832. /**
  14833. * Constructs a new line dashed 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.isLineDashedNodeMaterial = true;
  14847. this.setDefaultValues( _defaultValues$c );
  14848. /**
  14849. * The dash offset.
  14850. *
  14851. * @type {number}
  14852. * @default 0
  14853. */
  14854. this.dashOffset = 0;
  14855. /**
  14856. * The offset of dash materials is by default inferred from the `dashOffset`
  14857. * property. This node property allows to overwrite the default
  14858. * and define the offset with a node instead.
  14859. *
  14860. * If you don't want to overwrite the offset but modify the existing
  14861. * value instead, use {@link materialLineDashOffset}.
  14862. *
  14863. * @type {?Node<float>}
  14864. * @default null
  14865. */
  14866. this.offsetNode = null;
  14867. /**
  14868. * The scale of dash materials is by default inferred from the `scale`
  14869. * property. This node property allows to overwrite the default
  14870. * and define the scale with a node instead.
  14871. *
  14872. * If you don't want to overwrite the scale but modify the existing
  14873. * value instead, use {@link materialLineScale}.
  14874. *
  14875. * @type {?Node<float>}
  14876. * @default null
  14877. */
  14878. this.dashScaleNode = null;
  14879. /**
  14880. * The dash size of dash materials is by default inferred from the `dashSize`
  14881. * property. This node property allows to overwrite the default
  14882. * and define the dash size with a node instead.
  14883. *
  14884. * If you don't want to overwrite the dash size but modify the existing
  14885. * value instead, use {@link materialLineDashSize}.
  14886. *
  14887. * @type {?Node<float>}
  14888. * @default null
  14889. */
  14890. this.dashSizeNode = null;
  14891. /**
  14892. * The gap size of dash materials is by default inferred from the `gapSize`
  14893. * property. This node property allows to overwrite the default
  14894. * and define the gap size with a node instead.
  14895. *
  14896. * If you don't want to overwrite the gap size but modify the existing
  14897. * value instead, use {@link materialLineGapSize}.
  14898. *
  14899. * @type {?Node<float>}
  14900. * @default null
  14901. */
  14902. this.gapSizeNode = null;
  14903. this.setValues( parameters );
  14904. }
  14905. /**
  14906. * Setups the dash specific node variables.
  14907. *
  14908. * @param {NodeBuilder} builder - The current node builder.
  14909. */
  14910. setupVariants( /* builder */ ) {
  14911. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14912. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14913. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14914. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14915. dashSize.assign( dashSizeNode );
  14916. gapSize.assign( gapSizeNode );
  14917. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14918. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14919. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14920. }
  14921. }
  14922. let _sharedFramebuffer = null;
  14923. /**
  14924. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14925. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14926. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14927. *
  14928. * @augments ViewportTextureNode
  14929. */
  14930. class ViewportSharedTextureNode extends ViewportTextureNode {
  14931. static get type() {
  14932. return 'ViewportSharedTextureNode';
  14933. }
  14934. /**
  14935. * Constructs a new viewport shared texture node.
  14936. *
  14937. * @param {Node} [uvNode=screenUV] - The uv node.
  14938. * @param {?Node} [levelNode=null] - The level node.
  14939. */
  14940. constructor( uvNode = screenUV, levelNode = null ) {
  14941. if ( _sharedFramebuffer === null ) {
  14942. _sharedFramebuffer = new FramebufferTexture();
  14943. }
  14944. super( uvNode, levelNode, _sharedFramebuffer );
  14945. }
  14946. /**
  14947. * Overwritten so the method always returns the unique shared
  14948. * framebuffer texture.
  14949. *
  14950. * @return {FramebufferTexture} The shared framebuffer texture.
  14951. */
  14952. getTextureForReference() {
  14953. return _sharedFramebuffer;
  14954. }
  14955. updateReference() {
  14956. return this;
  14957. }
  14958. }
  14959. /**
  14960. * TSL function for creating a shared viewport texture node.
  14961. *
  14962. * @tsl
  14963. * @function
  14964. * @param {?Node} [uvNode=screenUV] - The uv node.
  14965. * @param {?Node} [levelNode=null] - The level node.
  14966. * @returns {ViewportSharedTextureNode}
  14967. */
  14968. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14969. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14970. /**
  14971. * This node material can be used to render lines with a size larger than one
  14972. * by representing them as instanced meshes.
  14973. *
  14974. * @augments NodeMaterial
  14975. */
  14976. class Line2NodeMaterial extends NodeMaterial {
  14977. static get type() {
  14978. return 'Line2NodeMaterial';
  14979. }
  14980. /**
  14981. * Constructs a new node material for wide line rendering.
  14982. *
  14983. * @param {Object} [parameters={}] - The configuration parameter.
  14984. */
  14985. constructor( parameters = {} ) {
  14986. super();
  14987. /**
  14988. * This flag can be used for type testing.
  14989. *
  14990. * @type {boolean}
  14991. * @readonly
  14992. * @default true
  14993. */
  14994. this.isLine2NodeMaterial = true;
  14995. this.setDefaultValues( _defaultValues$b );
  14996. /**
  14997. * Whether vertex colors should be used or not.
  14998. *
  14999. * @type {boolean}
  15000. * @default false
  15001. */
  15002. this.useColor = parameters.vertexColors;
  15003. /**
  15004. * The dash offset.
  15005. *
  15006. * @type {number}
  15007. * @default 0
  15008. */
  15009. this.dashOffset = 0;
  15010. /**
  15011. * Defines the lines color.
  15012. *
  15013. * @type {?Node<vec3>}
  15014. * @default null
  15015. */
  15016. this.lineColorNode = null;
  15017. /**
  15018. * Defines the offset.
  15019. *
  15020. * @type {?Node<float>}
  15021. * @default null
  15022. */
  15023. this.offsetNode = null;
  15024. /**
  15025. * Defines the dash scale.
  15026. *
  15027. * @type {?Node<float>}
  15028. * @default null
  15029. */
  15030. this.dashScaleNode = null;
  15031. /**
  15032. * Defines the dash size.
  15033. *
  15034. * @type {?Node<float>}
  15035. * @default null
  15036. */
  15037. this.dashSizeNode = null;
  15038. /**
  15039. * Defines the gap size.
  15040. *
  15041. * @type {?Node<float>}
  15042. * @default null
  15043. */
  15044. this.gapSizeNode = null;
  15045. /**
  15046. * Blending is set to `NoBlending` since transparency
  15047. * is not supported, yet.
  15048. *
  15049. * @type {number}
  15050. * @default 0
  15051. */
  15052. this.blending = NoBlending;
  15053. this._useDash = parameters.dashed;
  15054. this._useAlphaToCoverage = true;
  15055. this._useWorldUnits = false;
  15056. this.setValues( parameters );
  15057. }
  15058. /**
  15059. * Setups the vertex and fragment stage of this node material.
  15060. *
  15061. * @param {NodeBuilder} builder - The current node builder.
  15062. */
  15063. setup( builder ) {
  15064. const { renderer } = builder;
  15065. const useAlphaToCoverage = this._useAlphaToCoverage;
  15066. const useColor = this.useColor;
  15067. const useDash = this._useDash;
  15068. const useWorldUnits = this._useWorldUnits;
  15069. const trimSegment = Fn( ( { start, end } ) => {
  15070. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15071. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15072. const nearEstimate = b.mul( -0.5 ).div( a );
  15073. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15074. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15075. } ).setLayout( {
  15076. name: 'trimSegment',
  15077. type: 'vec4',
  15078. inputs: [
  15079. { name: 'start', type: 'vec4' },
  15080. { name: 'end', type: 'vec4' }
  15081. ]
  15082. } );
  15083. this.vertexNode = Fn( () => {
  15084. const instanceStart = attribute( 'instanceStart' );
  15085. const instanceEnd = attribute( 'instanceEnd' );
  15086. // camera space
  15087. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15088. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15089. if ( useDash ) {
  15090. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15091. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15092. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15093. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15094. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15095. lineDistance = lineDistance.add( offsetNode );
  15096. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15097. }
  15098. if ( useWorldUnits ) {
  15099. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15100. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15101. }
  15102. const aspect = viewport.z.div( viewport.w );
  15103. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15104. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15105. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15106. // perhaps there is a more elegant solution -- WestLangley
  15107. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15108. If( perspective, () => {
  15109. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15110. end.assign( trimSegment( { start: start, end: end } ) );
  15111. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15112. start.assign( trimSegment( { start: end, end: start } ) );
  15113. } );
  15114. } );
  15115. // clip space
  15116. const clipStart = cameraProjectionMatrix.mul( start );
  15117. const clipEnd = cameraProjectionMatrix.mul( end );
  15118. // ndc space
  15119. const ndcStart = clipStart.xyz.div( clipStart.w );
  15120. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15121. // direction
  15122. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15123. // account for clip-space aspect ratio
  15124. dir.x.assign( dir.x.mul( aspect ) );
  15125. dir.assign( dir.normalize() );
  15126. const clip = vec4().toVar();
  15127. if ( useWorldUnits ) {
  15128. // get the offset direction as perpendicular to the view vector
  15129. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15130. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15131. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15132. const worldFwd = worldDir.cross( worldUp );
  15133. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15134. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15135. // height offset
  15136. const hw = materialLineWidth.mul( 0.5 );
  15137. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15138. // don't extend the line if we're rendering dashes because we
  15139. // won't be rendering the endcaps
  15140. if ( ! useDash ) {
  15141. // cap extension
  15142. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15143. // add width to the box
  15144. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15145. // endcaps
  15146. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15147. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15148. } );
  15149. }
  15150. // project the worldpos
  15151. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15152. // shift the depth of the projected points so the line
  15153. // segments overlap neatly
  15154. const clipPose = vec3().toVar();
  15155. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15156. clip.z.assign( clipPose.z.mul( clip.w ) );
  15157. } else {
  15158. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15159. // undo aspect ratio adjustment
  15160. dir.x.assign( dir.x.div( aspect ) );
  15161. offset.x.assign( offset.x.div( aspect ) );
  15162. // sign flip
  15163. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15164. // endcaps
  15165. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15166. offset.assign( offset.sub( dir ) );
  15167. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15168. offset.assign( offset.add( dir ) );
  15169. } );
  15170. // adjust for linewidth
  15171. offset.assign( offset.mul( materialLineWidth ) );
  15172. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15173. offset.assign( offset.div( viewport.w ) );
  15174. // select end
  15175. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15176. // back to clip space
  15177. offset.assign( offset.mul( clip.w ) );
  15178. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15179. }
  15180. return clip;
  15181. } )();
  15182. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15183. const p13 = p1.sub( p3 );
  15184. const p43 = p4.sub( p3 );
  15185. const p21 = p2.sub( p1 );
  15186. const d1343 = p13.dot( p43 );
  15187. const d4321 = p43.dot( p21 );
  15188. const d1321 = p13.dot( p21 );
  15189. const d4343 = p43.dot( p43 );
  15190. const d2121 = p21.dot( p21 );
  15191. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15192. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15193. const mua = numer.div( denom ).clamp();
  15194. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15195. return vec2( mua, mub );
  15196. } );
  15197. this.colorNode = Fn( () => {
  15198. const vUv = uv$1();
  15199. if ( useDash ) {
  15200. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15201. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15202. dashSize.assign( dashSizeNode );
  15203. gapSize.assign( gapSizeNode );
  15204. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15205. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15206. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15207. }
  15208. const alpha = float( 1 ).toVar( 'alpha' );
  15209. if ( useWorldUnits ) {
  15210. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15211. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15212. // Find the closest points on the view ray and the line segment
  15213. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15214. const lineDir = worldEnd.sub( worldStart );
  15215. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15216. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15217. const p2 = rayEnd.mul( params.y );
  15218. const delta = p1.sub( p2 );
  15219. const len = delta.length();
  15220. const norm = len.div( materialLineWidth );
  15221. if ( ! useDash ) {
  15222. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15223. const dnorm = norm.fwidth();
  15224. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15225. } else {
  15226. norm.greaterThan( 0.5 ).discard();
  15227. }
  15228. }
  15229. } else {
  15230. // round endcaps
  15231. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15232. const a = vUv.x;
  15233. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15234. const len2 = a.mul( a ).add( b.mul( b ) );
  15235. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15236. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15237. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15238. } );
  15239. } else {
  15240. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15241. const a = vUv.x;
  15242. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15243. const len2 = a.mul( a ).add( b.mul( b ) );
  15244. len2.greaterThan( 1.0 ).discard();
  15245. } );
  15246. }
  15247. }
  15248. let lineColorNode;
  15249. if ( this.lineColorNode ) {
  15250. lineColorNode = this.lineColorNode;
  15251. } else {
  15252. if ( useColor ) {
  15253. const instanceColorStart = attribute( 'instanceColorStart' );
  15254. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15255. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15256. lineColorNode = instanceColor.mul( materialColor );
  15257. } else {
  15258. lineColorNode = materialColor;
  15259. }
  15260. }
  15261. return vec4( lineColorNode, alpha );
  15262. } )();
  15263. if ( this.transparent ) {
  15264. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15265. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15266. }
  15267. super.setup( builder );
  15268. }
  15269. /**
  15270. * Whether the lines should sized in world units or not.
  15271. * When set to `false` the unit is pixel.
  15272. *
  15273. * @type {boolean}
  15274. * @default false
  15275. */
  15276. get worldUnits() {
  15277. return this._useWorldUnits;
  15278. }
  15279. set worldUnits( value ) {
  15280. if ( this._useWorldUnits !== value ) {
  15281. this._useWorldUnits = value;
  15282. this.needsUpdate = true;
  15283. }
  15284. }
  15285. /**
  15286. * Whether the lines should be dashed or not.
  15287. *
  15288. * @type {boolean}
  15289. * @default false
  15290. */
  15291. get dashed() {
  15292. return this._useDash;
  15293. }
  15294. set dashed( value ) {
  15295. if ( this._useDash !== value ) {
  15296. this._useDash = value;
  15297. this.needsUpdate = true;
  15298. }
  15299. }
  15300. /**
  15301. * Whether alpha to coverage should be used or not.
  15302. *
  15303. * @type {boolean}
  15304. * @default true
  15305. */
  15306. get alphaToCoverage() {
  15307. return this._useAlphaToCoverage;
  15308. }
  15309. set alphaToCoverage( value ) {
  15310. if ( this._useAlphaToCoverage !== value ) {
  15311. this._useAlphaToCoverage = value;
  15312. this.needsUpdate = true;
  15313. }
  15314. }
  15315. }
  15316. /**
  15317. * Packs a direction vector into a color value.
  15318. *
  15319. * @tsl
  15320. * @function
  15321. * @param {Node<vec3>} node - The direction to pack.
  15322. * @return {Node<vec3>} The color.
  15323. */
  15324. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  15325. /**
  15326. * Unpacks a color value into a direction vector.
  15327. *
  15328. * @tsl
  15329. * @function
  15330. * @param {Node<vec3>} node - The color to unpack.
  15331. * @return {Node<vec3>} The direction.
  15332. */
  15333. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  15334. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15335. /**
  15336. * Node material version of {@link MeshNormalMaterial}.
  15337. *
  15338. * @augments NodeMaterial
  15339. */
  15340. class MeshNormalNodeMaterial extends NodeMaterial {
  15341. static get type() {
  15342. return 'MeshNormalNodeMaterial';
  15343. }
  15344. /**
  15345. * Constructs a new mesh normal node material.
  15346. *
  15347. * @param {Object} [parameters] - The configuration parameter.
  15348. */
  15349. constructor( parameters ) {
  15350. super();
  15351. /**
  15352. * This flag can be used for type testing.
  15353. *
  15354. * @type {boolean}
  15355. * @readonly
  15356. * @default true
  15357. */
  15358. this.isMeshNormalNodeMaterial = true;
  15359. this.setDefaultValues( _defaultValues$a );
  15360. this.setValues( parameters );
  15361. }
  15362. /**
  15363. * Overwrites the default implementation by computing the diffuse color
  15364. * based on the normal data.
  15365. */
  15366. setupDiffuseColor() {
  15367. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15368. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15369. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15370. }
  15371. }
  15372. /**
  15373. * TSL function for creating an equirect uv node.
  15374. *
  15375. * Can be used to compute texture coordinates for projecting an
  15376. * equirectangular texture onto a mesh for using it as the scene's
  15377. * background.
  15378. *
  15379. * ```js
  15380. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15381. * ```
  15382. *
  15383. * @tsl
  15384. * @function
  15385. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15386. * @returns {Node<vec2>}
  15387. */
  15388. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15389. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15390. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15391. return vec2( u, v );
  15392. } );
  15393. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15394. /**
  15395. * This class represents a cube render target. It is a special version
  15396. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15397. *
  15398. * @augments WebGLCubeRenderTarget
  15399. */
  15400. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15401. /**
  15402. * Constructs a new cube render target.
  15403. *
  15404. * @param {number} [size=1] - The size of the render target.
  15405. * @param {RenderTarget~Options} [options] - The configuration object.
  15406. */
  15407. constructor( size = 1, options = {} ) {
  15408. super( size, options );
  15409. /**
  15410. * This flag can be used for type testing.
  15411. *
  15412. * @type {boolean}
  15413. * @readonly
  15414. * @default true
  15415. */
  15416. this.isCubeRenderTarget = true;
  15417. }
  15418. /**
  15419. * Converts the given equirectangular texture to a cube map.
  15420. *
  15421. * @param {Renderer} renderer - The renderer.
  15422. * @param {Texture} texture - The equirectangular texture.
  15423. * @return {CubeRenderTarget} A reference to this cube render target.
  15424. */
  15425. fromEquirectangularTexture( renderer, texture$1 ) {
  15426. const currentMinFilter = texture$1.minFilter;
  15427. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15428. texture$1.generateMipmaps = true;
  15429. this.texture.type = texture$1.type;
  15430. this.texture.colorSpace = texture$1.colorSpace;
  15431. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15432. this.texture.minFilter = texture$1.minFilter;
  15433. this.texture.magFilter = texture$1.magFilter;
  15434. const geometry = new BoxGeometry( 5, 5, 5 );
  15435. const uvNode = equirectUV( positionWorldDirection );
  15436. const material = new NodeMaterial();
  15437. material.colorNode = texture( texture$1, uvNode, 0 );
  15438. material.side = BackSide;
  15439. material.blending = NoBlending;
  15440. const mesh = new Mesh( geometry, material );
  15441. const scene = new Scene();
  15442. scene.add( mesh );
  15443. // Avoid blurred poles
  15444. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15445. const camera = new CubeCamera( 1, 10, this );
  15446. const currentMRT = renderer.getMRT();
  15447. renderer.setMRT( null );
  15448. camera.update( renderer, scene );
  15449. renderer.setMRT( currentMRT );
  15450. texture$1.minFilter = currentMinFilter;
  15451. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15452. mesh.geometry.dispose();
  15453. mesh.material.dispose();
  15454. return this;
  15455. }
  15456. }
  15457. const _cache$1 = new WeakMap();
  15458. /**
  15459. * This node can be used to automatically convert environment maps in the
  15460. * equirectangular format into the cube map format.
  15461. *
  15462. * @augments TempNode
  15463. */
  15464. class CubeMapNode extends TempNode {
  15465. static get type() {
  15466. return 'CubeMapNode';
  15467. }
  15468. /**
  15469. * Constructs a new cube map node.
  15470. *
  15471. * @param {Node} envNode - The node representing the environment map.
  15472. */
  15473. constructor( envNode ) {
  15474. super( 'vec3' );
  15475. /**
  15476. * The node representing the environment map.
  15477. *
  15478. * @type {Node}
  15479. */
  15480. this.envNode = envNode;
  15481. /**
  15482. * A reference to the internal cube texture.
  15483. *
  15484. * @private
  15485. * @type {?CubeTexture}
  15486. * @default null
  15487. */
  15488. this._cubeTexture = null;
  15489. /**
  15490. * A reference to the internal cube texture node.
  15491. *
  15492. * @private
  15493. * @type {CubeTextureNode}
  15494. */
  15495. this._cubeTextureNode = cubeTexture( null );
  15496. const defaultTexture = new CubeTexture();
  15497. defaultTexture.isRenderTargetTexture = true;
  15498. /**
  15499. * A default cube texture that acts as a placeholder.
  15500. * It is used when the conversion from equirectangular to cube
  15501. * map has not finished yet for a given texture.
  15502. *
  15503. * @private
  15504. * @type {CubeTexture}
  15505. */
  15506. this._defaultTexture = defaultTexture;
  15507. /**
  15508. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15509. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15510. *
  15511. * @type {string}
  15512. * @default 'render'
  15513. */
  15514. this.updateBeforeType = NodeUpdateType.RENDER;
  15515. }
  15516. updateBefore( frame ) {
  15517. const { renderer, material } = frame;
  15518. const envNode = this.envNode;
  15519. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15520. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15521. if ( texture && texture.isTexture ) {
  15522. const mapping = texture.mapping;
  15523. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15524. // check for converted cubemap map
  15525. if ( _cache$1.has( texture ) ) {
  15526. const cubeMap = _cache$1.get( texture );
  15527. mapTextureMapping( cubeMap, texture.mapping );
  15528. this._cubeTexture = cubeMap;
  15529. } else {
  15530. // create cube map from equirectangular map
  15531. const image = texture.image;
  15532. if ( isEquirectangularMapReady$1( image ) ) {
  15533. const renderTarget = new CubeRenderTarget( image.height );
  15534. renderTarget.fromEquirectangularTexture( renderer, texture );
  15535. mapTextureMapping( renderTarget.texture, texture.mapping );
  15536. this._cubeTexture = renderTarget.texture;
  15537. _cache$1.set( texture, renderTarget.texture );
  15538. texture.addEventListener( 'dispose', onTextureDispose );
  15539. } else {
  15540. // default cube texture as fallback when equirectangular texture is not yet loaded
  15541. this._cubeTexture = this._defaultTexture;
  15542. }
  15543. }
  15544. //
  15545. this._cubeTextureNode.value = this._cubeTexture;
  15546. } else {
  15547. // envNode already refers to a cube map
  15548. this._cubeTextureNode = this.envNode;
  15549. }
  15550. }
  15551. }
  15552. }
  15553. setup( builder ) {
  15554. this.updateBefore( builder );
  15555. return this._cubeTextureNode;
  15556. }
  15557. }
  15558. /**
  15559. * Returns true if the given equirectangular image has been fully loaded
  15560. * and is ready for further processing.
  15561. *
  15562. * @private
  15563. * @param {Image} image - The equirectangular image to check.
  15564. * @return {boolean} Whether the image is ready or not.
  15565. */
  15566. function isEquirectangularMapReady$1( image ) {
  15567. if ( image === null || image === undefined ) return false;
  15568. return image.height > 0;
  15569. }
  15570. /**
  15571. * This function is executed when `dispose()` is called on the equirectangular
  15572. * texture. In this case, the generated cube map with its render target
  15573. * is deleted as well.
  15574. *
  15575. * @private
  15576. * @param {Object} event - The event object.
  15577. */
  15578. function onTextureDispose( event ) {
  15579. const texture = event.target;
  15580. texture.removeEventListener( 'dispose', onTextureDispose );
  15581. const renderTarget = _cache$1.get( texture );
  15582. if ( renderTarget !== undefined ) {
  15583. _cache$1.delete( texture );
  15584. renderTarget.dispose();
  15585. }
  15586. }
  15587. /**
  15588. * This function makes sure the generated cube map uses the correct
  15589. * texture mapping that corresponds to the equirectangular original.
  15590. *
  15591. * @private
  15592. * @param {Texture} texture - The cube texture.
  15593. * @param {number} mapping - The original texture mapping.
  15594. */
  15595. function mapTextureMapping( texture, mapping ) {
  15596. if ( mapping === EquirectangularReflectionMapping ) {
  15597. texture.mapping = CubeReflectionMapping;
  15598. } else if ( mapping === EquirectangularRefractionMapping ) {
  15599. texture.mapping = CubeRefractionMapping;
  15600. }
  15601. }
  15602. /**
  15603. * TSL function for creating a cube map node.
  15604. *
  15605. * @tsl
  15606. * @function
  15607. * @param {Node} envNode - The node representing the environment map.
  15608. * @returns {CubeMapNode}
  15609. */
  15610. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15611. /**
  15612. * Represents a basic model for Image-based lighting (IBL). The environment
  15613. * is defined via environment maps in the equirectangular or cube map format.
  15614. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15615. * or {@link MeshPhongNodeMaterial}.
  15616. *
  15617. * @augments LightingNode
  15618. */
  15619. class BasicEnvironmentNode extends LightingNode {
  15620. static get type() {
  15621. return 'BasicEnvironmentNode';
  15622. }
  15623. /**
  15624. * Constructs a new basic environment node.
  15625. *
  15626. * @param {Node} [envNode=null] - A node representing the environment.
  15627. */
  15628. constructor( envNode = null ) {
  15629. super();
  15630. /**
  15631. * A node representing the environment.
  15632. *
  15633. * @type {Node}
  15634. * @default null
  15635. */
  15636. this.envNode = envNode;
  15637. }
  15638. setup( builder ) {
  15639. // environment property is used in the finish() method of BasicLightingModel
  15640. builder.context.environment = cubeMapNode( this.envNode );
  15641. }
  15642. }
  15643. /**
  15644. * A specific version of {@link IrradianceNode} that is only relevant
  15645. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15646. * requires a special scaling factor for the light map.
  15647. *
  15648. * @augments LightingNode
  15649. */
  15650. class BasicLightMapNode extends LightingNode {
  15651. static get type() {
  15652. return 'BasicLightMapNode';
  15653. }
  15654. /**
  15655. * Constructs a new basic light map node.
  15656. *
  15657. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15658. */
  15659. constructor( lightMapNode = null ) {
  15660. super();
  15661. /**
  15662. * The light map node.
  15663. *
  15664. * @type {?Node<vec3>}
  15665. */
  15666. this.lightMapNode = lightMapNode;
  15667. }
  15668. setup( builder ) {
  15669. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15670. const RECIPROCAL_PI = float( 1 / Math.PI );
  15671. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15672. }
  15673. }
  15674. /**
  15675. * Abstract class for implementing lighting models. The module defines
  15676. * multiple methods that concrete lighting models can implement. These
  15677. * methods are executed at different points during the light evaluation
  15678. * process.
  15679. */
  15680. class LightingModel {
  15681. /**
  15682. * This method is intended for setting up lighting model and context data
  15683. * which are later used in the evaluation process.
  15684. *
  15685. * @abstract
  15686. * @param {NodeBuilder} builder - The current node builder.
  15687. */
  15688. start( builder ) {
  15689. // lights ( direct )
  15690. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15691. // indirect
  15692. this.indirect( builder );
  15693. }
  15694. /**
  15695. * This method is intended for executing final tasks like final updates
  15696. * to the outgoing light.
  15697. *
  15698. * @abstract
  15699. * @param {NodeBuilder} builder - The current node builder.
  15700. */
  15701. finish( /*builder*/ ) { }
  15702. /**
  15703. * This method is intended for implementing the direct light term and
  15704. * executed during the build process of directional, point and spot light nodes.
  15705. *
  15706. * @abstract
  15707. * @param {Object} lightData - The light data.
  15708. * @param {NodeBuilder} builder - The current node builder.
  15709. */
  15710. direct( /*lightData, builder*/ ) { }
  15711. /**
  15712. * This method is intended for implementing the direct light term for
  15713. * rect area light nodes.
  15714. *
  15715. * @abstract
  15716. * @param {Object} lightData - The light data.
  15717. * @param {NodeBuilder} builder - The current node builder.
  15718. */
  15719. directRectArea( /*lightData, builder*/ ) {}
  15720. /**
  15721. * This method is intended for implementing the indirect light term.
  15722. *
  15723. * @abstract
  15724. * @param {NodeBuilder} builder - The current node builder.
  15725. */
  15726. indirect( /*builder*/ ) { }
  15727. /**
  15728. * This method is intended for implementing the ambient occlusion term.
  15729. * Unlike other methods, this method must be called manually by the lighting
  15730. * model in its indirect term.
  15731. *
  15732. * @abstract
  15733. * @param {NodeBuilder} builder - The current node builder.
  15734. */
  15735. ambientOcclusion( /*input, stack, builder*/ ) { }
  15736. }
  15737. /**
  15738. * Represents the lighting model for unlit materials. The only light contribution
  15739. * is baked indirect lighting modulated with ambient occlusion and the material's
  15740. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15741. *
  15742. * @augments LightingModel
  15743. */
  15744. class BasicLightingModel extends LightingModel {
  15745. /**
  15746. * Constructs a new basic lighting model.
  15747. */
  15748. constructor() {
  15749. super();
  15750. }
  15751. /**
  15752. * Implements the baked indirect lighting with its modulation.
  15753. *
  15754. * @param {NodeBuilder} builder - The current node builder.
  15755. */
  15756. indirect( { context } ) {
  15757. const ambientOcclusion = context.ambientOcclusion;
  15758. const reflectedLight = context.reflectedLight;
  15759. const irradianceLightMap = context.irradianceLightMap;
  15760. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15761. // accumulation (baked indirect lighting only)
  15762. if ( irradianceLightMap ) {
  15763. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15764. } else {
  15765. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15766. }
  15767. // modulation
  15768. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15769. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15770. }
  15771. /**
  15772. * Implements the environment mapping.
  15773. *
  15774. * @param {NodeBuilder} builder - The current node builder.
  15775. */
  15776. finish( builder ) {
  15777. const { material, context } = builder;
  15778. const outgoingLight = context.outgoingLight;
  15779. const envNode = builder.context.environment;
  15780. if ( envNode ) {
  15781. switch ( material.combine ) {
  15782. case MultiplyOperation:
  15783. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15784. break;
  15785. case MixOperation:
  15786. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15787. break;
  15788. case AddOperation:
  15789. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15790. break;
  15791. default:
  15792. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15793. break;
  15794. }
  15795. }
  15796. }
  15797. }
  15798. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15799. /**
  15800. * Node material version of {@link MeshBasicMaterial}.
  15801. *
  15802. * @augments NodeMaterial
  15803. */
  15804. class MeshBasicNodeMaterial extends NodeMaterial {
  15805. static get type() {
  15806. return 'MeshBasicNodeMaterial';
  15807. }
  15808. /**
  15809. * Constructs a new mesh basic node material.
  15810. *
  15811. * @param {Object} [parameters] - The configuration parameter.
  15812. */
  15813. constructor( parameters ) {
  15814. super();
  15815. /**
  15816. * This flag can be used for type testing.
  15817. *
  15818. * @type {boolean}
  15819. * @readonly
  15820. * @default true
  15821. */
  15822. this.isMeshBasicNodeMaterial = true;
  15823. /**
  15824. * Although the basic material is by definition unlit, we set
  15825. * this property to `true` since we use a lighting model to compute
  15826. * the outgoing light of the fragment shader.
  15827. *
  15828. * @type {boolean}
  15829. * @default true
  15830. */
  15831. this.lights = true;
  15832. this.setDefaultValues( _defaultValues$9 );
  15833. this.setValues( parameters );
  15834. }
  15835. /**
  15836. * Basic materials are not affected by normal and bump maps so we
  15837. * return by default {@link normalViewGeometry}.
  15838. *
  15839. * @return {Node<vec3>} The normal node.
  15840. */
  15841. setupNormal() {
  15842. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15843. }
  15844. /**
  15845. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15846. * to implement the default environment mapping.
  15847. *
  15848. * @param {NodeBuilder} builder - The current node builder.
  15849. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15850. */
  15851. setupEnvironment( builder ) {
  15852. const envNode = super.setupEnvironment( builder );
  15853. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15854. }
  15855. /**
  15856. * This method must be overwritten since light maps are evaluated
  15857. * with a special scaling factor for basic materials.
  15858. *
  15859. * @param {NodeBuilder} builder - The current node builder.
  15860. * @return {?BasicLightMapNode<vec3>} The light map node.
  15861. */
  15862. setupLightMap( builder ) {
  15863. let node = null;
  15864. if ( builder.material.lightMap ) {
  15865. node = new BasicLightMapNode( materialLightMap );
  15866. }
  15867. return node;
  15868. }
  15869. /**
  15870. * The material overwrites this method because `lights` is set to `true` but
  15871. * we still want to return the diffuse color as the outgoing light.
  15872. *
  15873. * @return {Node<vec3>} The outgoing light node.
  15874. */
  15875. setupOutgoingLight() {
  15876. return diffuseColor.rgb;
  15877. }
  15878. /**
  15879. * Setups the lighting model.
  15880. *
  15881. * @return {BasicLightingModel} The lighting model.
  15882. */
  15883. setupLightingModel() {
  15884. return new BasicLightingModel();
  15885. }
  15886. }
  15887. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15888. // Original approximation by Christophe Schlick '94
  15889. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15890. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15891. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15892. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15893. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15894. } ); // validated
  15895. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15896. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15897. } ); // validated
  15898. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15899. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15900. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15901. } );
  15902. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15903. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15904. const dotNH = normalView.dot( halfDir ).clamp();
  15905. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15906. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15907. const G = G_BlinnPhong_Implicit();
  15908. const D = D_BlinnPhong( { dotNH } );
  15909. return F.mul( G ).mul( D );
  15910. } );
  15911. /**
  15912. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15913. *
  15914. * @augments BasicLightingModel
  15915. */
  15916. class PhongLightingModel extends BasicLightingModel {
  15917. /**
  15918. * Constructs a new phong lighting model.
  15919. *
  15920. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15921. */
  15922. constructor( specular = true ) {
  15923. super();
  15924. /**
  15925. * Whether specular is supported or not. Set this to `false` if you are
  15926. * looking for a Lambert-like material meaning a material for non-shiny
  15927. * surfaces, without specular highlights.
  15928. *
  15929. * @type {boolean}
  15930. * @default true
  15931. */
  15932. this.specular = specular;
  15933. }
  15934. /**
  15935. * Implements the direct lighting. The specular portion is optional an can be controlled
  15936. * with the {@link PhongLightingModel#specular} flag.
  15937. *
  15938. * @param {Object} lightData - The light data.
  15939. */
  15940. direct( { lightDirection, lightColor, reflectedLight } ) {
  15941. const dotNL = normalView.dot( lightDirection ).clamp();
  15942. const irradiance = dotNL.mul( lightColor );
  15943. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15944. if ( this.specular === true ) {
  15945. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15946. }
  15947. }
  15948. /**
  15949. * Implements the indirect lighting.
  15950. *
  15951. * @param {NodeBuilder} builder - The current node builder.
  15952. */
  15953. indirect( builder ) {
  15954. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15955. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15956. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15957. }
  15958. }
  15959. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15960. /**
  15961. * Node material version of {@link MeshLambertMaterial}.
  15962. *
  15963. * @augments NodeMaterial
  15964. */
  15965. class MeshLambertNodeMaterial extends NodeMaterial {
  15966. static get type() {
  15967. return 'MeshLambertNodeMaterial';
  15968. }
  15969. /**
  15970. * Constructs a new mesh lambert node material.
  15971. *
  15972. * @param {Object} [parameters] - The configuration parameter.
  15973. */
  15974. constructor( parameters ) {
  15975. super();
  15976. /**
  15977. * This flag can be used for type testing.
  15978. *
  15979. * @type {boolean}
  15980. * @readonly
  15981. * @default true
  15982. */
  15983. this.isMeshLambertNodeMaterial = true;
  15984. /**
  15985. * Set to `true` because lambert materials react on lights.
  15986. *
  15987. * @type {boolean}
  15988. * @default true
  15989. */
  15990. this.lights = true;
  15991. this.setDefaultValues( _defaultValues$8 );
  15992. this.setValues( parameters );
  15993. }
  15994. /**
  15995. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15996. * to implement the default environment mapping.
  15997. *
  15998. * @param {NodeBuilder} builder - The current node builder.
  15999. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16000. */
  16001. setupEnvironment( builder ) {
  16002. const envNode = super.setupEnvironment( builder );
  16003. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16004. }
  16005. /**
  16006. * Setups the lighting model.
  16007. *
  16008. * @return {PhongLightingModel} The lighting model.
  16009. */
  16010. setupLightingModel( /*builder*/ ) {
  16011. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16012. }
  16013. }
  16014. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16015. /**
  16016. * Node material version of {@link MeshPhongMaterial}.
  16017. *
  16018. * @augments NodeMaterial
  16019. */
  16020. class MeshPhongNodeMaterial extends NodeMaterial {
  16021. static get type() {
  16022. return 'MeshPhongNodeMaterial';
  16023. }
  16024. /**
  16025. * Constructs a new mesh lambert node material.
  16026. *
  16027. * @param {Object} [parameters] - The configuration parameter.
  16028. */
  16029. constructor( parameters ) {
  16030. super();
  16031. /**
  16032. * This flag can be used for type testing.
  16033. *
  16034. * @type {boolean}
  16035. * @readonly
  16036. * @default true
  16037. */
  16038. this.isMeshPhongNodeMaterial = true;
  16039. /**
  16040. * Set to `true` because phong materials react on lights.
  16041. *
  16042. * @type {boolean}
  16043. * @default true
  16044. */
  16045. this.lights = true;
  16046. /**
  16047. * The shininess of phong materials is by default inferred from the `shininess`
  16048. * property. This node property allows to overwrite the default
  16049. * and define the shininess with a node instead.
  16050. *
  16051. * If you don't want to overwrite the shininess but modify the existing
  16052. * value instead, use {@link materialShininess}.
  16053. *
  16054. * @type {?Node<float>}
  16055. * @default null
  16056. */
  16057. this.shininessNode = null;
  16058. /**
  16059. * The specular color of phong materials is by default inferred from the
  16060. * `specular` property. This node property allows to overwrite the default
  16061. * and define the specular color with a node instead.
  16062. *
  16063. * If you don't want to overwrite the specular color but modify the existing
  16064. * value instead, use {@link materialSpecular}.
  16065. *
  16066. * @type {?Node<vec3>}
  16067. * @default null
  16068. */
  16069. this.specularNode = null;
  16070. this.setDefaultValues( _defaultValues$7 );
  16071. this.setValues( parameters );
  16072. }
  16073. /**
  16074. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16075. * to implement the default environment mapping.
  16076. *
  16077. * @param {NodeBuilder} builder - The current node builder.
  16078. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16079. */
  16080. setupEnvironment( builder ) {
  16081. const envNode = super.setupEnvironment( builder );
  16082. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16083. }
  16084. /**
  16085. * Setups the lighting model.
  16086. *
  16087. * @return {PhongLightingModel} The lighting model.
  16088. */
  16089. setupLightingModel( /*builder*/ ) {
  16090. return new PhongLightingModel();
  16091. }
  16092. /**
  16093. * Setups the phong specific node variables.
  16094. *
  16095. * @param {NodeBuilder} builder - The current node builder.
  16096. */
  16097. setupVariants( /*builder*/ ) {
  16098. // SHININESS
  16099. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16100. shininess.assign( shininessNode );
  16101. // SPECULAR COLOR
  16102. const specularNode = this.specularNode || materialSpecular;
  16103. specularColor.assign( specularNode );
  16104. }
  16105. copy( source ) {
  16106. this.shininessNode = source.shininessNode;
  16107. this.specularNode = source.specularNode;
  16108. return super.copy( source );
  16109. }
  16110. }
  16111. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16112. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16113. return float( 0 );
  16114. }
  16115. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16116. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16117. return geometryRoughness;
  16118. } );
  16119. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16120. const { roughness } = inputs;
  16121. const geometryRoughness = getGeometryRoughness();
  16122. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16123. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16124. roughnessFactor = roughnessFactor.min( 1.0 );
  16125. return roughnessFactor;
  16126. } );
  16127. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16128. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16129. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16130. const a2 = alpha.pow2();
  16131. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16132. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16133. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16134. } ).setLayout( {
  16135. name: 'V_GGX_SmithCorrelated',
  16136. type: 'float',
  16137. inputs: [
  16138. { name: 'alpha', type: 'float' },
  16139. { name: 'dotNL', type: 'float' },
  16140. { name: 'dotNV', type: 'float' }
  16141. ]
  16142. } ); // validated
  16143. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16144. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16145. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16146. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16147. const v = div( 0.5, gv.add( gl ) );
  16148. return v.saturate();
  16149. } ).setLayout( {
  16150. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16151. type: 'float',
  16152. inputs: [
  16153. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16154. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16155. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16156. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16157. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16158. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16159. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16160. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16161. ]
  16162. } );
  16163. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16164. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16165. // alpha is "roughness squared" in Disney’s reparameterization
  16166. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16167. const a2 = alpha.pow2();
  16168. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16169. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16170. } ).setLayout( {
  16171. name: 'D_GGX',
  16172. type: 'float',
  16173. inputs: [
  16174. { name: 'alpha', type: 'float' },
  16175. { name: 'dotNH', type: 'float' }
  16176. ]
  16177. } ); // validated
  16178. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16179. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16180. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16181. const a2 = alphaT.mul( alphaB );
  16182. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16183. const v2 = v.dot( v );
  16184. const w2 = a2.div( v2 );
  16185. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16186. } ).setLayout( {
  16187. name: 'D_GGX_Anisotropic',
  16188. type: 'float',
  16189. inputs: [
  16190. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16191. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16192. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16193. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16194. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16195. ]
  16196. } );
  16197. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16198. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16199. const alpha = roughness.pow2(); // UE4's roughness
  16200. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16201. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16202. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16203. const dotNH = normalView$1.dot( halfDir ).clamp();
  16204. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16205. let F = F_Schlick( { f0, f90, dotVH } );
  16206. let V, D;
  16207. if ( defined( USE_IRIDESCENCE ) ) {
  16208. F = iridescence.mix( F, f );
  16209. }
  16210. if ( defined( USE_ANISOTROPY ) ) {
  16211. const dotTL = anisotropyT.dot( lightDirection );
  16212. const dotTV = anisotropyT.dot( positionViewDirection );
  16213. const dotTH = anisotropyT.dot( halfDir );
  16214. const dotBL = anisotropyB.dot( lightDirection );
  16215. const dotBV = anisotropyB.dot( positionViewDirection );
  16216. const dotBH = anisotropyB.dot( halfDir );
  16217. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16218. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16219. } else {
  16220. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16221. D = D_GGX( { alpha, dotNH } );
  16222. }
  16223. return F.mul( V ).mul( D );
  16224. } ); // validated
  16225. // Analytical approximation of the DFG LUT, one half of the
  16226. // split-sum approximation used in indirect specular lighting.
  16227. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  16228. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  16229. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16230. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  16231. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  16232. const r = roughness.mul( c0 ).add( c1 );
  16233. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  16234. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  16235. return fab;
  16236. } ).setLayout( {
  16237. name: 'DFGApprox',
  16238. type: 'vec2',
  16239. inputs: [
  16240. { name: 'roughness', type: 'float' },
  16241. { name: 'dotNV', type: 'vec3' }
  16242. ]
  16243. } );
  16244. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16245. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16246. const fab = DFGApprox( { dotNV, roughness } );
  16247. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16248. } );
  16249. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16250. const x = dotVH.oneMinus().saturate();
  16251. const x2 = x.mul( x );
  16252. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16253. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16254. } ).setLayout( {
  16255. name: 'Schlick_to_F0',
  16256. type: 'vec3',
  16257. inputs: [
  16258. { name: 'f', type: 'vec3' },
  16259. { name: 'f90', type: 'float' },
  16260. { name: 'dotVH', type: 'float' }
  16261. ]
  16262. } );
  16263. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16264. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16265. const alpha = roughness.pow2();
  16266. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16267. const invAlpha = float( 1.0 ).div( alpha );
  16268. const cos2h = dotNH.pow2();
  16269. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16270. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16271. } ).setLayout( {
  16272. name: 'D_Charlie',
  16273. type: 'float',
  16274. inputs: [
  16275. { name: 'roughness', type: 'float' },
  16276. { name: 'dotNH', type: 'float' }
  16277. ]
  16278. } );
  16279. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16280. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16281. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16282. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16283. } ).setLayout( {
  16284. name: 'V_Neubelt',
  16285. type: 'float',
  16286. inputs: [
  16287. { name: 'dotNV', type: 'float' },
  16288. { name: 'dotNL', type: 'float' }
  16289. ]
  16290. } );
  16291. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16292. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16293. const dotNL = normalView.dot( lightDirection ).clamp();
  16294. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16295. const dotNH = normalView.dot( halfDir ).clamp();
  16296. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16297. const V = V_Neubelt( { dotNV, dotNL } );
  16298. return sheen.mul( D ).mul( V );
  16299. } );
  16300. // Rect Area Light
  16301. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16302. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16303. // code: https://github.com/selfshadow/ltc_code/
  16304. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16305. const LUT_SIZE = 64.0;
  16306. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16307. const LUT_BIAS = 0.5 / LUT_SIZE;
  16308. const dotNV = N.dot( V ).saturate();
  16309. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16310. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16311. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16312. return uv;
  16313. } ).setLayout( {
  16314. name: 'LTC_Uv',
  16315. type: 'vec2',
  16316. inputs: [
  16317. { name: 'N', type: 'vec3' },
  16318. { name: 'V', type: 'vec3' },
  16319. { name: 'roughness', type: 'float' }
  16320. ]
  16321. } );
  16322. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16323. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16324. // An approximation of the form factor of a horizon-clipped rectangle.
  16325. const l = f.length();
  16326. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16327. } ).setLayout( {
  16328. name: 'LTC_ClippedSphereFormFactor',
  16329. type: 'float',
  16330. inputs: [
  16331. { name: 'f', type: 'vec3' }
  16332. ]
  16333. } );
  16334. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16335. const x = v1.dot( v2 );
  16336. const y = x.abs().toVar();
  16337. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16338. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16339. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16340. const v = a.div( b );
  16341. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16342. return v1.cross( v2 ).mul( theta_sintheta );
  16343. } ).setLayout( {
  16344. name: 'LTC_EdgeVectorFormFactor',
  16345. type: 'vec3',
  16346. inputs: [
  16347. { name: 'v1', type: 'vec3' },
  16348. { name: 'v2', type: 'vec3' }
  16349. ]
  16350. } );
  16351. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16352. // bail if point is on back side of plane of light
  16353. // assumes ccw winding order of light vertices
  16354. const v1 = p1.sub( p0 ).toVar();
  16355. const v2 = p3.sub( p0 ).toVar();
  16356. const lightNormal = v1.cross( v2 );
  16357. const result = vec3().toVar();
  16358. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16359. // construct orthonormal basis around N
  16360. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16361. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16362. // compute transform
  16363. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16364. // transform rect
  16365. // & project rect onto sphere
  16366. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16367. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16368. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16369. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16370. // calculate vector form factor
  16371. const vectorFormFactor = vec3( 0 ).toVar();
  16372. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16373. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16374. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16375. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16376. // adjust for horizon clipping
  16377. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16378. } );
  16379. return result;
  16380. } ).setLayout( {
  16381. name: 'LTC_Evaluate',
  16382. type: 'vec3',
  16383. inputs: [
  16384. { name: 'N', type: 'vec3' },
  16385. { name: 'V', type: 'vec3' },
  16386. { name: 'P', type: 'vec3' },
  16387. { name: 'mInv', type: 'mat3' },
  16388. { name: 'p0', type: 'vec3' },
  16389. { name: 'p1', type: 'vec3' },
  16390. { name: 'p2', type: 'vec3' },
  16391. { name: 'p3', type: 'vec3' }
  16392. ]
  16393. } );
  16394. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16395. // bail if point is on back side of plane of light
  16396. // assumes ccw winding order of light vertices
  16397. const v1 = p1.sub( p0 ).toVar();
  16398. const v2 = p3.sub( p0 ).toVar();
  16399. const lightNormal = v1.cross( v2 );
  16400. const result = vec3().toVar();
  16401. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16402. // transform rect
  16403. // & project rect onto sphere
  16404. const coords0 = p0.sub( P ).normalize().toVar();
  16405. const coords1 = p1.sub( P ).normalize().toVar();
  16406. const coords2 = p2.sub( P ).normalize().toVar();
  16407. const coords3 = p3.sub( P ).normalize().toVar();
  16408. // calculate vector form factor
  16409. const vectorFormFactor = vec3( 0 ).toVar();
  16410. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16411. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16412. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16413. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16414. // adjust for horizon clipping
  16415. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16416. } );
  16417. return result;
  16418. } ).setLayout( {
  16419. name: 'LTC_Evaluate',
  16420. type: 'vec3',
  16421. inputs: [
  16422. { name: 'P', type: 'vec3' },
  16423. { name: 'p0', type: 'vec3' },
  16424. { name: 'p1', type: 'vec3' },
  16425. { name: 'p2', type: 'vec3' },
  16426. { name: 'p3', type: 'vec3' }
  16427. ]
  16428. } );
  16429. // Mipped Bicubic Texture Filtering by N8
  16430. // https://www.shadertoy.com/view/Dl2SDW
  16431. const bC = 1.0 / 6.0;
  16432. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16433. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16434. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16435. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16436. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16437. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16438. // h0 and h1 are the two offset functions
  16439. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16440. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16441. const bicubic = ( textureNode, texelSize, lod ) => {
  16442. const uv = textureNode.uvNode;
  16443. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16444. const iuv = floor( uvScaled );
  16445. const fuv = fract( uvScaled );
  16446. const g0x = g0( fuv.x );
  16447. const g1x = g1( fuv.x );
  16448. const h0x = h0( fuv.x );
  16449. const h1x = h1( fuv.x );
  16450. const h0y = h0( fuv.y );
  16451. const h1y = h1( fuv.y );
  16452. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16453. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16454. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16455. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16456. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16457. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16458. return a.add( b );
  16459. };
  16460. /**
  16461. * Applies mipped bicubic texture filtering to the given texture node.
  16462. *
  16463. * @tsl
  16464. * @function
  16465. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16466. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16467. * @return {Node} The filtered texture sample.
  16468. */
  16469. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16470. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16471. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16472. const fLodSizeInv = div( 1.0, fLodSize );
  16473. const cLodSizeInv = div( 1.0, cLodSize );
  16474. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16475. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16476. return fract( lodNode ).mix( fSample, cSample );
  16477. } );
  16478. /**
  16479. * Applies mipped bicubic texture filtering to the given texture node.
  16480. *
  16481. * @tsl
  16482. * @function
  16483. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16484. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16485. * @return {Node} The filtered texture sample.
  16486. */
  16487. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16488. const lod = strength.mul( maxMipLevel( textureNode ) );
  16489. return textureBicubicLevel( textureNode, lod );
  16490. } );
  16491. //
  16492. // Transmission
  16493. //
  16494. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16495. // Direction of refracted light.
  16496. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16497. // Compute rotation-independent scaling of the model matrix.
  16498. const modelScale = vec3(
  16499. length( modelMatrix[ 0 ].xyz ),
  16500. length( modelMatrix[ 1 ].xyz ),
  16501. length( modelMatrix[ 2 ].xyz )
  16502. );
  16503. // The thickness is specified in local space.
  16504. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16505. } ).setLayout( {
  16506. name: 'getVolumeTransmissionRay',
  16507. type: 'vec3',
  16508. inputs: [
  16509. { name: 'n', type: 'vec3' },
  16510. { name: 'v', type: 'vec3' },
  16511. { name: 'thickness', type: 'float' },
  16512. { name: 'ior', type: 'float' },
  16513. { name: 'modelMatrix', type: 'mat4' }
  16514. ]
  16515. } );
  16516. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16517. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16518. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16519. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16520. } ).setLayout( {
  16521. name: 'applyIorToRoughness',
  16522. type: 'float',
  16523. inputs: [
  16524. { name: 'roughness', type: 'float' },
  16525. { name: 'ior', type: 'float' }
  16526. ]
  16527. } );
  16528. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16529. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16530. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16531. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16532. const transmissionSample = vTexture.sample( fragCoord );
  16533. //const transmissionSample = viewportMipTexture( fragCoord );
  16534. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16535. return textureBicubicLevel( transmissionSample, lod );
  16536. } );
  16537. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16538. If( attenuationDistance.notEqual( 0 ), () => {
  16539. // Compute light attenuation using Beer's law.
  16540. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16541. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16542. return transmittance;
  16543. } );
  16544. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16545. return vec3( 1.0 );
  16546. } ).setLayout( {
  16547. name: 'volumeAttenuation',
  16548. type: 'vec3',
  16549. inputs: [
  16550. { name: 'transmissionDistance', type: 'float' },
  16551. { name: 'attenuationColor', type: 'vec3' },
  16552. { name: 'attenuationDistance', type: 'float' }
  16553. ]
  16554. } );
  16555. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16556. let transmittedLight, transmittance;
  16557. if ( dispersion ) {
  16558. transmittedLight = vec4().toVar();
  16559. transmittance = vec3().toVar();
  16560. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16561. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16562. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16563. const ior = iors.element( i );
  16564. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16565. const refractedRayExit = position.add( transmissionRay );
  16566. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16567. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16568. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16569. refractionCoords.addAssign( 1.0 );
  16570. refractionCoords.divAssign( 2.0 );
  16571. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16572. // Sample framebuffer to get pixel the refracted ray hits.
  16573. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16574. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16575. transmittedLight.a.addAssign( transmissionSample.a );
  16576. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16577. } );
  16578. transmittedLight.a.divAssign( 3.0 );
  16579. } else {
  16580. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16581. const refractedRayExit = position.add( transmissionRay );
  16582. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16583. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16584. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16585. refractionCoords.addAssign( 1.0 );
  16586. refractionCoords.divAssign( 2.0 );
  16587. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16588. // Sample framebuffer to get pixel the refracted ray hits.
  16589. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16590. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16591. }
  16592. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16593. const dotNV = n.dot( v ).clamp();
  16594. // Get the specular component.
  16595. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16596. dotNV,
  16597. specularColor,
  16598. specularF90,
  16599. roughness
  16600. } ) );
  16601. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16602. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16603. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16604. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16605. } );
  16606. //
  16607. // Iridescence
  16608. //
  16609. // XYZ to linear-sRGB color space
  16610. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16611. 3.2404542, -0.969266, 0.0556434,
  16612. -1.5371385, 1.8760108, -0.2040259,
  16613. -0.4985314, 0.0415560, 1.0572252
  16614. );
  16615. // Assume air interface for top
  16616. // Note: We don't handle the case fresnel0 == 1
  16617. const Fresnel0ToIor = ( fresnel0 ) => {
  16618. const sqrtF0 = fresnel0.sqrt();
  16619. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16620. };
  16621. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16622. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16623. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16624. };
  16625. // Fresnel equations for dielectric/dielectric interfaces.
  16626. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16627. // Evaluation XYZ sensitivity curves in Fourier space
  16628. const evalSensitivity = ( OPD, shift ) => {
  16629. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16630. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16631. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16632. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16633. 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() );
  16634. 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() );
  16635. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16636. const rgb = XYZ_TO_REC709.mul( xyz );
  16637. return rgb;
  16638. };
  16639. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16640. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16641. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16642. // Evaluate the cosTheta on the base layer (Snell law)
  16643. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16644. // Handle TIR:
  16645. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16646. If( cosTheta2Sq.lessThan( 0 ), () => {
  16647. return vec3( 1.0 );
  16648. } );
  16649. const cosTheta2 = cosTheta2Sq.sqrt();
  16650. // First interface
  16651. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16652. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16653. //const R21 = R12;
  16654. const T121 = R12.oneMinus();
  16655. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16656. const phi21 = float( Math.PI ).sub( phi12 );
  16657. // Second interface
  16658. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16659. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16660. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16661. const phi23 = vec3(
  16662. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16663. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16664. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16665. );
  16666. // Phase shift
  16667. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16668. const phi = vec3( phi21 ).add( phi23 );
  16669. // Compound terms
  16670. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16671. const r123 = R123.sqrt();
  16672. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16673. // Reflectance term for m = 0 (DC term amplitude)
  16674. const C0 = R12.add( Rs );
  16675. const I = C0.toVar();
  16676. // Reflectance term for m > 0 (pairs of diracs)
  16677. const Cm = Rs.sub( T121 ).toVar();
  16678. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16679. Cm.mulAssign( r123 );
  16680. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16681. I.addAssign( Cm.mul( Sm ) );
  16682. } );
  16683. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16684. return I.max( vec3( 0.0 ) );
  16685. } ).setLayout( {
  16686. name: 'evalIridescence',
  16687. type: 'vec3',
  16688. inputs: [
  16689. { name: 'outsideIOR', type: 'float' },
  16690. { name: 'eta2', type: 'float' },
  16691. { name: 'cosTheta1', type: 'float' },
  16692. { name: 'thinFilmThickness', type: 'float' },
  16693. { name: 'baseF0', type: 'vec3' }
  16694. ]
  16695. } );
  16696. //
  16697. // Sheen
  16698. //
  16699. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16700. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16701. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16702. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16703. const dotNV = normal.dot( viewDir ).saturate();
  16704. const r2 = roughness.pow2();
  16705. const a = select(
  16706. roughness.lessThan( 0.25 ),
  16707. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16708. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16709. );
  16710. const b = select(
  16711. roughness.lessThan( 0.25 ),
  16712. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16713. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16714. );
  16715. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16716. return DG.mul( 1.0 / Math.PI ).saturate();
  16717. } );
  16718. const clearcoatF0 = vec3( 0.04 );
  16719. const clearcoatF90 = float( 1 );
  16720. /**
  16721. * Represents the lighting model for a PBR material.
  16722. *
  16723. * @augments LightingModel
  16724. */
  16725. class PhysicalLightingModel extends LightingModel {
  16726. /**
  16727. * Constructs a new physical lighting model.
  16728. *
  16729. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16730. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16731. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16732. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16733. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16734. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16735. */
  16736. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16737. super();
  16738. /**
  16739. * Whether clearcoat is supported or not.
  16740. *
  16741. * @type {boolean}
  16742. * @default false
  16743. */
  16744. this.clearcoat = clearcoat;
  16745. /**
  16746. * Whether sheen is supported or not.
  16747. *
  16748. * @type {boolean}
  16749. * @default false
  16750. */
  16751. this.sheen = sheen;
  16752. /**
  16753. * Whether iridescence is supported or not.
  16754. *
  16755. * @type {boolean}
  16756. * @default false
  16757. */
  16758. this.iridescence = iridescence;
  16759. /**
  16760. * Whether anisotropy is supported or not.
  16761. *
  16762. * @type {boolean}
  16763. * @default false
  16764. */
  16765. this.anisotropy = anisotropy;
  16766. /**
  16767. * Whether transmission is supported or not.
  16768. *
  16769. * @type {boolean}
  16770. * @default false
  16771. */
  16772. this.transmission = transmission;
  16773. /**
  16774. * Whether dispersion is supported or not.
  16775. *
  16776. * @type {boolean}
  16777. * @default false
  16778. */
  16779. this.dispersion = dispersion;
  16780. /**
  16781. * The clear coat radiance.
  16782. *
  16783. * @type {?Node}
  16784. * @default null
  16785. */
  16786. this.clearcoatRadiance = null;
  16787. /**
  16788. * The clear coat specular direct.
  16789. *
  16790. * @type {?Node}
  16791. * @default null
  16792. */
  16793. this.clearcoatSpecularDirect = null;
  16794. /**
  16795. * The clear coat specular indirect.
  16796. *
  16797. * @type {?Node}
  16798. * @default null
  16799. */
  16800. this.clearcoatSpecularIndirect = null;
  16801. /**
  16802. * The sheen specular direct.
  16803. *
  16804. * @type {?Node}
  16805. * @default null
  16806. */
  16807. this.sheenSpecularDirect = null;
  16808. /**
  16809. * The sheen specular indirect.
  16810. *
  16811. * @type {?Node}
  16812. * @default null
  16813. */
  16814. this.sheenSpecularIndirect = null;
  16815. /**
  16816. * The iridescence Fresnel.
  16817. *
  16818. * @type {?Node}
  16819. * @default null
  16820. */
  16821. this.iridescenceFresnel = null;
  16822. /**
  16823. * The iridescence F0.
  16824. *
  16825. * @type {?Node}
  16826. * @default null
  16827. */
  16828. this.iridescenceF0 = null;
  16829. }
  16830. /**
  16831. * Depending on what features are requested, the method prepares certain node variables
  16832. * which are later used for lighting computations.
  16833. *
  16834. * @param {NodeBuilder} builder - The current node builder.
  16835. */
  16836. start( builder ) {
  16837. if ( this.clearcoat === true ) {
  16838. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16839. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16840. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16841. }
  16842. if ( this.sheen === true ) {
  16843. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16844. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16845. }
  16846. if ( this.iridescence === true ) {
  16847. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16848. this.iridescenceFresnel = evalIridescence( {
  16849. outsideIOR: float( 1.0 ),
  16850. eta2: iridescenceIOR,
  16851. cosTheta1: dotNVi,
  16852. thinFilmThickness: iridescenceThickness,
  16853. baseF0: specularColor
  16854. } );
  16855. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16856. }
  16857. if ( this.transmission === true ) {
  16858. const position = positionWorld;
  16859. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16860. const n = normalWorld;
  16861. const context = builder.context;
  16862. context.backdrop = getIBLVolumeRefraction(
  16863. n,
  16864. v,
  16865. roughness,
  16866. diffuseColor,
  16867. specularColor,
  16868. specularF90, // specularF90
  16869. position, // positionWorld
  16870. modelWorldMatrix, // modelMatrix
  16871. cameraViewMatrix, // viewMatrix
  16872. cameraProjectionMatrix, // projMatrix
  16873. ior,
  16874. thickness,
  16875. attenuationColor,
  16876. attenuationDistance,
  16877. this.dispersion ? dispersion : null
  16878. );
  16879. context.backdropAlpha = transmission;
  16880. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16881. }
  16882. super.start( builder );
  16883. }
  16884. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16885. // Approximates multi-scattering in order to preserve energy.
  16886. // http://www.jcgt.org/published/0008/01/03/
  16887. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16888. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16889. const fab = DFGApprox( { roughness, dotNV } );
  16890. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16891. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16892. const Ess = fab.x.add( fab.y );
  16893. const Ems = Ess.oneMinus();
  16894. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16895. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16896. singleScatter.addAssign( FssEss );
  16897. multiScatter.addAssign( Fms.mul( Ems ) );
  16898. }
  16899. /**
  16900. * Implements the direct light.
  16901. *
  16902. * @param {Object} lightData - The light data.
  16903. * @param {NodeBuilder} builder - The current node builder.
  16904. */
  16905. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16906. const dotNL = normalView.dot( lightDirection ).clamp();
  16907. const irradiance = dotNL.mul( lightColor );
  16908. if ( this.sheen === true ) {
  16909. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16910. }
  16911. if ( this.clearcoat === true ) {
  16912. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16913. const ccIrradiance = dotNLcc.mul( lightColor );
  16914. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16915. }
  16916. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16917. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  16918. }
  16919. /**
  16920. * This method is intended for implementing the direct light term for
  16921. * rect area light nodes.
  16922. *
  16923. * @param {Object} input - The input data.
  16924. * @param {NodeBuilder} builder - The current node builder.
  16925. */
  16926. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16927. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16928. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16929. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16930. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16931. const N = normalView;
  16932. const V = positionViewDirection;
  16933. const P = positionView.toVar();
  16934. const uv = LTC_Uv( { N, V, roughness } );
  16935. const t1 = ltc_1.sample( uv ).toVar();
  16936. const t2 = ltc_2.sample( uv ).toVar();
  16937. const mInv = mat3(
  16938. vec3( t1.x, 0, t1.y ),
  16939. vec3( 0, 1, 0 ),
  16940. vec3( t1.z, 0, t1.w )
  16941. ).toVar();
  16942. // LTC Fresnel Approximation by Stephen Hill
  16943. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16944. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16945. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16946. 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 } ) ) );
  16947. }
  16948. /**
  16949. * Implements the indirect lighting.
  16950. *
  16951. * @param {NodeBuilder} builder - The current node builder.
  16952. */
  16953. indirect( builder ) {
  16954. this.indirectDiffuse( builder );
  16955. this.indirectSpecular( builder );
  16956. this.ambientOcclusion( builder );
  16957. }
  16958. /**
  16959. * Implements the indirect diffuse term.
  16960. *
  16961. * @param {NodeBuilder} builder - The current node builder.
  16962. */
  16963. indirectDiffuse( builder ) {
  16964. const { irradiance, reflectedLight } = builder.context;
  16965. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16966. }
  16967. /**
  16968. * Implements the indirect specular term.
  16969. *
  16970. * @param {NodeBuilder} builder - The current node builder.
  16971. */
  16972. indirectSpecular( builder ) {
  16973. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16974. if ( this.sheen === true ) {
  16975. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16976. sheen,
  16977. IBLSheenBRDF( {
  16978. normal: normalView,
  16979. viewDir: positionViewDirection,
  16980. roughness: sheenRoughness
  16981. } )
  16982. ) );
  16983. }
  16984. if ( this.clearcoat === true ) {
  16985. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16986. const clearcoatEnv = EnvironmentBRDF( {
  16987. dotNV: dotNVcc,
  16988. specularColor: clearcoatF0,
  16989. specularF90: clearcoatF90,
  16990. roughness: clearcoatRoughness
  16991. } );
  16992. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16993. }
  16994. // Both indirect specular and indirect diffuse light accumulate here
  16995. const singleScattering = vec3().toVar( 'singleScattering' );
  16996. const multiScattering = vec3().toVar( 'multiScattering' );
  16997. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16998. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16999. const totalScattering = singleScattering.add( multiScattering );
  17000. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  17001. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  17002. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  17003. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  17004. }
  17005. /**
  17006. * Implements the ambient occlusion term.
  17007. *
  17008. * @param {NodeBuilder} builder - The current node builder.
  17009. */
  17010. ambientOcclusion( builder ) {
  17011. const { ambientOcclusion, reflectedLight } = builder.context;
  17012. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17013. const aoNV = dotNV.add( ambientOcclusion );
  17014. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17015. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17016. if ( this.clearcoat === true ) {
  17017. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17018. }
  17019. if ( this.sheen === true ) {
  17020. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17021. }
  17022. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17023. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17024. }
  17025. /**
  17026. * Used for final lighting accumulations depending on the requested features.
  17027. *
  17028. * @param {NodeBuilder} builder - The current node builder.
  17029. */
  17030. finish( { context } ) {
  17031. const { outgoingLight } = context;
  17032. if ( this.clearcoat === true ) {
  17033. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17034. const Fcc = F_Schlick( {
  17035. dotVH: dotNVcc,
  17036. f0: clearcoatF0,
  17037. f90: clearcoatF90
  17038. } );
  17039. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17040. outgoingLight.assign( clearcoatLight );
  17041. }
  17042. if ( this.sheen === true ) {
  17043. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  17044. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  17045. outgoingLight.assign( sheenLight );
  17046. }
  17047. }
  17048. }
  17049. // These defines must match with PMREMGenerator
  17050. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17051. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17052. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17053. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17054. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17055. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17056. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17057. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17058. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17059. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17060. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17061. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17062. // These shader functions convert between the UV coordinates of a single face of
  17063. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17064. // sampling a textureCube (not generally normalized ).
  17065. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17066. const absDirection = vec3( abs( direction ) ).toVar();
  17067. const face = float( -1 ).toVar();
  17068. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17069. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17070. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17071. } ).Else( () => {
  17072. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17073. } );
  17074. } ).Else( () => {
  17075. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17076. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17077. } ).Else( () => {
  17078. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17079. } );
  17080. } );
  17081. return face;
  17082. } ).setLayout( {
  17083. name: 'getFace',
  17084. type: 'float',
  17085. inputs: [
  17086. { name: 'direction', type: 'vec3' }
  17087. ]
  17088. } );
  17089. // RH coordinate system; PMREM face-indexing convention
  17090. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17091. const uv = vec2().toVar();
  17092. If( face.equal( 0.0 ), () => {
  17093. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17094. } ).ElseIf( face.equal( 1.0 ), () => {
  17095. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17096. } ).ElseIf( face.equal( 2.0 ), () => {
  17097. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17098. } ).ElseIf( face.equal( 3.0 ), () => {
  17099. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17100. } ).ElseIf( face.equal( 4.0 ), () => {
  17101. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17102. } ).Else( () => {
  17103. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17104. } );
  17105. return mul( 0.5, uv.add( 1.0 ) );
  17106. } ).setLayout( {
  17107. name: 'getUV',
  17108. type: 'vec2',
  17109. inputs: [
  17110. { name: 'direction', type: 'vec3' },
  17111. { name: 'face', type: 'float' }
  17112. ]
  17113. } );
  17114. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17115. const mip = float( 0.0 ).toVar();
  17116. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17117. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17118. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17119. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17120. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17121. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17122. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17123. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17124. } ).Else( () => {
  17125. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17126. } );
  17127. return mip;
  17128. } ).setLayout( {
  17129. name: 'roughnessToMip',
  17130. type: 'float',
  17131. inputs: [
  17132. { name: 'roughness', type: 'float' }
  17133. ]
  17134. } );
  17135. // RH coordinate system; PMREM face-indexing convention
  17136. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17137. const uv = uv_immutable.toVar();
  17138. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17139. const direction = vec3( uv, 1.0 ).toVar();
  17140. If( face.equal( 0.0 ), () => {
  17141. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17142. } ).ElseIf( face.equal( 1.0 ), () => {
  17143. direction.assign( direction.xzy );
  17144. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17145. } ).ElseIf( face.equal( 2.0 ), () => {
  17146. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17147. } ).ElseIf( face.equal( 3.0 ), () => {
  17148. direction.assign( direction.zyx );
  17149. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17150. } ).ElseIf( face.equal( 4.0 ), () => {
  17151. direction.assign( direction.xzy );
  17152. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17153. } ).ElseIf( face.equal( 5.0 ), () => {
  17154. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17155. } );
  17156. return direction;
  17157. } ).setLayout( {
  17158. name: 'getDirection',
  17159. type: 'vec3',
  17160. inputs: [
  17161. { name: 'uv', type: 'vec2' },
  17162. { name: 'face', type: 'float' }
  17163. ]
  17164. } );
  17165. //
  17166. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17167. const roughness = float( roughness_immutable );
  17168. const sampleDir = vec3( sampleDir_immutable );
  17169. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17170. const mipF = fract( mip );
  17171. const mipInt = floor( mip );
  17172. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17173. If( mipF.notEqual( 0.0 ), () => {
  17174. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17175. color0.assign( mix( color0, color1, mipF ) );
  17176. } );
  17177. return color0;
  17178. } );
  17179. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17180. const mipInt = float( mipInt_immutable ).toVar();
  17181. const direction = vec3( direction_immutable );
  17182. const face = float( getFace( direction ) ).toVar();
  17183. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17184. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17185. const faceSize = float( exp2( mipInt ) ).toVar();
  17186. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17187. If( face.greaterThan( 2.0 ), () => {
  17188. uv.y.addAssign( faceSize );
  17189. face.subAssign( 3.0 );
  17190. } );
  17191. uv.x.addAssign( face.mul( faceSize ) );
  17192. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17193. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17194. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17195. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17196. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17197. } );
  17198. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17199. const cosTheta = cos( theta );
  17200. // Rodrigues' axis-angle rotation
  17201. const sampleDirection = outputDirection.mul( cosTheta )
  17202. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17203. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17204. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17205. } );
  17206. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17207. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17208. If( axis.equal( vec3( 0.0 ) ), () => {
  17209. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17210. } );
  17211. axis.assign( normalize( axis ) );
  17212. const gl_FragColor = vec3().toVar();
  17213. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17214. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17215. If( i.greaterThanEqual( samples ), () => {
  17216. Break();
  17217. } );
  17218. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17219. 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 } ) ) );
  17220. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17221. } );
  17222. return vec4( gl_FragColor, 1 );
  17223. } );
  17224. const LOD_MIN = 4;
  17225. // The standard deviations (radians) associated with the extra mips. These are
  17226. // chosen to approximate a Trowbridge-Reitz distribution function times the
  17227. // geometric shadowing function. These sigma values squared must match the
  17228. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  17229. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17230. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17231. // samples and exit early, but not recompile the shader.
  17232. const MAX_SAMPLES = 20;
  17233. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17234. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17235. const _clearColor$2 = /*@__PURE__*/ new Color();
  17236. let _oldTarget = null;
  17237. let _oldActiveCubeFace = 0;
  17238. let _oldActiveMipmapLevel = 0;
  17239. // Golden Ratio
  17240. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  17241. const INV_PHI = 1 / PHI;
  17242. // Vertices of a dodecahedron (except the opposites, which represent the
  17243. // same axis), used as axis directions evenly spread on a sphere.
  17244. const _axisDirections = [
  17245. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  17246. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  17247. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  17248. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  17249. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  17250. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  17251. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  17252. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  17253. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  17254. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  17255. ];
  17256. const _origin = /*@__PURE__*/ new Vector3();
  17257. // maps blur materials to their uniforms dictionary
  17258. const _uniformsMap = new WeakMap();
  17259. // WebGPU Face indices
  17260. const _faceLib = [
  17261. 3, 1, 5,
  17262. 0, 4, 2
  17263. ];
  17264. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17265. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17266. /**
  17267. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17268. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17269. * blur to be quickly accessed based on material roughness. It is packed into a
  17270. * special CubeUV format that allows us to perform custom interpolation so that
  17271. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17272. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17273. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17274. * higher roughness levels. In this way we maintain resolution to smoothly
  17275. * interpolate diffuse lighting while limiting sampling computation.
  17276. *
  17277. * Paper: Fast, Accurate Image-Based Lighting:
  17278. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  17279. */
  17280. class PMREMGenerator {
  17281. /**
  17282. * Constructs a new PMREM generator.
  17283. *
  17284. * @param {Renderer} renderer - The renderer.
  17285. */
  17286. constructor( renderer ) {
  17287. this._renderer = renderer;
  17288. this._pingPongRenderTarget = null;
  17289. this._lodMax = 0;
  17290. this._cubeSize = 0;
  17291. this._lodPlanes = [];
  17292. this._sizeLods = [];
  17293. this._sigmas = [];
  17294. this._lodMeshes = [];
  17295. this._blurMaterial = null;
  17296. this._cubemapMaterial = null;
  17297. this._equirectMaterial = null;
  17298. this._backgroundBox = null;
  17299. }
  17300. get _hasInitialized() {
  17301. return this._renderer.hasInitialized();
  17302. }
  17303. /**
  17304. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17305. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17306. * in radians to be applied to the scene before PMREM generation. Optional near
  17307. * and far planes ensure the scene is rendered in its entirety.
  17308. *
  17309. * @param {Scene} scene - The scene to be captured.
  17310. * @param {number} [sigma=0] - The blur radius in radians.
  17311. * @param {number} [near=0.1] - The near plane distance.
  17312. * @param {number} [far=100] - The far plane distance.
  17313. * @param {Object} [options={}] - The configuration options.
  17314. * @param {number} [options.size=256] - The texture size of the PMREM.
  17315. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17316. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17317. * @return {RenderTarget} The resulting PMREM.
  17318. * @see {@link PMREMGenerator#fromSceneAsync}
  17319. */
  17320. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17321. const {
  17322. size = 256,
  17323. position = _origin,
  17324. renderTarget = null,
  17325. } = options;
  17326. this._setSize( size );
  17327. if ( this._hasInitialized === false ) {
  17328. warn( 'PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  17329. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17330. options.renderTarget = cubeUVRenderTarget;
  17331. this.fromSceneAsync( scene, sigma, near, far, options );
  17332. return cubeUVRenderTarget;
  17333. }
  17334. _oldTarget = this._renderer.getRenderTarget();
  17335. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17336. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17337. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17338. cubeUVRenderTarget.depthBuffer = true;
  17339. this._init( cubeUVRenderTarget );
  17340. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17341. if ( sigma > 0 ) {
  17342. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17343. }
  17344. this._applyPMREM( cubeUVRenderTarget );
  17345. this._cleanup( cubeUVRenderTarget );
  17346. return cubeUVRenderTarget;
  17347. }
  17348. /**
  17349. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17350. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17351. * in radians to be applied to the scene before PMREM generation. Optional near
  17352. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17353. * is placed at the origin).
  17354. *
  17355. * @param {Scene} scene - The scene to be captured.
  17356. * @param {number} [sigma=0] - The blur radius in radians.
  17357. * @param {number} [near=0.1] - The near plane distance.
  17358. * @param {number} [far=100] - The far plane distance.
  17359. * @param {Object} [options={}] - The configuration options.
  17360. * @param {number} [options.size=256] - The texture size of the PMREM.
  17361. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17362. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17363. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17364. * @see {@link PMREMGenerator#fromScene}
  17365. */
  17366. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17367. if ( this._hasInitialized === false ) await this._renderer.init();
  17368. return this.fromScene( scene, sigma, near, far, options );
  17369. }
  17370. /**
  17371. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17372. * or HDR. The ideal input image size is 1k (1024 x 512),
  17373. * as this matches best with the 256 x 256 cubemap output.
  17374. *
  17375. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17376. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17377. * @return {RenderTarget} The resulting PMREM.
  17378. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17379. */
  17380. fromEquirectangular( equirectangular, renderTarget = null ) {
  17381. if ( this._hasInitialized === false ) {
  17382. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  17383. this._setSizeFromTexture( equirectangular );
  17384. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17385. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17386. return cubeUVRenderTarget;
  17387. }
  17388. return this._fromTexture( equirectangular, renderTarget );
  17389. }
  17390. /**
  17391. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17392. * or HDR. The ideal input image size is 1k (1024 x 512),
  17393. * as this matches best with the 256 x 256 cubemap output.
  17394. *
  17395. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17396. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17397. * @return {Promise<RenderTarget>} The resulting PMREM.
  17398. * @see {@link PMREMGenerator#fromEquirectangular}
  17399. */
  17400. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17401. if ( this._hasInitialized === false ) await this._renderer.init();
  17402. return this._fromTexture( equirectangular, renderTarget );
  17403. }
  17404. /**
  17405. * Generates a PMREM from an cubemap texture, which can be either LDR
  17406. * or HDR. The ideal input cube size is 256 x 256,
  17407. * as this matches best with the 256 x 256 cubemap output.
  17408. *
  17409. * @param {Texture} cubemap - The cubemap texture to be converted.
  17410. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17411. * @return {RenderTarget} The resulting PMREM.
  17412. * @see {@link PMREMGenerator#fromCubemapAsync}
  17413. */
  17414. fromCubemap( cubemap, renderTarget = null ) {
  17415. if ( this._hasInitialized === false ) {
  17416. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17417. this._setSizeFromTexture( cubemap );
  17418. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17419. this.fromCubemapAsync( cubemap, renderTarget );
  17420. return cubeUVRenderTarget;
  17421. }
  17422. return this._fromTexture( cubemap, renderTarget );
  17423. }
  17424. /**
  17425. * Generates a PMREM from an cubemap texture, which can be either LDR
  17426. * or HDR. The ideal input cube size is 256 x 256,
  17427. * with the 256 x 256 cubemap output.
  17428. *
  17429. * @param {Texture} cubemap - The cubemap texture to be converted.
  17430. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17431. * @return {Promise<RenderTarget>} The resulting PMREM.
  17432. * @see {@link PMREMGenerator#fromCubemap}
  17433. */
  17434. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17435. if ( this._hasInitialized === false ) await this._renderer.init();
  17436. return this._fromTexture( cubemap, renderTarget );
  17437. }
  17438. /**
  17439. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17440. * your texture's network fetch for increased concurrency.
  17441. *
  17442. * @returns {Promise}
  17443. */
  17444. async compileCubemapShader() {
  17445. if ( this._cubemapMaterial === null ) {
  17446. this._cubemapMaterial = _getCubemapMaterial();
  17447. await this._compileMaterial( this._cubemapMaterial );
  17448. }
  17449. }
  17450. /**
  17451. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17452. * your texture's network fetch for increased concurrency.
  17453. *
  17454. * @returns {Promise}
  17455. */
  17456. async compileEquirectangularShader() {
  17457. if ( this._equirectMaterial === null ) {
  17458. this._equirectMaterial = _getEquirectMaterial();
  17459. await this._compileMaterial( this._equirectMaterial );
  17460. }
  17461. }
  17462. /**
  17463. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17464. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17465. * one of them will cause any others to also become unusable.
  17466. */
  17467. dispose() {
  17468. this._dispose();
  17469. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17470. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17471. if ( this._backgroundBox !== null ) {
  17472. this._backgroundBox.geometry.dispose();
  17473. this._backgroundBox.material.dispose();
  17474. }
  17475. }
  17476. // private interface
  17477. _setSizeFromTexture( texture ) {
  17478. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17479. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17480. } else { // Equirectangular
  17481. this._setSize( texture.image.width / 4 );
  17482. }
  17483. }
  17484. _setSize( cubeSize ) {
  17485. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17486. this._cubeSize = Math.pow( 2, this._lodMax );
  17487. }
  17488. _dispose() {
  17489. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17490. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17491. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17492. this._lodPlanes[ i ].dispose();
  17493. }
  17494. }
  17495. _cleanup( outputTarget ) {
  17496. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17497. outputTarget.scissorTest = false;
  17498. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17499. }
  17500. _fromTexture( texture, renderTarget ) {
  17501. this._setSizeFromTexture( texture );
  17502. _oldTarget = this._renderer.getRenderTarget();
  17503. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17504. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17505. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17506. this._init( cubeUVRenderTarget );
  17507. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17508. this._applyPMREM( cubeUVRenderTarget );
  17509. this._cleanup( cubeUVRenderTarget );
  17510. return cubeUVRenderTarget;
  17511. }
  17512. _allocateTarget() {
  17513. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17514. const height = 4 * this._cubeSize;
  17515. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17516. return cubeUVRenderTarget;
  17517. }
  17518. _init( renderTarget ) {
  17519. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17520. if ( this._pingPongRenderTarget !== null ) {
  17521. this._dispose();
  17522. }
  17523. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17524. const { _lodMax } = this;
  17525. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17526. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17527. }
  17528. }
  17529. async _compileMaterial( material ) {
  17530. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17531. await this._renderer.compile( tmpMesh, _flatCamera );
  17532. }
  17533. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17534. const cubeCamera = _cubeCamera;
  17535. cubeCamera.near = near;
  17536. cubeCamera.far = far;
  17537. // px, py, pz, nx, ny, nz
  17538. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17539. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17540. const renderer = this._renderer;
  17541. const originalAutoClear = renderer.autoClear;
  17542. renderer.getClearColor( _clearColor$2 );
  17543. renderer.autoClear = false;
  17544. let backgroundBox = this._backgroundBox;
  17545. if ( backgroundBox === null ) {
  17546. const backgroundMaterial = new MeshBasicMaterial( {
  17547. name: 'PMREM.Background',
  17548. side: BackSide,
  17549. depthWrite: false,
  17550. depthTest: false
  17551. } );
  17552. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17553. }
  17554. let useSolidColor = false;
  17555. const background = scene.background;
  17556. if ( background ) {
  17557. if ( background.isColor ) {
  17558. backgroundBox.material.color.copy( background );
  17559. scene.background = null;
  17560. useSolidColor = true;
  17561. }
  17562. } else {
  17563. backgroundBox.material.color.copy( _clearColor$2 );
  17564. useSolidColor = true;
  17565. }
  17566. renderer.setRenderTarget( cubeUVRenderTarget );
  17567. renderer.clear();
  17568. if ( useSolidColor ) {
  17569. renderer.render( backgroundBox, cubeCamera );
  17570. }
  17571. for ( let i = 0; i < 6; i ++ ) {
  17572. const col = i % 3;
  17573. if ( col === 0 ) {
  17574. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17575. cubeCamera.position.set( position.x, position.y, position.z );
  17576. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17577. } else if ( col === 1 ) {
  17578. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17579. cubeCamera.position.set( position.x, position.y, position.z );
  17580. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17581. } else {
  17582. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17583. cubeCamera.position.set( position.x, position.y, position.z );
  17584. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17585. }
  17586. const size = this._cubeSize;
  17587. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17588. renderer.render( scene, cubeCamera );
  17589. }
  17590. renderer.autoClear = originalAutoClear;
  17591. scene.background = background;
  17592. }
  17593. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17594. const renderer = this._renderer;
  17595. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17596. if ( isCubeTexture ) {
  17597. if ( this._cubemapMaterial === null ) {
  17598. this._cubemapMaterial = _getCubemapMaterial( texture );
  17599. }
  17600. } else {
  17601. if ( this._equirectMaterial === null ) {
  17602. this._equirectMaterial = _getEquirectMaterial( texture );
  17603. }
  17604. }
  17605. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17606. material.fragmentNode.value = texture;
  17607. const mesh = this._lodMeshes[ 0 ];
  17608. mesh.material = material;
  17609. const size = this._cubeSize;
  17610. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17611. renderer.setRenderTarget( cubeUVRenderTarget );
  17612. renderer.render( mesh, _flatCamera );
  17613. }
  17614. _applyPMREM( cubeUVRenderTarget ) {
  17615. const renderer = this._renderer;
  17616. const autoClear = renderer.autoClear;
  17617. renderer.autoClear = false;
  17618. const n = this._lodPlanes.length;
  17619. for ( let i = 1; i < n; i ++ ) {
  17620. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17621. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17622. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17623. }
  17624. renderer.autoClear = autoClear;
  17625. }
  17626. /**
  17627. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17628. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17629. * the blur latitudinally (around the poles), and then longitudinally (towards
  17630. * the poles) to approximate the orthogonally-separable blur. It is least
  17631. * accurate at the poles, but still does a decent job.
  17632. *
  17633. * @private
  17634. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17635. * @param {number} lodIn - The input level-of-detail.
  17636. * @param {number} lodOut - The output level-of-detail.
  17637. * @param {number} sigma - The blur radius in radians.
  17638. * @param {Vector3} [poleAxis] - The pole axis.
  17639. */
  17640. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17641. const pingPongRenderTarget = this._pingPongRenderTarget;
  17642. this._halfBlur(
  17643. cubeUVRenderTarget,
  17644. pingPongRenderTarget,
  17645. lodIn,
  17646. lodOut,
  17647. sigma,
  17648. 'latitudinal',
  17649. poleAxis );
  17650. this._halfBlur(
  17651. pingPongRenderTarget,
  17652. cubeUVRenderTarget,
  17653. lodOut,
  17654. lodOut,
  17655. sigma,
  17656. 'longitudinal',
  17657. poleAxis );
  17658. }
  17659. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17660. const renderer = this._renderer;
  17661. const blurMaterial = this._blurMaterial;
  17662. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17663. error( 'blur direction must be either latitudinal or longitudinal!' );
  17664. }
  17665. // Number of standard deviations at which to cut off the discrete approximation.
  17666. const STANDARD_DEVIATIONS = 3;
  17667. const blurMesh = this._lodMeshes[ lodOut ];
  17668. blurMesh.material = blurMaterial;
  17669. const blurUniforms = _uniformsMap.get( blurMaterial );
  17670. const pixels = this._sizeLods[ lodIn ] - 1;
  17671. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17672. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17673. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17674. if ( samples > MAX_SAMPLES ) {
  17675. warn( `sigmaRadians, ${
  17676. sigmaRadians}, is too large and will clip, as it requested ${
  17677. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17678. }
  17679. const weights = [];
  17680. let sum = 0;
  17681. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17682. const x = i / sigmaPixels;
  17683. const weight = Math.exp( - x * x / 2 );
  17684. weights.push( weight );
  17685. if ( i === 0 ) {
  17686. sum += weight;
  17687. } else if ( i < samples ) {
  17688. sum += 2 * weight;
  17689. }
  17690. }
  17691. for ( let i = 0; i < weights.length; i ++ ) {
  17692. weights[ i ] = weights[ i ] / sum;
  17693. }
  17694. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17695. blurUniforms.envMap.value = targetIn.texture;
  17696. blurUniforms.samples.value = samples;
  17697. blurUniforms.weights.array = weights;
  17698. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17699. if ( poleAxis ) {
  17700. blurUniforms.poleAxis.value = poleAxis;
  17701. }
  17702. const { _lodMax } = this;
  17703. blurUniforms.dTheta.value = radiansPerPixel;
  17704. blurUniforms.mipInt.value = _lodMax - lodIn;
  17705. const outputSize = this._sizeLods[ lodOut ];
  17706. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17707. const y = 4 * ( this._cubeSize - outputSize );
  17708. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17709. renderer.setRenderTarget( targetOut );
  17710. renderer.render( blurMesh, _flatCamera );
  17711. }
  17712. }
  17713. function _createPlanes( lodMax ) {
  17714. const lodPlanes = [];
  17715. const sizeLods = [];
  17716. const sigmas = [];
  17717. const lodMeshes = [];
  17718. let lod = lodMax;
  17719. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17720. for ( let i = 0; i < totalLods; i ++ ) {
  17721. const sizeLod = Math.pow( 2, lod );
  17722. sizeLods.push( sizeLod );
  17723. let sigma = 1.0 / sizeLod;
  17724. if ( i > lodMax - LOD_MIN ) {
  17725. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17726. } else if ( i === 0 ) {
  17727. sigma = 0;
  17728. }
  17729. sigmas.push( sigma );
  17730. const texelSize = 1.0 / ( sizeLod - 2 );
  17731. const min = - texelSize;
  17732. const max = 1 + texelSize;
  17733. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17734. const cubeFaces = 6;
  17735. const vertices = 6;
  17736. const positionSize = 3;
  17737. const uvSize = 2;
  17738. const faceIndexSize = 1;
  17739. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17740. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17741. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17742. for ( let face = 0; face < cubeFaces; face ++ ) {
  17743. const x = ( face % 3 ) * 2 / 3 - 1;
  17744. const y = face > 2 ? 0 : -1;
  17745. const coordinates = [
  17746. x, y, 0,
  17747. x + 2 / 3, y, 0,
  17748. x + 2 / 3, y + 1, 0,
  17749. x, y, 0,
  17750. x + 2 / 3, y + 1, 0,
  17751. x, y + 1, 0
  17752. ];
  17753. const faceIdx = _faceLib[ face ];
  17754. position.set( coordinates, positionSize * vertices * faceIdx );
  17755. uv.set( uv1, uvSize * vertices * faceIdx );
  17756. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17757. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17758. }
  17759. const planes = new BufferGeometry();
  17760. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17761. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17762. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17763. lodPlanes.push( planes );
  17764. lodMeshes.push( new Mesh( planes, null ) );
  17765. if ( lod > LOD_MIN ) {
  17766. lod --;
  17767. }
  17768. }
  17769. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17770. }
  17771. function _createRenderTarget( width, height ) {
  17772. const params = {
  17773. magFilter: LinearFilter,
  17774. minFilter: LinearFilter,
  17775. generateMipmaps: false,
  17776. type: HalfFloatType,
  17777. format: RGBAFormat,
  17778. colorSpace: LinearSRGBColorSpace,
  17779. //depthBuffer: false
  17780. };
  17781. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17782. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17783. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17784. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17785. cubeUVRenderTarget.scissorTest = true;
  17786. return cubeUVRenderTarget;
  17787. }
  17788. function _setViewport( target, x, y, width, height ) {
  17789. target.viewport.set( x, y, width, height );
  17790. target.scissor.set( x, y, width, height );
  17791. }
  17792. function _getMaterial( type ) {
  17793. const material = new NodeMaterial();
  17794. material.depthTest = false;
  17795. material.depthWrite = false;
  17796. material.blending = NoBlending;
  17797. material.name = `PMREM_${ type }`;
  17798. return material;
  17799. }
  17800. function _getBlurShader( lodMax, width, height ) {
  17801. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17802. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17803. const dTheta = uniform( 0 );
  17804. const n = float( MAX_SAMPLES );
  17805. const latitudinal = uniform( 0 ); // false, bool
  17806. const samples = uniform( 1 ); // int
  17807. const envMap = texture( null );
  17808. const mipInt = uniform( 0 ); // int
  17809. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17810. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17811. const CUBEUV_MAX_MIP = float( lodMax );
  17812. const materialUniforms = {
  17813. n,
  17814. latitudinal,
  17815. weights,
  17816. poleAxis,
  17817. outputDirection: _outputDirection,
  17818. dTheta,
  17819. samples,
  17820. envMap,
  17821. mipInt,
  17822. CUBEUV_TEXEL_WIDTH,
  17823. CUBEUV_TEXEL_HEIGHT,
  17824. CUBEUV_MAX_MIP
  17825. };
  17826. const material = _getMaterial( 'blur' );
  17827. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17828. _uniformsMap.set( material, materialUniforms );
  17829. return material;
  17830. }
  17831. function _getCubemapMaterial( envTexture ) {
  17832. const material = _getMaterial( 'cubemap' );
  17833. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17834. return material;
  17835. }
  17836. function _getEquirectMaterial( envTexture ) {
  17837. const material = _getMaterial( 'equirect' );
  17838. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17839. return material;
  17840. }
  17841. const _cache = new WeakMap();
  17842. /**
  17843. * Generates the cubeUV size based on the given image height.
  17844. *
  17845. * @private
  17846. * @param {number} imageHeight - The image height.
  17847. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17848. */
  17849. function _generateCubeUVSize( imageHeight ) {
  17850. const maxMip = Math.log2( imageHeight ) - 2;
  17851. const texelHeight = 1.0 / imageHeight;
  17852. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17853. return { texelWidth, texelHeight, maxMip };
  17854. }
  17855. /**
  17856. * Generates a PMREM from the given texture.
  17857. *
  17858. * @private
  17859. * @param {Texture} texture - The texture to create the PMREM for.
  17860. * @param {Renderer} renderer - The renderer.
  17861. * @param {PMREMGenerator} generator - The PMREM generator.
  17862. * @return {?Texture} The PMREM.
  17863. */
  17864. function _getPMREMFromTexture( texture, renderer, generator ) {
  17865. const cache = _getCache( renderer );
  17866. let cacheTexture = cache.get( texture );
  17867. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17868. if ( pmremVersion !== texture.pmremVersion ) {
  17869. const image = texture.image;
  17870. if ( texture.isCubeTexture ) {
  17871. if ( isCubeMapReady( image ) ) {
  17872. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17873. } else {
  17874. return null;
  17875. }
  17876. } else {
  17877. if ( isEquirectangularMapReady( image ) ) {
  17878. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17879. } else {
  17880. return null;
  17881. }
  17882. }
  17883. cacheTexture.pmremVersion = texture.pmremVersion;
  17884. cache.set( texture, cacheTexture );
  17885. }
  17886. return cacheTexture.texture;
  17887. }
  17888. /**
  17889. * Returns a cache that stores generated PMREMs for the respective textures.
  17890. * A cache must be maintained per renderer since PMREMs are render target textures
  17891. * which can't be shared across render contexts.
  17892. *
  17893. * @private
  17894. * @param {Renderer} renderer - The renderer.
  17895. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17896. */
  17897. function _getCache( renderer ) {
  17898. let rendererCache = _cache.get( renderer );
  17899. if ( rendererCache === undefined ) {
  17900. rendererCache = new WeakMap();
  17901. _cache.set( renderer, rendererCache );
  17902. }
  17903. return rendererCache;
  17904. }
  17905. /**
  17906. * This node represents a PMREM which is a special type of preprocessed
  17907. * environment map intended for PBR materials.
  17908. *
  17909. * ```js
  17910. * const material = new MeshStandardNodeMaterial();
  17911. * material.envNode = pmremTexture( envMap );
  17912. * ```
  17913. *
  17914. * @augments TempNode
  17915. */
  17916. class PMREMNode extends TempNode {
  17917. static get type() {
  17918. return 'PMREMNode';
  17919. }
  17920. /**
  17921. * Constructs a new function overloading node.
  17922. *
  17923. * @param {Texture} value - The input texture.
  17924. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17925. * @param {Node<float>} [levelNode=null] - The level node.
  17926. */
  17927. constructor( value, uvNode = null, levelNode = null ) {
  17928. super( 'vec3' );
  17929. /**
  17930. * Reference to the input texture.
  17931. *
  17932. * @private
  17933. * @type {Texture}
  17934. */
  17935. this._value = value;
  17936. /**
  17937. * Reference to the generated PMREM.
  17938. *
  17939. * @private
  17940. * @type {Texture | null}
  17941. * @default null
  17942. */
  17943. this._pmrem = null;
  17944. /**
  17945. * The uv node.
  17946. *
  17947. * @type {Node<vec2>}
  17948. */
  17949. this.uvNode = uvNode;
  17950. /**
  17951. * The level node.
  17952. *
  17953. * @type {Node<float>}
  17954. */
  17955. this.levelNode = levelNode;
  17956. /**
  17957. * Reference to a PMREM generator.
  17958. *
  17959. * @private
  17960. * @type {?PMREMGenerator}
  17961. * @default null
  17962. */
  17963. this._generator = null;
  17964. const defaultTexture = new Texture();
  17965. defaultTexture.isRenderTargetTexture = true;
  17966. /**
  17967. * The texture node holding the generated PMREM.
  17968. *
  17969. * @private
  17970. * @type {TextureNode}
  17971. */
  17972. this._texture = texture( defaultTexture );
  17973. /**
  17974. * A uniform representing the PMREM's width.
  17975. *
  17976. * @private
  17977. * @type {UniformNode<float>}
  17978. */
  17979. this._width = uniform( 0 );
  17980. /**
  17981. * A uniform representing the PMREM's height.
  17982. *
  17983. * @private
  17984. * @type {UniformNode<float>}
  17985. */
  17986. this._height = uniform( 0 );
  17987. /**
  17988. * A uniform representing the PMREM's max Mip.
  17989. *
  17990. * @private
  17991. * @type {UniformNode<float>}
  17992. */
  17993. this._maxMip = uniform( 0 );
  17994. /**
  17995. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17996. *
  17997. * @type {string}
  17998. * @default 'render'
  17999. */
  18000. this.updateBeforeType = NodeUpdateType.RENDER;
  18001. }
  18002. set value( value ) {
  18003. this._value = value;
  18004. this._pmrem = null;
  18005. }
  18006. /**
  18007. * The node's texture value.
  18008. *
  18009. * @type {Texture}
  18010. */
  18011. get value() {
  18012. return this._value;
  18013. }
  18014. /**
  18015. * Uses the given PMREM texture to update internal values.
  18016. *
  18017. * @param {Texture} texture - The PMREM texture.
  18018. */
  18019. updateFromTexture( texture ) {
  18020. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18021. this._texture.value = texture;
  18022. this._width.value = cubeUVSize.texelWidth;
  18023. this._height.value = cubeUVSize.texelHeight;
  18024. this._maxMip.value = cubeUVSize.maxMip;
  18025. }
  18026. updateBefore( frame ) {
  18027. let pmrem = this._pmrem;
  18028. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18029. const texture = this._value;
  18030. if ( pmremVersion !== texture.pmremVersion ) {
  18031. if ( texture.isPMREMTexture === true ) {
  18032. pmrem = texture;
  18033. } else {
  18034. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18035. }
  18036. if ( pmrem !== null ) {
  18037. this._pmrem = pmrem;
  18038. this.updateFromTexture( pmrem );
  18039. }
  18040. }
  18041. }
  18042. setup( builder ) {
  18043. if ( this._generator === null ) {
  18044. this._generator = new PMREMGenerator( builder.renderer );
  18045. }
  18046. this.updateBefore( builder );
  18047. //
  18048. let uvNode = this.uvNode;
  18049. if ( uvNode === null && builder.context.getUV ) {
  18050. uvNode = builder.context.getUV( this );
  18051. }
  18052. //
  18053. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18054. //
  18055. let levelNode = this.levelNode;
  18056. if ( levelNode === null && builder.context.getTextureLevel ) {
  18057. levelNode = builder.context.getTextureLevel( this );
  18058. }
  18059. //
  18060. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18061. }
  18062. dispose() {
  18063. super.dispose();
  18064. if ( this._generator !== null ) this._generator.dispose();
  18065. }
  18066. }
  18067. /**
  18068. * Returns `true` if the given cube map image has been fully loaded.
  18069. *
  18070. * @private
  18071. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18072. * @return {boolean} Whether the given cube map is ready or not.
  18073. */
  18074. function isCubeMapReady( image ) {
  18075. if ( image === null || image === undefined ) return false;
  18076. let count = 0;
  18077. const length = 6;
  18078. for ( let i = 0; i < length; i ++ ) {
  18079. if ( image[ i ] !== undefined ) count ++;
  18080. }
  18081. return count === length;
  18082. }
  18083. /**
  18084. * Returns `true` if the given equirectangular image has been fully loaded.
  18085. *
  18086. * @private
  18087. * @param {(Image|Object)} image - The equirectangular image.
  18088. * @return {boolean} Whether the given cube map is ready or not.
  18089. */
  18090. function isEquirectangularMapReady( image ) {
  18091. if ( image === null || image === undefined ) return false;
  18092. return image.height > 0;
  18093. }
  18094. /**
  18095. * TSL function for creating a PMREM node.
  18096. *
  18097. * @tsl
  18098. * @function
  18099. * @param {Texture} value - The input texture.
  18100. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18101. * @param {?Node<float>} [levelNode=null] - The level node.
  18102. * @returns {PMREMNode}
  18103. */
  18104. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18105. const _envNodeCache = new WeakMap();
  18106. /**
  18107. * Represents a physical model for Image-based lighting (IBL). The environment
  18108. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18109. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18110. *
  18111. * @augments LightingNode
  18112. */
  18113. class EnvironmentNode extends LightingNode {
  18114. static get type() {
  18115. return 'EnvironmentNode';
  18116. }
  18117. /**
  18118. * Constructs a new environment node.
  18119. *
  18120. * @param {Node} [envNode=null] - A node representing the environment.
  18121. */
  18122. constructor( envNode = null ) {
  18123. super();
  18124. /**
  18125. * A node representing the environment.
  18126. *
  18127. * @type {?Node}
  18128. * @default null
  18129. */
  18130. this.envNode = envNode;
  18131. }
  18132. setup( builder ) {
  18133. const { material } = builder;
  18134. let envNode = this.envNode;
  18135. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18136. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18137. let cacheEnvNode = _envNodeCache.get( value );
  18138. if ( cacheEnvNode === undefined ) {
  18139. cacheEnvNode = pmremTexture( value );
  18140. _envNodeCache.set( value, cacheEnvNode );
  18141. }
  18142. envNode = cacheEnvNode;
  18143. }
  18144. //
  18145. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18146. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18147. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18148. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18149. const isolateRadiance = isolate( radiance );
  18150. const isolateIrradiance = isolate( irradiance );
  18151. //
  18152. builder.context.radiance.addAssign( isolateRadiance );
  18153. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18154. //
  18155. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18156. if ( clearcoatRadiance ) {
  18157. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18158. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18159. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18160. }
  18161. }
  18162. }
  18163. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18164. let reflectVec = null;
  18165. return {
  18166. getUV: () => {
  18167. if ( reflectVec === null ) {
  18168. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18169. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18170. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18171. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18172. }
  18173. return reflectVec;
  18174. },
  18175. getTextureLevel: () => {
  18176. return roughnessNode;
  18177. }
  18178. };
  18179. };
  18180. const createIrradianceContext = ( normalWorldNode ) => {
  18181. return {
  18182. getUV: () => {
  18183. return normalWorldNode;
  18184. },
  18185. getTextureLevel: () => {
  18186. return float( 1.0 );
  18187. }
  18188. };
  18189. };
  18190. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18191. /**
  18192. * Node material version of {@link MeshStandardMaterial}.
  18193. *
  18194. * @augments NodeMaterial
  18195. */
  18196. class MeshStandardNodeMaterial extends NodeMaterial {
  18197. static get type() {
  18198. return 'MeshStandardNodeMaterial';
  18199. }
  18200. /**
  18201. * Constructs a new mesh standard node material.
  18202. *
  18203. * @param {Object} [parameters] - The configuration parameter.
  18204. */
  18205. constructor( parameters ) {
  18206. super();
  18207. /**
  18208. * This flag can be used for type testing.
  18209. *
  18210. * @type {boolean}
  18211. * @readonly
  18212. * @default true
  18213. */
  18214. this.isMeshStandardNodeMaterial = true;
  18215. /**
  18216. * Set to `true` because standard materials react on lights.
  18217. *
  18218. * @type {boolean}
  18219. * @default true
  18220. */
  18221. this.lights = true;
  18222. /**
  18223. * The emissive color of standard materials is by default inferred from the `emissive`,
  18224. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18225. * overwrite the default and define the emissive color with a node instead.
  18226. *
  18227. * If you don't want to overwrite the emissive color but modify the existing
  18228. * value instead, use {@link materialEmissive}.
  18229. *
  18230. * @type {?Node<vec3>}
  18231. * @default null
  18232. */
  18233. this.emissiveNode = null;
  18234. /**
  18235. * The metalness of standard materials is by default inferred from the `metalness`,
  18236. * and `metalnessMap` properties. This node property allows to
  18237. * overwrite the default and define the metalness with a node instead.
  18238. *
  18239. * If you don't want to overwrite the metalness but modify the existing
  18240. * value instead, use {@link materialMetalness}.
  18241. *
  18242. * @type {?Node<float>}
  18243. * @default null
  18244. */
  18245. this.metalnessNode = null;
  18246. /**
  18247. * The roughness of standard materials is by default inferred from the `roughness`,
  18248. * and `roughnessMap` properties. This node property allows to
  18249. * overwrite the default and define the roughness with a node instead.
  18250. *
  18251. * If you don't want to overwrite the roughness but modify the existing
  18252. * value instead, use {@link materialRoughness}.
  18253. *
  18254. * @type {?Node<float>}
  18255. * @default null
  18256. */
  18257. this.roughnessNode = null;
  18258. this.setDefaultValues( _defaultValues$6 );
  18259. this.setValues( parameters );
  18260. }
  18261. /**
  18262. * Overwritten since this type of material uses {@link EnvironmentNode}
  18263. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18264. * method honors `Scene.environment`.
  18265. *
  18266. * @param {NodeBuilder} builder - The current node builder.
  18267. * @return {?EnvironmentNode<vec3>} The environment node.
  18268. */
  18269. setupEnvironment( builder ) {
  18270. let envNode = super.setupEnvironment( builder );
  18271. if ( envNode === null && builder.environmentNode ) {
  18272. envNode = builder.environmentNode;
  18273. }
  18274. return envNode ? new EnvironmentNode( envNode ) : null;
  18275. }
  18276. /**
  18277. * Setups the lighting model.
  18278. *
  18279. * @return {PhysicalLightingModel} The lighting model.
  18280. */
  18281. setupLightingModel( /*builder*/ ) {
  18282. return new PhysicalLightingModel();
  18283. }
  18284. /**
  18285. * Setups the specular related node variables.
  18286. */
  18287. setupSpecular() {
  18288. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18289. specularColor.assign( specularColorNode );
  18290. specularF90.assign( 1.0 );
  18291. }
  18292. /**
  18293. * Setups the standard specific node variables.
  18294. *
  18295. * @param {NodeBuilder} builder - The current node builder.
  18296. */
  18297. setupVariants() {
  18298. // METALNESS
  18299. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18300. metalness.assign( metalnessNode );
  18301. // ROUGHNESS
  18302. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18303. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18304. roughness.assign( roughnessNode );
  18305. // SPECULAR COLOR
  18306. this.setupSpecular();
  18307. // DIFFUSE COLOR
  18308. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  18309. }
  18310. copy( source ) {
  18311. this.emissiveNode = source.emissiveNode;
  18312. this.metalnessNode = source.metalnessNode;
  18313. this.roughnessNode = source.roughnessNode;
  18314. return super.copy( source );
  18315. }
  18316. }
  18317. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18318. /**
  18319. * Node material version of {@link MeshPhysicalMaterial}.
  18320. *
  18321. * @augments MeshStandardNodeMaterial
  18322. */
  18323. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18324. static get type() {
  18325. return 'MeshPhysicalNodeMaterial';
  18326. }
  18327. /**
  18328. * Constructs a new mesh physical node material.
  18329. *
  18330. * @param {Object} [parameters] - The configuration parameter.
  18331. */
  18332. constructor( parameters ) {
  18333. super();
  18334. /**
  18335. * This flag can be used for type testing.
  18336. *
  18337. * @type {boolean}
  18338. * @readonly
  18339. * @default true
  18340. */
  18341. this.isMeshPhysicalNodeMaterial = true;
  18342. /**
  18343. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18344. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18345. * and define the clearcoat with a node instead.
  18346. *
  18347. * If you don't want to overwrite the clearcoat but modify the existing
  18348. * value instead, use {@link materialClearcoat}.
  18349. *
  18350. * @type {?Node<float>}
  18351. * @default null
  18352. */
  18353. this.clearcoatNode = null;
  18354. /**
  18355. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18356. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18357. * and define the clearcoat roughness with a node instead.
  18358. *
  18359. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18360. * value instead, use {@link materialClearcoatRoughness}.
  18361. *
  18362. * @type {?Node<float>}
  18363. * @default null
  18364. */
  18365. this.clearcoatRoughnessNode = null;
  18366. /**
  18367. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18368. * property. This node property allows to overwrite the default
  18369. * and define the clearcoat normal with a node instead.
  18370. *
  18371. * If you don't want to overwrite the clearcoat normal but modify the existing
  18372. * value instead, use {@link materialClearcoatNormal}.
  18373. *
  18374. * @type {?Node<vec3>}
  18375. * @default null
  18376. */
  18377. this.clearcoatNormalNode = null;
  18378. /**
  18379. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18380. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18381. * and define the sheen with a node instead.
  18382. *
  18383. * If you don't want to overwrite the sheen but modify the existing
  18384. * value instead, use {@link materialSheen}.
  18385. *
  18386. * @type {?Node<vec3>}
  18387. * @default null
  18388. */
  18389. this.sheenNode = null;
  18390. /**
  18391. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18392. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18393. * and define the sheen roughness with a node instead.
  18394. *
  18395. * If you don't want to overwrite the sheen roughness but modify the existing
  18396. * value instead, use {@link materialSheenRoughness}.
  18397. *
  18398. * @type {?Node<float>}
  18399. * @default null
  18400. */
  18401. this.sheenRoughnessNode = null;
  18402. /**
  18403. * The iridescence of physical materials is by default inferred from the `iridescence`
  18404. * property. This node property allows to overwrite the default
  18405. * and define the iridescence with a node instead.
  18406. *
  18407. * If you don't want to overwrite the iridescence but modify the existing
  18408. * value instead, use {@link materialIridescence}.
  18409. *
  18410. * @type {?Node<float>}
  18411. * @default null
  18412. */
  18413. this.iridescenceNode = null;
  18414. /**
  18415. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18416. * property. This node property allows to overwrite the default
  18417. * and define the iridescence IOR with a node instead.
  18418. *
  18419. * If you don't want to overwrite the iridescence IOR but modify the existing
  18420. * value instead, use {@link materialIridescenceIOR}.
  18421. *
  18422. * @type {?Node<float>}
  18423. * @default null
  18424. */
  18425. this.iridescenceIORNode = null;
  18426. /**
  18427. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18428. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18429. * and define the iridescence thickness with a node instead.
  18430. *
  18431. * If you don't want to overwrite the iridescence thickness but modify the existing
  18432. * value instead, use {@link materialIridescenceThickness}.
  18433. *
  18434. * @type {?Node<float>}
  18435. * @default null
  18436. */
  18437. this.iridescenceThicknessNode = null;
  18438. /**
  18439. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18440. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18441. * and define the specular intensity with a node instead.
  18442. *
  18443. * If you don't want to overwrite the specular intensity but modify the existing
  18444. * value instead, use {@link materialSpecularIntensity}.
  18445. *
  18446. * @type {?Node<float>}
  18447. * @default null
  18448. */
  18449. this.specularIntensityNode = null;
  18450. /**
  18451. * The specular color of physical materials is by default inferred from the `specularColor`
  18452. * and `specularColorMap` properties. This node property allows to overwrite the default
  18453. * and define the specular color with a node instead.
  18454. *
  18455. * If you don't want to overwrite the specular color but modify the existing
  18456. * value instead, use {@link materialSpecularColor}.
  18457. *
  18458. * @type {?Node<vec3>}
  18459. * @default null
  18460. */
  18461. this.specularColorNode = null;
  18462. /**
  18463. * The ior of physical materials is by default inferred from the `ior`
  18464. * property. This node property allows to overwrite the default
  18465. * and define the ior with a node instead.
  18466. *
  18467. * If you don't want to overwrite the ior but modify the existing
  18468. * value instead, use {@link materialIOR}.
  18469. *
  18470. * @type {?Node<float>}
  18471. * @default null
  18472. */
  18473. this.iorNode = null;
  18474. /**
  18475. * The transmission of physical materials is by default inferred from the `transmission` and
  18476. * `transmissionMap` properties. This node property allows to overwrite the default
  18477. * and define the transmission with a node instead.
  18478. *
  18479. * If you don't want to overwrite the transmission but modify the existing
  18480. * value instead, use {@link materialTransmission}.
  18481. *
  18482. * @type {?Node<float>}
  18483. * @default null
  18484. */
  18485. this.transmissionNode = null;
  18486. /**
  18487. * The thickness of physical materials is by default inferred from the `thickness` and
  18488. * `thicknessMap` properties. This node property allows to overwrite the default
  18489. * and define the thickness with a node instead.
  18490. *
  18491. * If you don't want to overwrite the thickness but modify the existing
  18492. * value instead, use {@link materialThickness}.
  18493. *
  18494. * @type {?Node<float>}
  18495. * @default null
  18496. */
  18497. this.thicknessNode = null;
  18498. /**
  18499. * The attenuation distance of physical materials is by default inferred from the
  18500. * `attenuationDistance` property. This node property allows to overwrite the default
  18501. * and define the attenuation distance with a node instead.
  18502. *
  18503. * If you don't want to overwrite the attenuation distance but modify the existing
  18504. * value instead, use {@link materialAttenuationDistance}.
  18505. *
  18506. * @type {?Node<float>}
  18507. * @default null
  18508. */
  18509. this.attenuationDistanceNode = null;
  18510. /**
  18511. * The attenuation color of physical materials is by default inferred from the
  18512. * `attenuationColor` property. This node property allows to overwrite the default
  18513. * and define the attenuation color with a node instead.
  18514. *
  18515. * If you don't want to overwrite the attenuation color but modify the existing
  18516. * value instead, use {@link materialAttenuationColor}.
  18517. *
  18518. * @type {?Node<vec3>}
  18519. * @default null
  18520. */
  18521. this.attenuationColorNode = null;
  18522. /**
  18523. * The dispersion of physical materials is by default inferred from the
  18524. * `dispersion` property. This node property allows to overwrite the default
  18525. * and define the dispersion with a node instead.
  18526. *
  18527. * If you don't want to overwrite the dispersion but modify the existing
  18528. * value instead, use {@link materialDispersion}.
  18529. *
  18530. * @type {?Node<float>}
  18531. * @default null
  18532. */
  18533. this.dispersionNode = null;
  18534. /**
  18535. * The anisotropy of physical materials is by default inferred from the
  18536. * `anisotropy` property. This node property allows to overwrite the default
  18537. * and define the anisotropy with a node instead.
  18538. *
  18539. * If you don't want to overwrite the anisotropy but modify the existing
  18540. * value instead, use {@link materialAnisotropy}.
  18541. *
  18542. * @type {?Node<float>}
  18543. * @default null
  18544. */
  18545. this.anisotropyNode = null;
  18546. this.setDefaultValues( _defaultValues$5 );
  18547. this.setValues( parameters );
  18548. }
  18549. /**
  18550. * Whether the lighting model should use clearcoat or not.
  18551. *
  18552. * @type {boolean}
  18553. * @default true
  18554. */
  18555. get useClearcoat() {
  18556. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18557. }
  18558. /**
  18559. * Whether the lighting model should use iridescence or not.
  18560. *
  18561. * @type {boolean}
  18562. * @default true
  18563. */
  18564. get useIridescence() {
  18565. return this.iridescence > 0 || this.iridescenceNode !== null;
  18566. }
  18567. /**
  18568. * Whether the lighting model should use sheen or not.
  18569. *
  18570. * @type {boolean}
  18571. * @default true
  18572. */
  18573. get useSheen() {
  18574. return this.sheen > 0 || this.sheenNode !== null;
  18575. }
  18576. /**
  18577. * Whether the lighting model should use anisotropy or not.
  18578. *
  18579. * @type {boolean}
  18580. * @default true
  18581. */
  18582. get useAnisotropy() {
  18583. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18584. }
  18585. /**
  18586. * Whether the lighting model should use transmission or not.
  18587. *
  18588. * @type {boolean}
  18589. * @default true
  18590. */
  18591. get useTransmission() {
  18592. return this.transmission > 0 || this.transmissionNode !== null;
  18593. }
  18594. /**
  18595. * Whether the lighting model should use dispersion or not.
  18596. *
  18597. * @type {boolean}
  18598. * @default true
  18599. */
  18600. get useDispersion() {
  18601. return this.dispersion > 0 || this.dispersionNode !== null;
  18602. }
  18603. /**
  18604. * Setups the specular related node variables.
  18605. */
  18606. setupSpecular() {
  18607. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18608. ior.assign( iorNode );
  18609. 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 ) );
  18610. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18611. }
  18612. /**
  18613. * Setups the lighting model.
  18614. *
  18615. * @return {PhysicalLightingModel} The lighting model.
  18616. */
  18617. setupLightingModel( /*builder*/ ) {
  18618. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18619. }
  18620. /**
  18621. * Setups the physical specific node variables.
  18622. *
  18623. * @param {NodeBuilder} builder - The current node builder.
  18624. */
  18625. setupVariants( builder ) {
  18626. super.setupVariants( builder );
  18627. // CLEARCOAT
  18628. if ( this.useClearcoat ) {
  18629. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18630. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18631. clearcoat.assign( clearcoatNode );
  18632. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18633. }
  18634. // SHEEN
  18635. if ( this.useSheen ) {
  18636. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18637. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18638. sheen.assign( sheenNode );
  18639. sheenRoughness.assign( sheenRoughnessNode );
  18640. }
  18641. // IRIDESCENCE
  18642. if ( this.useIridescence ) {
  18643. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18644. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18645. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18646. iridescence.assign( iridescenceNode );
  18647. iridescenceIOR.assign( iridescenceIORNode );
  18648. iridescenceThickness.assign( iridescenceThicknessNode );
  18649. }
  18650. // ANISOTROPY
  18651. if ( this.useAnisotropy ) {
  18652. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18653. anisotropy.assign( anisotropyV.length() );
  18654. If( anisotropy.equal( 0.0 ), () => {
  18655. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18656. } ).Else( () => {
  18657. anisotropyV.divAssign( vec2( anisotropy ) );
  18658. anisotropy.assign( anisotropy.saturate() );
  18659. } );
  18660. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18661. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18662. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18663. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18664. }
  18665. // TRANSMISSION
  18666. if ( this.useTransmission ) {
  18667. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18668. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18669. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18670. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18671. transmission.assign( transmissionNode );
  18672. thickness.assign( thicknessNode );
  18673. attenuationDistance.assign( attenuationDistanceNode );
  18674. attenuationColor.assign( attenuationColorNode );
  18675. if ( this.useDispersion ) {
  18676. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18677. dispersion.assign( dispersionNode );
  18678. }
  18679. }
  18680. }
  18681. /**
  18682. * Setups the clearcoat normal node.
  18683. *
  18684. * @return {Node<vec3>} The clearcoat normal.
  18685. */
  18686. setupClearcoatNormal() {
  18687. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18688. }
  18689. setup( builder ) {
  18690. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18691. super.setup( builder );
  18692. }
  18693. copy( source ) {
  18694. this.clearcoatNode = source.clearcoatNode;
  18695. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18696. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18697. this.sheenNode = source.sheenNode;
  18698. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18699. this.iridescenceNode = source.iridescenceNode;
  18700. this.iridescenceIORNode = source.iridescenceIORNode;
  18701. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18702. this.specularIntensityNode = source.specularIntensityNode;
  18703. this.specularColorNode = source.specularColorNode;
  18704. this.transmissionNode = source.transmissionNode;
  18705. this.thicknessNode = source.thicknessNode;
  18706. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18707. this.attenuationColorNode = source.attenuationColorNode;
  18708. this.dispersionNode = source.dispersionNode;
  18709. this.anisotropyNode = source.anisotropyNode;
  18710. return super.copy( source );
  18711. }
  18712. }
  18713. /**
  18714. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18715. *
  18716. * @augments PhysicalLightingModel
  18717. */
  18718. class SSSLightingModel extends PhysicalLightingModel {
  18719. /**
  18720. * Constructs a new physical lighting model.
  18721. *
  18722. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18723. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18724. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18725. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18726. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18727. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18728. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18729. */
  18730. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18731. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18732. /**
  18733. * Whether the lighting model should use SSS or not.
  18734. *
  18735. * @type {boolean}
  18736. * @default false
  18737. */
  18738. this.useSSS = sss;
  18739. }
  18740. /**
  18741. * Extends the default implementation with a SSS term.
  18742. *
  18743. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look]{@link https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/}
  18744. *
  18745. * @param {Object} input - The input data.
  18746. * @param {NodeBuilder} builder - The current node builder.
  18747. */
  18748. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18749. if ( this.useSSS === true ) {
  18750. const material = builder.material;
  18751. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18752. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18753. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18754. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18755. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18756. }
  18757. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18758. }
  18759. }
  18760. /**
  18761. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18762. * that implements a Subsurface scattering (SSS) term.
  18763. *
  18764. * @augments MeshPhysicalNodeMaterial
  18765. */
  18766. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18767. static get type() {
  18768. return 'MeshSSSNodeMaterial';
  18769. }
  18770. /**
  18771. * Constructs a new mesh SSS node material.
  18772. *
  18773. * @param {Object} [parameters] - The configuration parameter.
  18774. */
  18775. constructor( parameters ) {
  18776. super( parameters );
  18777. /**
  18778. * Represents the thickness color.
  18779. *
  18780. * @type {?Node<vec3>}
  18781. * @default null
  18782. */
  18783. this.thicknessColorNode = null;
  18784. /**
  18785. * Represents the distortion factor.
  18786. *
  18787. * @type {?Node<float>}
  18788. */
  18789. this.thicknessDistortionNode = float( 0.1 );
  18790. /**
  18791. * Represents the thickness ambient factor.
  18792. *
  18793. * @type {?Node<float>}
  18794. */
  18795. this.thicknessAmbientNode = float( 0.0 );
  18796. /**
  18797. * Represents the thickness attenuation.
  18798. *
  18799. * @type {?Node<float>}
  18800. */
  18801. this.thicknessAttenuationNode = float( .1 );
  18802. /**
  18803. * Represents the thickness power.
  18804. *
  18805. * @type {?Node<float>}
  18806. */
  18807. this.thicknessPowerNode = float( 2.0 );
  18808. /**
  18809. * Represents the thickness scale.
  18810. *
  18811. * @type {?Node<float>}
  18812. */
  18813. this.thicknessScaleNode = float( 10.0 );
  18814. }
  18815. /**
  18816. * Whether the lighting model should use SSS or not.
  18817. *
  18818. * @type {boolean}
  18819. * @default true
  18820. */
  18821. get useSSS() {
  18822. return this.thicknessColorNode !== null;
  18823. }
  18824. /**
  18825. * Setups the lighting model.
  18826. *
  18827. * @return {SSSLightingModel} The lighting model.
  18828. */
  18829. setupLightingModel( /*builder*/ ) {
  18830. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18831. }
  18832. copy( source ) {
  18833. this.thicknessColorNode = source.thicknessColorNode;
  18834. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18835. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18836. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18837. this.thicknessPowerNode = source.thicknessPowerNode;
  18838. this.thicknessScaleNode = source.thicknessScaleNode;
  18839. return super.copy( source );
  18840. }
  18841. }
  18842. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18843. // dotNL will be from -1.0 to 1.0
  18844. const dotNL = normal.dot( lightDirection );
  18845. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18846. if ( builder.material.gradientMap ) {
  18847. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18848. return vec3( gradientMap.r );
  18849. } else {
  18850. const fw = coord.fwidth().mul( 0.5 );
  18851. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18852. }
  18853. } );
  18854. /**
  18855. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18856. *
  18857. * @augments LightingModel
  18858. */
  18859. class ToonLightingModel extends LightingModel {
  18860. /**
  18861. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18862. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18863. *
  18864. * @param {Object} lightData - The light data.
  18865. * @param {NodeBuilder} builder - The current node builder.
  18866. */
  18867. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18868. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18869. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18870. }
  18871. /**
  18872. * Implements the indirect lighting.
  18873. *
  18874. * @param {NodeBuilder} builder - The current node builder.
  18875. */
  18876. indirect( builder ) {
  18877. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18878. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18879. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18880. }
  18881. }
  18882. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18883. /**
  18884. * Node material version of {@link MeshToonMaterial}.
  18885. *
  18886. * @augments NodeMaterial
  18887. */
  18888. class MeshToonNodeMaterial extends NodeMaterial {
  18889. static get type() {
  18890. return 'MeshToonNodeMaterial';
  18891. }
  18892. /**
  18893. * Constructs a new mesh toon node material.
  18894. *
  18895. * @param {Object} [parameters] - The configuration parameter.
  18896. */
  18897. constructor( parameters ) {
  18898. super();
  18899. /**
  18900. * This flag can be used for type testing.
  18901. *
  18902. * @type {boolean}
  18903. * @readonly
  18904. * @default true
  18905. */
  18906. this.isMeshToonNodeMaterial = true;
  18907. /**
  18908. * Set to `true` because toon materials react on lights.
  18909. *
  18910. * @type {boolean}
  18911. * @default true
  18912. */
  18913. this.lights = true;
  18914. this.setDefaultValues( _defaultValues$4 );
  18915. this.setValues( parameters );
  18916. }
  18917. /**
  18918. * Setups the lighting model.
  18919. *
  18920. * @return {ToonLightingModel} The lighting model.
  18921. */
  18922. setupLightingModel( /*builder*/ ) {
  18923. return new ToonLightingModel();
  18924. }
  18925. }
  18926. /**
  18927. * TSL function for creating a matcap uv node.
  18928. *
  18929. * Can be used to compute texture coordinates for projecting a
  18930. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18931. *
  18932. * @tsl
  18933. * @function
  18934. * @returns {Node<vec2>} The matcap UV coordinates.
  18935. */
  18936. const matcapUV = /*@__PURE__*/ Fn( () => {
  18937. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18938. const y = positionViewDirection.cross( x );
  18939. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18940. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18941. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18942. /**
  18943. * Node material version of {@link MeshMatcapMaterial}.
  18944. *
  18945. * @augments NodeMaterial
  18946. */
  18947. class MeshMatcapNodeMaterial extends NodeMaterial {
  18948. static get type() {
  18949. return 'MeshMatcapNodeMaterial';
  18950. }
  18951. /**
  18952. * Constructs a new mesh normal node material.
  18953. *
  18954. * @param {Object} [parameters] - The configuration parameter.
  18955. */
  18956. constructor( parameters ) {
  18957. super();
  18958. /**
  18959. * This flag can be used for type testing.
  18960. *
  18961. * @type {boolean}
  18962. * @readonly
  18963. * @default true
  18964. */
  18965. this.isMeshMatcapNodeMaterial = true;
  18966. this.setDefaultValues( _defaultValues$3 );
  18967. this.setValues( parameters );
  18968. }
  18969. /**
  18970. * Setups the matcap specific node variables.
  18971. *
  18972. * @param {NodeBuilder} builder - The current node builder.
  18973. */
  18974. setupVariants( builder ) {
  18975. const uv = matcapUV;
  18976. let matcapColor;
  18977. if ( builder.material.matcap ) {
  18978. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18979. } else {
  18980. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18981. }
  18982. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18983. }
  18984. }
  18985. /**
  18986. * Applies a rotation to the given position node.
  18987. *
  18988. * @augments TempNode
  18989. */
  18990. class RotateNode extends TempNode {
  18991. static get type() {
  18992. return 'RotateNode';
  18993. }
  18994. /**
  18995. * Constructs a new rotate node.
  18996. *
  18997. * @param {Node} positionNode - The position node.
  18998. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18999. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19000. */
  19001. constructor( positionNode, rotationNode ) {
  19002. super();
  19003. /**
  19004. * The position node.
  19005. *
  19006. * @type {Node}
  19007. */
  19008. this.positionNode = positionNode;
  19009. /**
  19010. * Represents the rotation that is applied to the position node.
  19011. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19012. *
  19013. * @type {Node}
  19014. */
  19015. this.rotationNode = rotationNode;
  19016. }
  19017. /**
  19018. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19019. *
  19020. * @param {NodeBuilder} builder - The current node builder.
  19021. * @return {string} The node's type.
  19022. */
  19023. getNodeType( builder ) {
  19024. return this.positionNode.getNodeType( builder );
  19025. }
  19026. setup( builder ) {
  19027. const { rotationNode, positionNode } = this;
  19028. const nodeType = this.getNodeType( builder );
  19029. if ( nodeType === 'vec2' ) {
  19030. const cosAngle = rotationNode.cos();
  19031. const sinAngle = rotationNode.sin();
  19032. const rotationMatrix = mat2(
  19033. cosAngle, sinAngle,
  19034. sinAngle.negate(), cosAngle
  19035. );
  19036. return rotationMatrix.mul( positionNode );
  19037. } else {
  19038. const rotation = rotationNode;
  19039. 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 ) );
  19040. 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 ) );
  19041. 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 ) );
  19042. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19043. }
  19044. }
  19045. }
  19046. /**
  19047. * TSL function for creating a rotate node.
  19048. *
  19049. * @tsl
  19050. * @function
  19051. * @param {Node} positionNode - The position node.
  19052. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19053. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19054. * @returns {RotateNode}
  19055. */
  19056. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19057. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19058. /**
  19059. * Node material version of {@link SpriteMaterial}.
  19060. *
  19061. * @augments NodeMaterial
  19062. */
  19063. class SpriteNodeMaterial extends NodeMaterial {
  19064. static get type() {
  19065. return 'SpriteNodeMaterial';
  19066. }
  19067. /**
  19068. * Constructs a new sprite node material.
  19069. *
  19070. * @param {Object} [parameters] - The configuration parameter.
  19071. */
  19072. constructor( parameters ) {
  19073. super();
  19074. /**
  19075. * This flag can be used for type testing.
  19076. *
  19077. * @type {boolean}
  19078. * @readonly
  19079. * @default true
  19080. */
  19081. this.isSpriteNodeMaterial = true;
  19082. this._useSizeAttenuation = true;
  19083. /**
  19084. * This property makes it possible to define the position of the sprite with a
  19085. * node. That can be useful when the material is used with instanced rendering
  19086. * and node data are defined with an instanced attribute node:
  19087. * ```js
  19088. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19089. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19090. * ```
  19091. * Another possibility is to compute the instanced data with a compute shader:
  19092. * ```js
  19093. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19094. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19095. * ```
  19096. *
  19097. * @type {?Node<vec2>}
  19098. * @default null
  19099. */
  19100. this.positionNode = null;
  19101. /**
  19102. * The rotation of sprite materials is by default inferred from the `rotation`,
  19103. * property. This node property allows to overwrite the default and define
  19104. * the rotation with a node instead.
  19105. *
  19106. * If you don't want to overwrite the rotation but modify the existing
  19107. * value instead, use {@link materialRotation}.
  19108. *
  19109. * @type {?Node<float>}
  19110. * @default null
  19111. */
  19112. this.rotationNode = null;
  19113. /**
  19114. * This node property provides an additional way to scale sprites next to
  19115. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19116. * is multiplied with the scale value of this node in the vertex shader.
  19117. *
  19118. * @type {?Node<vec2>}
  19119. * @default null
  19120. */
  19121. this.scaleNode = null;
  19122. /**
  19123. * In Sprites, the transparent property is enabled by default.
  19124. *
  19125. * @type {boolean}
  19126. * @default true
  19127. */
  19128. this.transparent = true;
  19129. this.setDefaultValues( _defaultValues$2 );
  19130. this.setValues( parameters );
  19131. }
  19132. /**
  19133. * Setups the position node in view space. This method implements
  19134. * the sprite specific vertex shader.
  19135. *
  19136. * @param {NodeBuilder} builder - The current node builder.
  19137. * @return {Node<vec3>} The position in view space.
  19138. */
  19139. setupPositionView( builder ) {
  19140. const { object, camera } = builder;
  19141. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19142. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19143. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19144. if ( scaleNode !== null ) {
  19145. scale = scale.mul( vec2( scaleNode ) );
  19146. }
  19147. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19148. scale = scale.mul( mvPosition.z.negate() );
  19149. }
  19150. let alignedPosition = positionGeometry.xy;
  19151. if ( object.center && object.center.isVector2 === true ) {
  19152. const center = reference$1( 'center', 'vec2', object );
  19153. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19154. }
  19155. alignedPosition = alignedPosition.mul( scale );
  19156. const rotation = float( rotationNode || materialRotation );
  19157. const rotatedPosition = rotate( alignedPosition, rotation );
  19158. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19159. }
  19160. copy( source ) {
  19161. this.positionNode = source.positionNode;
  19162. this.rotationNode = source.rotationNode;
  19163. this.scaleNode = source.scaleNode;
  19164. return super.copy( source );
  19165. }
  19166. /**
  19167. * Whether to use size attenuation or not.
  19168. *
  19169. * @type {boolean}
  19170. * @default true
  19171. */
  19172. get sizeAttenuation() {
  19173. return this._useSizeAttenuation;
  19174. }
  19175. set sizeAttenuation( value ) {
  19176. if ( this._useSizeAttenuation !== value ) {
  19177. this._useSizeAttenuation = value;
  19178. this.needsUpdate = true;
  19179. }
  19180. }
  19181. }
  19182. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19183. const _size$4 = /*@__PURE__*/ new Vector2();
  19184. /**
  19185. * Node material version of {@link PointsMaterial}.
  19186. *
  19187. * This material can be used in two ways:
  19188. *
  19189. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19190. * with a pixel size of `1`, it's not possible to define a size.
  19191. *
  19192. * ```js
  19193. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19194. * ```
  19195. *
  19196. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19197. * see {@link PointsNodeMaterial#sizeNode}.
  19198. *
  19199. * ```js
  19200. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19201. * ```
  19202. *
  19203. * @augments SpriteNodeMaterial
  19204. */
  19205. class PointsNodeMaterial extends SpriteNodeMaterial {
  19206. static get type() {
  19207. return 'PointsNodeMaterial';
  19208. }
  19209. /**
  19210. * Constructs a new points node material.
  19211. *
  19212. * @param {Object} [parameters] - The configuration parameter.
  19213. */
  19214. constructor( parameters ) {
  19215. super();
  19216. /**
  19217. * This node property provides an additional way to set the point size.
  19218. *
  19219. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19220. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19221. * backend. If an application wants to render points with a size larger than 1 pixel,
  19222. * the material should be used with {@link Sprite} and instancing.
  19223. *
  19224. * @type {?Node<vec2>}
  19225. * @default null
  19226. */
  19227. this.sizeNode = null;
  19228. /**
  19229. * This flag can be used for type testing.
  19230. *
  19231. * @type {boolean}
  19232. * @readonly
  19233. * @default true
  19234. */
  19235. this.isPointsNodeMaterial = true;
  19236. this.setDefaultValues( _defaultValues$1 );
  19237. this.setValues( parameters );
  19238. }
  19239. setupPositionView() {
  19240. const { positionNode } = this;
  19241. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19242. }
  19243. setupVertexSprite( builder ) {
  19244. const { material, camera } = builder;
  19245. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19246. let mvp = super.setupVertex( builder );
  19247. // skip further processing if the material is not a node material
  19248. if ( material.isNodeMaterial !== true ) {
  19249. return mvp;
  19250. }
  19251. // point size
  19252. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19253. pointSize = pointSize.mul( screenDPR );
  19254. // size attenuation
  19255. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19256. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19257. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19258. }
  19259. // scale
  19260. if ( scaleNode && scaleNode.isNode ) {
  19261. pointSize = pointSize.mul( vec2( scaleNode ) );
  19262. }
  19263. // compute offset
  19264. let offset = positionGeometry.xy;
  19265. // apply rotation
  19266. if ( rotationNode && rotationNode.isNode ) {
  19267. const rotation = float( rotationNode );
  19268. offset = rotate( offset, rotation );
  19269. }
  19270. // account for point size
  19271. offset = offset.mul( pointSize );
  19272. // scale by viewport size
  19273. offset = offset.div( viewportSize.div( 2 ) );
  19274. // compensate for the perspective divide
  19275. offset = offset.mul( mvp.w );
  19276. // add offset
  19277. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19278. return mvp;
  19279. }
  19280. setupVertex( builder ) {
  19281. if ( builder.object.isPoints ) {
  19282. return super.setupVertex( builder );
  19283. } else {
  19284. return this.setupVertexSprite( builder );
  19285. }
  19286. }
  19287. /**
  19288. * Whether alpha to coverage should be used or not.
  19289. *
  19290. * @type {boolean}
  19291. * @default true
  19292. */
  19293. get alphaToCoverage() {
  19294. return this._useAlphaToCoverage;
  19295. }
  19296. set alphaToCoverage( value ) {
  19297. if ( this._useAlphaToCoverage !== value ) {
  19298. this._useAlphaToCoverage = value;
  19299. this.needsUpdate = true;
  19300. }
  19301. }
  19302. }
  19303. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19304. const size = renderer.getSize( _size$4 ); // logical units
  19305. this.value = 0.5 * size.y;
  19306. } );
  19307. /**
  19308. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19309. *
  19310. * @augments LightingModel
  19311. */
  19312. class ShadowMaskModel extends LightingModel {
  19313. /**
  19314. * Constructs a new shadow mask model.
  19315. */
  19316. constructor() {
  19317. super();
  19318. /**
  19319. * The shadow mask node.
  19320. *
  19321. * @type {Node}
  19322. */
  19323. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19324. }
  19325. /**
  19326. * Only used to save the shadow mask.
  19327. *
  19328. * @param {Object} input - The input data.
  19329. */
  19330. direct( { lightNode } ) {
  19331. if ( lightNode.shadowNode !== null ) {
  19332. this.shadowNode.mulAssign( lightNode.shadowNode );
  19333. }
  19334. }
  19335. /**
  19336. * Uses the shadow mask to produce the final color.
  19337. *
  19338. * @param {NodeBuilder} builder - The current node builder.
  19339. */
  19340. finish( { context } ) {
  19341. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19342. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19343. }
  19344. }
  19345. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19346. /**
  19347. * Node material version of {@link ShadowMaterial}.
  19348. *
  19349. * @augments NodeMaterial
  19350. */
  19351. class ShadowNodeMaterial extends NodeMaterial {
  19352. static get type() {
  19353. return 'ShadowNodeMaterial';
  19354. }
  19355. /**
  19356. * Constructs a new shadow node material.
  19357. *
  19358. * @param {Object} [parameters] - The configuration parameter.
  19359. */
  19360. constructor( parameters ) {
  19361. super();
  19362. /**
  19363. * This flag can be used for type testing.
  19364. *
  19365. * @type {boolean}
  19366. * @readonly
  19367. * @default true
  19368. */
  19369. this.isShadowNodeMaterial = true;
  19370. /**
  19371. * Set to `true` because so it's possible to implement
  19372. * the shadow mask effect.
  19373. *
  19374. * @type {boolean}
  19375. * @default true
  19376. */
  19377. this.lights = true;
  19378. /**
  19379. * Overwritten since shadow materials are transparent
  19380. * by default.
  19381. *
  19382. * @type {boolean}
  19383. * @default true
  19384. */
  19385. this.transparent = true;
  19386. this.setDefaultValues( _defaultValues );
  19387. this.setValues( parameters );
  19388. }
  19389. /**
  19390. * Setups the lighting model.
  19391. *
  19392. * @return {ShadowMaskModel} The lighting model.
  19393. */
  19394. setupLightingModel( /*builder*/ ) {
  19395. return new ShadowMaskModel();
  19396. }
  19397. }
  19398. const scatteringDensity = property( 'vec3' );
  19399. const linearDepthRay = property( 'vec3' );
  19400. const outgoingRayLight = property( 'vec3' );
  19401. /**
  19402. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19403. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19404. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19405. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19406. *
  19407. * @augments LightingModel
  19408. */
  19409. class VolumetricLightingModel extends LightingModel {
  19410. constructor() {
  19411. super();
  19412. }
  19413. start( builder ) {
  19414. const { material, context } = builder;
  19415. const startPos = property( 'vec3' );
  19416. const endPos = property( 'vec3' );
  19417. // This approach dynamically changes the direction of the ray,
  19418. // 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.
  19419. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19420. startPos.assign( cameraPosition );
  19421. endPos.assign( positionWorld );
  19422. } ).Else( () => {
  19423. startPos.assign( positionWorld );
  19424. endPos.assign( cameraPosition );
  19425. } );
  19426. //
  19427. const viewVector = endPos.sub( startPos );
  19428. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19429. const stepSize = viewVector.length().div( steps ).toVar();
  19430. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19431. const distTravelled = float( 0.0 ).toVar();
  19432. const transmittance = vec3( 1 ).toVar();
  19433. if ( material.offsetNode ) {
  19434. // reduce banding
  19435. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19436. }
  19437. Loop( steps, () => {
  19438. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19439. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19440. if ( material.depthNode !== null ) {
  19441. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19442. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19443. }
  19444. context.positionWorld = positionRay;
  19445. context.shadowPositionWorld = positionRay;
  19446. context.positionView = positionViewRay;
  19447. scatteringDensity.assign( 0 );
  19448. let scatteringNode;
  19449. if ( material.scatteringNode ) {
  19450. scatteringNode = material.scatteringNode( {
  19451. positionRay
  19452. } );
  19453. }
  19454. super.start( builder );
  19455. if ( scatteringNode ) {
  19456. scatteringDensity.mulAssign( scatteringNode );
  19457. }
  19458. // beer's law
  19459. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19460. transmittance.mulAssign( falloff );
  19461. // move along the ray
  19462. distTravelled.addAssign( stepSize );
  19463. } );
  19464. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19465. }
  19466. scatteringLight( lightColor, builder ) {
  19467. const sceneDepthNode = builder.context.sceneDepthNode;
  19468. if ( sceneDepthNode ) {
  19469. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19470. scatteringDensity.addAssign( lightColor );
  19471. } );
  19472. } else {
  19473. scatteringDensity.addAssign( lightColor );
  19474. }
  19475. }
  19476. direct( { lightNode, lightColor }, builder ) {
  19477. // Ignore lights with infinite distance
  19478. if ( lightNode.light.distance === undefined ) return;
  19479. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19480. const directLight = lightColor.xyz.toVar();
  19481. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19482. this.scatteringLight( directLight, builder );
  19483. }
  19484. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19485. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19486. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19487. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19488. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19489. const P = builder.context.positionView;
  19490. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19491. this.scatteringLight( directLight, builder );
  19492. }
  19493. finish( builder ) {
  19494. builder.context.outgoingLight.assign( outgoingRayLight );
  19495. }
  19496. }
  19497. /**
  19498. * Volume node material.
  19499. *
  19500. * @augments NodeMaterial
  19501. */
  19502. class VolumeNodeMaterial extends NodeMaterial {
  19503. static get type() {
  19504. return 'VolumeNodeMaterial';
  19505. }
  19506. /**
  19507. * Constructs a new volume node material.
  19508. *
  19509. * @param {Object} [parameters] - The configuration parameter.
  19510. */
  19511. constructor( parameters ) {
  19512. super();
  19513. /**
  19514. * This flag can be used for type testing.
  19515. *
  19516. * @type {boolean}
  19517. * @readonly
  19518. * @default true
  19519. */
  19520. this.isVolumeNodeMaterial = true;
  19521. /**
  19522. * Number of steps used for raymarching.
  19523. *
  19524. * @type {number}
  19525. * @default 25
  19526. */
  19527. this.steps = 25;
  19528. /**
  19529. * Offsets the distance a ray has been traveled through a volume.
  19530. * Can be used to implement dithering to reduce banding.
  19531. *
  19532. * @type {Node<float>}
  19533. * @default null
  19534. */
  19535. this.offsetNode = null;
  19536. /**
  19537. * Node used for scattering calculations.
  19538. *
  19539. * @type {Function|FunctionNode<vec4>}
  19540. * @default null
  19541. */
  19542. this.scatteringNode = null;
  19543. this.lights = true;
  19544. this.transparent = true;
  19545. this.side = BackSide;
  19546. this.depthTest = false;
  19547. this.depthWrite = false;
  19548. this.setValues( parameters );
  19549. }
  19550. setupLightingModel() {
  19551. return new VolumetricLightingModel();
  19552. }
  19553. }
  19554. /**
  19555. * This module manages the internal animation loop of the renderer.
  19556. *
  19557. * @private
  19558. */
  19559. class Animation {
  19560. /**
  19561. * Constructs a new animation loop management component.
  19562. *
  19563. * @param {Renderer} renderer - A reference to the main renderer.
  19564. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19565. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19566. */
  19567. constructor( renderer, nodes, info ) {
  19568. /**
  19569. * A reference to the main renderer.
  19570. *
  19571. * @type {Renderer}
  19572. */
  19573. this.renderer = renderer;
  19574. /**
  19575. * Renderer component for managing nodes related logic.
  19576. *
  19577. * @type {Nodes}
  19578. */
  19579. this.nodes = nodes;
  19580. /**
  19581. * Renderer component for managing metrics and monitoring data.
  19582. *
  19583. * @type {Info}
  19584. */
  19585. this.info = info;
  19586. /**
  19587. * A reference to the context from `requestAnimationFrame()` can
  19588. * be called (usually `window`).
  19589. *
  19590. * @type {?(Window|XRSession)}
  19591. */
  19592. this._context = typeof self !== 'undefined' ? self : null;
  19593. /**
  19594. * The user-defined animation loop.
  19595. *
  19596. * @type {?Function}
  19597. * @default null
  19598. */
  19599. this._animationLoop = null;
  19600. /**
  19601. * The requestId which is returned from the `requestAnimationFrame()` call.
  19602. * Can be used to cancel the stop the animation loop.
  19603. *
  19604. * @type {?number}
  19605. * @default null
  19606. */
  19607. this._requestId = null;
  19608. }
  19609. /**
  19610. * Starts the internal animation loop.
  19611. */
  19612. start() {
  19613. const update = ( time, xrFrame ) => {
  19614. this._requestId = this._context.requestAnimationFrame( update );
  19615. if ( this.info.autoReset === true ) this.info.reset();
  19616. this.nodes.nodeFrame.update();
  19617. this.info.frame = this.nodes.nodeFrame.frameId;
  19618. this.renderer._inspector.begin();
  19619. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19620. this.renderer._inspector.finish();
  19621. };
  19622. update();
  19623. }
  19624. /**
  19625. * Stops the internal animation loop.
  19626. */
  19627. stop() {
  19628. this._context.cancelAnimationFrame( this._requestId );
  19629. this._requestId = null;
  19630. }
  19631. /**
  19632. * Returns the user-level animation loop.
  19633. *
  19634. * @return {?Function} The animation loop.
  19635. */
  19636. getAnimationLoop() {
  19637. return this._animationLoop;
  19638. }
  19639. /**
  19640. * Defines the user-level animation loop.
  19641. *
  19642. * @param {?Function} callback - The animation loop.
  19643. */
  19644. setAnimationLoop( callback ) {
  19645. this._animationLoop = callback;
  19646. }
  19647. /**
  19648. * Returns the animation context.
  19649. *
  19650. * @return {Window|XRSession} The animation context.
  19651. */
  19652. getContext() {
  19653. return this._context;
  19654. }
  19655. /**
  19656. * Defines the context in which `requestAnimationFrame()` is executed.
  19657. *
  19658. * @param {Window|XRSession} context - The context to set.
  19659. */
  19660. setContext( context ) {
  19661. this._context = context;
  19662. }
  19663. /**
  19664. * Frees all internal resources and stops the animation loop.
  19665. */
  19666. dispose() {
  19667. this.stop();
  19668. }
  19669. }
  19670. /**
  19671. * Data structure for the renderer. It allows defining values
  19672. * with chained, hierarchical keys. Keys are meant to be
  19673. * objects since the module internally works with Weak Maps
  19674. * for performance reasons.
  19675. *
  19676. * @private
  19677. */
  19678. class ChainMap {
  19679. /**
  19680. * Constructs a new Chain Map.
  19681. */
  19682. constructor() {
  19683. /**
  19684. * The root Weak Map.
  19685. *
  19686. * @type {WeakMap<Object, WeakMap>}
  19687. */
  19688. this.weakMap = new WeakMap();
  19689. }
  19690. /**
  19691. * Returns the value for the given array of keys.
  19692. *
  19693. * @param {Array<Object>} keys - List of keys.
  19694. * @return {any} The value. Returns `undefined` if no value was found.
  19695. */
  19696. get( keys ) {
  19697. let map = this.weakMap;
  19698. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19699. map = map.get( keys[ i ] );
  19700. if ( map === undefined ) return undefined;
  19701. }
  19702. return map.get( keys[ keys.length - 1 ] );
  19703. }
  19704. /**
  19705. * Sets the value for the given keys.
  19706. *
  19707. * @param {Array<Object>} keys - List of keys.
  19708. * @param {any} value - The value to set.
  19709. * @return {ChainMap} A reference to this Chain Map.
  19710. */
  19711. set( keys, value ) {
  19712. let map = this.weakMap;
  19713. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19714. const key = keys[ i ];
  19715. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19716. map = map.get( key );
  19717. }
  19718. map.set( keys[ keys.length - 1 ], value );
  19719. return this;
  19720. }
  19721. /**
  19722. * Deletes a value for the given keys.
  19723. *
  19724. * @param {Array<Object>} keys - The keys.
  19725. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19726. */
  19727. delete( keys ) {
  19728. let map = this.weakMap;
  19729. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19730. map = map.get( keys[ i ] );
  19731. if ( map === undefined ) return false;
  19732. }
  19733. return map.delete( keys[ keys.length - 1 ] );
  19734. }
  19735. }
  19736. let _id$9 = 0;
  19737. function getKeys( obj ) {
  19738. const keys = Object.keys( obj );
  19739. let proto = Object.getPrototypeOf( obj );
  19740. while ( proto ) {
  19741. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19742. for ( const key in descriptors ) {
  19743. if ( descriptors[ key ] !== undefined ) {
  19744. const descriptor = descriptors[ key ];
  19745. if ( descriptor && typeof descriptor.get === 'function' ) {
  19746. keys.push( key );
  19747. }
  19748. }
  19749. }
  19750. proto = Object.getPrototypeOf( proto );
  19751. }
  19752. return keys;
  19753. }
  19754. /**
  19755. * A render object is the renderer's representation of single entity that gets drawn
  19756. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19757. * scene since render objects also depend from the used material, the current render context
  19758. * and the current scene's lighting.
  19759. *
  19760. * In general, the basic process of the renderer is:
  19761. *
  19762. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19763. * - Process the render lists by calling one or more render commands for each render item.
  19764. * - For each render command, request a render object and perform the draw.
  19765. *
  19766. * The module provides an interface to get data required for the draw command like the actual
  19767. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19768. * creating render objects should only be done when necessary.
  19769. *
  19770. * @private
  19771. */
  19772. class RenderObject {
  19773. /**
  19774. * Constructs a new render object.
  19775. *
  19776. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19777. * @param {Geometries} geometries - Renderer component for managing geometries.
  19778. * @param {Renderer} renderer - The renderer.
  19779. * @param {Object3D} object - The 3D object.
  19780. * @param {Material} material - The 3D object's material.
  19781. * @param {Scene} scene - The scene the 3D object belongs to.
  19782. * @param {Camera} camera - The camera the object should be rendered with.
  19783. * @param {LightsNode} lightsNode - The lights node.
  19784. * @param {RenderContext} renderContext - The render context.
  19785. * @param {ClippingContext} clippingContext - The clipping context.
  19786. */
  19787. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19788. this.id = _id$9 ++;
  19789. /**
  19790. * Renderer component for managing nodes related logic.
  19791. *
  19792. * @type {Nodes}
  19793. * @private
  19794. */
  19795. this._nodes = nodes;
  19796. /**
  19797. * Renderer component for managing geometries.
  19798. *
  19799. * @type {Geometries}
  19800. * @private
  19801. */
  19802. this._geometries = geometries;
  19803. /**
  19804. * The renderer.
  19805. *
  19806. * @type {Renderer}
  19807. */
  19808. this.renderer = renderer;
  19809. /**
  19810. * The 3D object.
  19811. *
  19812. * @type {Object3D}
  19813. */
  19814. this.object = object;
  19815. /**
  19816. * The 3D object's material.
  19817. *
  19818. * @type {Material}
  19819. */
  19820. this.material = material;
  19821. /**
  19822. * The scene the 3D object belongs to.
  19823. *
  19824. * @type {Scene}
  19825. */
  19826. this.scene = scene;
  19827. /**
  19828. * The camera the 3D object should be rendered with.
  19829. *
  19830. * @type {Camera}
  19831. */
  19832. this.camera = camera;
  19833. /**
  19834. * The lights node.
  19835. *
  19836. * @type {LightsNode}
  19837. */
  19838. this.lightsNode = lightsNode;
  19839. /**
  19840. * The render context.
  19841. *
  19842. * @type {RenderContext}
  19843. */
  19844. this.context = renderContext;
  19845. /**
  19846. * The 3D object's geometry.
  19847. *
  19848. * @type {BufferGeometry}
  19849. */
  19850. this.geometry = object.geometry;
  19851. /**
  19852. * The render object's version.
  19853. *
  19854. * @type {number}
  19855. */
  19856. this.version = material.version;
  19857. /**
  19858. * The draw range of the geometry.
  19859. *
  19860. * @type {?Object}
  19861. * @default null
  19862. */
  19863. this.drawRange = null;
  19864. /**
  19865. * An array holding the buffer attributes
  19866. * of the render object. This entails attribute
  19867. * definitions on geometry and node level.
  19868. *
  19869. * @type {?Array<BufferAttribute>}
  19870. * @default null
  19871. */
  19872. this.attributes = null;
  19873. /**
  19874. * An object holding the version of the
  19875. * attributes. The keys are the attribute names
  19876. * and the values are the attribute versions.
  19877. *
  19878. * @type {?Object<string, number>}
  19879. * @default null
  19880. */
  19881. this.attributesId = null;
  19882. /**
  19883. * A reference to a render pipeline the render
  19884. * object is processed with.
  19885. *
  19886. * @type {RenderPipeline}
  19887. * @default null
  19888. */
  19889. this.pipeline = null;
  19890. /**
  19891. * Only relevant for objects using
  19892. * multiple materials. This represents a group entry
  19893. * from the respective `BufferGeometry`.
  19894. *
  19895. * @type {?{start: number, count: number}}
  19896. * @default null
  19897. */
  19898. this.group = null;
  19899. /**
  19900. * An array holding the vertex buffers which can
  19901. * be buffer attributes but also interleaved buffers.
  19902. *
  19903. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19904. * @default null
  19905. */
  19906. this.vertexBuffers = null;
  19907. /**
  19908. * The parameters for the draw command.
  19909. *
  19910. * @type {?Object}
  19911. * @default null
  19912. */
  19913. this.drawParams = null;
  19914. /**
  19915. * If this render object is used inside a render bundle,
  19916. * this property points to the respective bundle group.
  19917. *
  19918. * @type {?BundleGroup}
  19919. * @default null
  19920. */
  19921. this.bundle = null;
  19922. /**
  19923. * The clipping context.
  19924. *
  19925. * @type {ClippingContext}
  19926. */
  19927. this.clippingContext = clippingContext;
  19928. /**
  19929. * The clipping context's cache key.
  19930. *
  19931. * @type {string}
  19932. */
  19933. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19934. /**
  19935. * The initial node cache key.
  19936. *
  19937. * @type {number}
  19938. */
  19939. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19940. /**
  19941. * The initial cache key.
  19942. *
  19943. * @type {number}
  19944. */
  19945. this.initialCacheKey = this.getCacheKey();
  19946. /**
  19947. * The node builder state.
  19948. *
  19949. * @type {?NodeBuilderState}
  19950. * @private
  19951. * @default null
  19952. */
  19953. this._nodeBuilderState = null;
  19954. /**
  19955. * An array of bindings.
  19956. *
  19957. * @type {?Array<BindGroup>}
  19958. * @private
  19959. * @default null
  19960. */
  19961. this._bindings = null;
  19962. /**
  19963. * Reference to the node material observer.
  19964. *
  19965. * @type {?NodeMaterialObserver}
  19966. * @private
  19967. * @default null
  19968. */
  19969. this._monitor = null;
  19970. /**
  19971. * An event listener which is defined by `RenderObjects`. It performs
  19972. * clean up tasks when `dispose()` on this render object.
  19973. *
  19974. * @method
  19975. */
  19976. this.onDispose = null;
  19977. /**
  19978. * This flag can be used for type testing.
  19979. *
  19980. * @type {boolean}
  19981. * @readonly
  19982. * @default true
  19983. */
  19984. this.isRenderObject = true;
  19985. /**
  19986. * An event listener which is executed when `dispose()` is called on
  19987. * the material of this render object.
  19988. *
  19989. * @method
  19990. */
  19991. this.onMaterialDispose = () => {
  19992. this.dispose();
  19993. };
  19994. /**
  19995. * An event listener which is executed when `dispose()` is called on
  19996. * the geometry of this render object.
  19997. *
  19998. * @method
  19999. */
  20000. this.onGeometryDispose = () => {
  20001. // clear geometry cache attributes
  20002. this.attributes = null;
  20003. this.attributesId = null;
  20004. };
  20005. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20006. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20007. }
  20008. /**
  20009. * Updates the clipping context.
  20010. *
  20011. * @param {ClippingContext} context - The clipping context to set.
  20012. */
  20013. updateClipping( context ) {
  20014. this.clippingContext = context;
  20015. }
  20016. /**
  20017. * Whether the clipping requires an update or not.
  20018. *
  20019. * @type {boolean}
  20020. * @readonly
  20021. */
  20022. get clippingNeedsUpdate() {
  20023. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20024. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20025. return true;
  20026. }
  20027. /**
  20028. * The number of clipping planes defined in context of hardware clipping.
  20029. *
  20030. * @type {number}
  20031. * @readonly
  20032. */
  20033. get hardwareClippingPlanes() {
  20034. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20035. }
  20036. /**
  20037. * Returns the node builder state of this render object.
  20038. *
  20039. * @return {NodeBuilderState} The node builder state.
  20040. */
  20041. getNodeBuilderState() {
  20042. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20043. }
  20044. /**
  20045. * Returns the node material observer of this render object.
  20046. *
  20047. * @return {NodeMaterialObserver} The node material observer.
  20048. */
  20049. getMonitor() {
  20050. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20051. }
  20052. /**
  20053. * Returns an array of bind groups of this render object.
  20054. *
  20055. * @return {Array<BindGroup>} The bindings.
  20056. */
  20057. getBindings() {
  20058. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20059. }
  20060. /**
  20061. * Returns a binding group by group name of this render object.
  20062. *
  20063. * @param {string} name - The name of the binding group.
  20064. * @return {?BindGroup} The bindings.
  20065. */
  20066. getBindingGroup( name ) {
  20067. for ( const bindingGroup of this.getBindings() ) {
  20068. if ( bindingGroup.name === name ) {
  20069. return bindingGroup;
  20070. }
  20071. }
  20072. }
  20073. /**
  20074. * Returns the index of the render object's geometry.
  20075. *
  20076. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20077. */
  20078. getIndex() {
  20079. return this._geometries.getIndex( this );
  20080. }
  20081. /**
  20082. * Returns the indirect buffer attribute.
  20083. *
  20084. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20085. */
  20086. getIndirect() {
  20087. return this._geometries.getIndirect( this );
  20088. }
  20089. /**
  20090. * Returns an array that acts as a key for identifying the render object in a chain map.
  20091. *
  20092. * @return {Array<Object>} An array with object references.
  20093. */
  20094. getChainArray() {
  20095. return [ this.object, this.material, this.context, this.lightsNode ];
  20096. }
  20097. /**
  20098. * This method is used when the geometry of a 3D object has been exchanged and the
  20099. * respective render object now requires an update.
  20100. *
  20101. * @param {BufferGeometry} geometry - The geometry to set.
  20102. */
  20103. setGeometry( geometry ) {
  20104. this.geometry = geometry;
  20105. this.attributes = null;
  20106. this.attributesId = null;
  20107. }
  20108. /**
  20109. * Returns the buffer attributes of the render object. The returned array holds
  20110. * attribute definitions on geometry and node level.
  20111. *
  20112. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20113. */
  20114. getAttributes() {
  20115. if ( this.attributes !== null ) return this.attributes;
  20116. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20117. const geometry = this.geometry;
  20118. const attributes = [];
  20119. const vertexBuffers = new Set();
  20120. const attributesId = {};
  20121. for ( const nodeAttribute of nodeAttributes ) {
  20122. let attribute;
  20123. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20124. // node attribute
  20125. attribute = nodeAttribute.node.attribute;
  20126. } else {
  20127. // geometry attribute
  20128. attribute = geometry.getAttribute( nodeAttribute.name );
  20129. attributesId[ nodeAttribute.name ] = attribute.version;
  20130. }
  20131. if ( attribute === undefined ) continue;
  20132. attributes.push( attribute );
  20133. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20134. vertexBuffers.add( bufferAttribute );
  20135. }
  20136. this.attributes = attributes;
  20137. this.attributesId = attributesId;
  20138. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20139. return attributes;
  20140. }
  20141. /**
  20142. * Returns the vertex buffers of the render object.
  20143. *
  20144. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20145. */
  20146. getVertexBuffers() {
  20147. if ( this.vertexBuffers === null ) this.getAttributes();
  20148. return this.vertexBuffers;
  20149. }
  20150. /**
  20151. * Returns the draw parameters for the render object.
  20152. *
  20153. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20154. */
  20155. getDrawParameters() {
  20156. const { object, material, geometry, group, drawRange } = this;
  20157. const drawParams = this.drawParams || ( this.drawParams = {
  20158. vertexCount: 0,
  20159. firstVertex: 0,
  20160. instanceCount: 0,
  20161. firstInstance: 0
  20162. } );
  20163. const index = this.getIndex();
  20164. const hasIndex = ( index !== null );
  20165. let instanceCount = 1;
  20166. if ( geometry.isInstancedBufferGeometry === true ) {
  20167. instanceCount = geometry.instanceCount;
  20168. } else if ( object.count !== undefined ) {
  20169. instanceCount = Math.max( 0, object.count );
  20170. }
  20171. if ( instanceCount === 0 ) return null;
  20172. drawParams.instanceCount = instanceCount;
  20173. if ( object.isBatchedMesh === true ) return drawParams;
  20174. let rangeFactor = 1;
  20175. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20176. rangeFactor = 2;
  20177. }
  20178. let firstVertex = drawRange.start * rangeFactor;
  20179. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20180. if ( group !== null ) {
  20181. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20182. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20183. }
  20184. const position = geometry.attributes.position;
  20185. let itemCount = Infinity;
  20186. if ( hasIndex ) {
  20187. itemCount = index.count;
  20188. } else if ( position !== undefined && position !== null ) {
  20189. itemCount = position.count;
  20190. }
  20191. firstVertex = Math.max( firstVertex, 0 );
  20192. lastVertex = Math.min( lastVertex, itemCount );
  20193. const count = lastVertex - firstVertex;
  20194. if ( count < 0 || count === Infinity ) return null;
  20195. drawParams.vertexCount = count;
  20196. drawParams.firstVertex = firstVertex;
  20197. return drawParams;
  20198. }
  20199. /**
  20200. * Returns the render object's geometry cache key.
  20201. *
  20202. * The geometry cache key is part of the material cache key.
  20203. *
  20204. * @return {string} The geometry cache key.
  20205. */
  20206. getGeometryCacheKey() {
  20207. const { geometry } = this;
  20208. let cacheKey = '';
  20209. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20210. const attribute = geometry.attributes[ name ];
  20211. cacheKey += name + ',';
  20212. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20213. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20214. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20215. if ( attribute.normalized ) cacheKey += 'n,';
  20216. }
  20217. // structural equality isn't sufficient for morph targets since the
  20218. // data are maintained in textures. only if the targets are all equal
  20219. // the texture and thus the instance of `MorphNode` can be shared.
  20220. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20221. const targets = geometry.morphAttributes[ name ];
  20222. cacheKey += 'morph-' + name + ',';
  20223. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20224. const attribute = targets[ i ];
  20225. cacheKey += attribute.id + ',';
  20226. }
  20227. }
  20228. if ( geometry.index ) {
  20229. cacheKey += 'index,';
  20230. }
  20231. return cacheKey;
  20232. }
  20233. /**
  20234. * Returns the render object's material cache key.
  20235. *
  20236. * The material cache key is part of the render object cache key.
  20237. *
  20238. * @return {number} The material cache key.
  20239. */
  20240. getMaterialCacheKey() {
  20241. const { object, material, renderer } = this;
  20242. let cacheKey = material.customProgramCacheKey();
  20243. for ( const property of getKeys( material ) ) {
  20244. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20245. const value = material[ property ];
  20246. let valueKey;
  20247. if ( value !== null ) {
  20248. // some material values require a formatting
  20249. const type = typeof value;
  20250. if ( type === 'number' ) {
  20251. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20252. } else if ( type === 'object' ) {
  20253. valueKey = '{';
  20254. if ( value.isTexture ) {
  20255. valueKey += value.mapping;
  20256. // WebGPU must honor the sampler data because they are part of the bindings
  20257. if ( renderer.backend.isWebGPUBackend === true ) {
  20258. valueKey += value.magFilter;
  20259. valueKey += value.minFilter;
  20260. valueKey += value.wrapS;
  20261. valueKey += value.wrapT;
  20262. valueKey += value.wrapR;
  20263. }
  20264. }
  20265. valueKey += '}';
  20266. } else {
  20267. valueKey = String( value );
  20268. }
  20269. } else {
  20270. valueKey = String( value );
  20271. }
  20272. cacheKey += /*property + ':' +*/ valueKey + ',';
  20273. }
  20274. cacheKey += this.clippingContextCacheKey + ',';
  20275. if ( object.geometry ) {
  20276. cacheKey += this.getGeometryCacheKey();
  20277. }
  20278. if ( object.skeleton ) {
  20279. cacheKey += object.skeleton.bones.length + ',';
  20280. }
  20281. if ( object.isBatchedMesh ) {
  20282. cacheKey += object._matricesTexture.uuid + ',';
  20283. if ( object._colorsTexture !== null ) {
  20284. cacheKey += object._colorsTexture.uuid + ',';
  20285. }
  20286. }
  20287. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20288. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20289. cacheKey += object.uuid + ',';
  20290. }
  20291. cacheKey += object.receiveShadow + ',';
  20292. return hashString( cacheKey );
  20293. }
  20294. /**
  20295. * Whether the geometry requires an update or not.
  20296. *
  20297. * @type {boolean}
  20298. * @readonly
  20299. */
  20300. get needsGeometryUpdate() {
  20301. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20302. if ( this.attributes !== null ) {
  20303. const attributesId = this.attributesId;
  20304. for ( const name in attributesId ) {
  20305. const attribute = this.geometry.getAttribute( name );
  20306. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20307. return true;
  20308. }
  20309. }
  20310. }
  20311. return false;
  20312. }
  20313. /**
  20314. * Whether the render object requires an update or not.
  20315. *
  20316. * Note: There are two distinct places where render objects are checked for an update.
  20317. *
  20318. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20319. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20320. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20321. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20322. * a need for a refresh due to material, geometry or object related value changes.
  20323. *
  20324. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20325. * that performs the 'needsUpdate' check.
  20326. *
  20327. * @type {boolean}
  20328. * @readonly
  20329. */
  20330. get needsUpdate() {
  20331. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20332. }
  20333. /**
  20334. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20335. *
  20336. * @return {number} The cache key.
  20337. */
  20338. getDynamicCacheKey() {
  20339. let cacheKey = 0;
  20340. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20341. // the renderer is inside a shadow pass.
  20342. if ( this.material.isShadowPassMaterial !== true ) {
  20343. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20344. }
  20345. if ( this.camera.isArrayCamera ) {
  20346. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20347. }
  20348. if ( this.object.receiveShadow ) {
  20349. cacheKey = hash$1( cacheKey, 1 );
  20350. }
  20351. return cacheKey;
  20352. }
  20353. /**
  20354. * Returns the render object's cache key.
  20355. *
  20356. * @return {number} The cache key.
  20357. */
  20358. getCacheKey() {
  20359. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20360. }
  20361. /**
  20362. * Frees internal resources.
  20363. */
  20364. dispose() {
  20365. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20366. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20367. this.onDispose();
  20368. }
  20369. }
  20370. const _chainKeys$5 = [];
  20371. /**
  20372. * This module manages the render objects of the renderer.
  20373. *
  20374. * @private
  20375. */
  20376. class RenderObjects {
  20377. /**
  20378. * Constructs a new render object management component.
  20379. *
  20380. * @param {Renderer} renderer - The renderer.
  20381. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20382. * @param {Geometries} geometries - Renderer component for managing geometries.
  20383. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20384. * @param {Bindings} bindings - Renderer component for managing bindings.
  20385. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20386. */
  20387. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20388. /**
  20389. * The renderer.
  20390. *
  20391. * @type {Renderer}
  20392. */
  20393. this.renderer = renderer;
  20394. /**
  20395. * Renderer component for managing nodes related logic.
  20396. *
  20397. * @type {Nodes}
  20398. */
  20399. this.nodes = nodes;
  20400. /**
  20401. * Renderer component for managing geometries.
  20402. *
  20403. * @type {Geometries}
  20404. */
  20405. this.geometries = geometries;
  20406. /**
  20407. * Renderer component for managing pipelines.
  20408. *
  20409. * @type {Pipelines}
  20410. */
  20411. this.pipelines = pipelines;
  20412. /**
  20413. * Renderer component for managing bindings.
  20414. *
  20415. * @type {Bindings}
  20416. */
  20417. this.bindings = bindings;
  20418. /**
  20419. * Renderer component for managing metrics and monitoring data.
  20420. *
  20421. * @type {Info}
  20422. */
  20423. this.info = info;
  20424. /**
  20425. * A dictionary that manages render contexts in chain maps
  20426. * for each pass ID.
  20427. *
  20428. * @type {Object<string,ChainMap>}
  20429. */
  20430. this.chainMaps = {};
  20431. }
  20432. /**
  20433. * Returns a render object for the given object and state data.
  20434. *
  20435. * @param {Object3D} object - The 3D object.
  20436. * @param {Material} material - The 3D object's material.
  20437. * @param {Scene} scene - The scene the 3D object belongs to.
  20438. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20439. * @param {LightsNode} lightsNode - The lights node.
  20440. * @param {RenderContext} renderContext - The render context.
  20441. * @param {ClippingContext} clippingContext - The clipping context.
  20442. * @param {string} [passId] - An optional ID for identifying the pass.
  20443. * @return {RenderObject} The render object.
  20444. */
  20445. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20446. const chainMap = this.getChainMap( passId );
  20447. // reuse chainArray
  20448. _chainKeys$5[ 0 ] = object;
  20449. _chainKeys$5[ 1 ] = material;
  20450. _chainKeys$5[ 2 ] = renderContext;
  20451. _chainKeys$5[ 3 ] = lightsNode;
  20452. let renderObject = chainMap.get( _chainKeys$5 );
  20453. if ( renderObject === undefined ) {
  20454. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20455. chainMap.set( _chainKeys$5, renderObject );
  20456. } else {
  20457. renderObject.updateClipping( clippingContext );
  20458. if ( renderObject.needsGeometryUpdate ) {
  20459. renderObject.setGeometry( object.geometry );
  20460. }
  20461. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20462. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20463. renderObject.dispose();
  20464. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20465. } else {
  20466. renderObject.version = material.version;
  20467. }
  20468. }
  20469. }
  20470. _chainKeys$5.length = 0;
  20471. return renderObject;
  20472. }
  20473. /**
  20474. * Returns a chain map for the given pass ID.
  20475. *
  20476. * @param {string} [passId='default'] - The pass ID.
  20477. * @return {ChainMap} The chain map.
  20478. */
  20479. getChainMap( passId = 'default' ) {
  20480. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20481. }
  20482. /**
  20483. * Frees internal resources.
  20484. */
  20485. dispose() {
  20486. this.chainMaps = {};
  20487. }
  20488. /**
  20489. * Factory method for creating render objects with the given list of parameters.
  20490. *
  20491. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20492. * @param {Geometries} geometries - Renderer component for managing geometries.
  20493. * @param {Renderer} renderer - The renderer.
  20494. * @param {Object3D} object - The 3D object.
  20495. * @param {Material} material - The object's material.
  20496. * @param {Scene} scene - The scene the 3D object belongs to.
  20497. * @param {Camera} camera - The camera the object should be rendered with.
  20498. * @param {LightsNode} lightsNode - The lights node.
  20499. * @param {RenderContext} renderContext - The render context.
  20500. * @param {ClippingContext} clippingContext - The clipping context.
  20501. * @param {string} [passId] - An optional ID for identifying the pass.
  20502. * @return {RenderObject} The render object.
  20503. */
  20504. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20505. const chainMap = this.getChainMap( passId );
  20506. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20507. renderObject.onDispose = () => {
  20508. this.pipelines.delete( renderObject );
  20509. this.bindings.deleteForRender( renderObject );
  20510. this.nodes.delete( renderObject );
  20511. chainMap.delete( renderObject.getChainArray() );
  20512. };
  20513. return renderObject;
  20514. }
  20515. }
  20516. /**
  20517. * Data structure for the renderer. It is intended to manage
  20518. * data of objects in dictionaries.
  20519. *
  20520. * @private
  20521. */
  20522. class DataMap {
  20523. /**
  20524. * Constructs a new data map.
  20525. */
  20526. constructor() {
  20527. /**
  20528. * `DataMap` internally uses a weak map
  20529. * to manage its data.
  20530. *
  20531. * @type {WeakMap<Object, Object>}
  20532. */
  20533. this.data = new WeakMap();
  20534. }
  20535. /**
  20536. * Returns the dictionary for the given object.
  20537. *
  20538. * @param {Object} object - The object.
  20539. * @return {Object} The dictionary.
  20540. */
  20541. get( object ) {
  20542. let map = this.data.get( object );
  20543. if ( map === undefined ) {
  20544. map = {};
  20545. this.data.set( object, map );
  20546. }
  20547. return map;
  20548. }
  20549. /**
  20550. * Deletes the dictionary for the given object.
  20551. *
  20552. * @param {Object} object - The object.
  20553. * @return {?Object} The deleted dictionary.
  20554. */
  20555. delete( object ) {
  20556. let map = null;
  20557. if ( this.data.has( object ) ) {
  20558. map = this.data.get( object );
  20559. this.data.delete( object );
  20560. }
  20561. return map;
  20562. }
  20563. /**
  20564. * Returns `true` if the given object has a dictionary defined.
  20565. *
  20566. * @param {Object} object - The object to test.
  20567. * @return {boolean} Whether a dictionary is defined or not.
  20568. */
  20569. has( object ) {
  20570. return this.data.has( object );
  20571. }
  20572. /**
  20573. * Frees internal resources.
  20574. */
  20575. dispose() {
  20576. this.data = new WeakMap();
  20577. }
  20578. }
  20579. const AttributeType = {
  20580. VERTEX: 1,
  20581. INDEX: 2,
  20582. STORAGE: 3,
  20583. INDIRECT: 4
  20584. };
  20585. // size of a chunk in bytes (STD140 layout)
  20586. const GPU_CHUNK_BYTES = 16;
  20587. // @TODO: Move to src/constants.js
  20588. const BlendColorFactor = 211;
  20589. const OneMinusBlendColorFactor = 212;
  20590. /**
  20591. * This renderer module manages geometry attributes.
  20592. *
  20593. * @private
  20594. * @augments DataMap
  20595. */
  20596. class Attributes extends DataMap {
  20597. /**
  20598. * Constructs a new attribute management component.
  20599. *
  20600. * @param {Backend} backend - The renderer's backend.
  20601. */
  20602. constructor( backend ) {
  20603. super();
  20604. /**
  20605. * The renderer's backend.
  20606. *
  20607. * @type {Backend}
  20608. */
  20609. this.backend = backend;
  20610. }
  20611. /**
  20612. * Deletes the data for the given attribute.
  20613. *
  20614. * @param {BufferAttribute} attribute - The attribute.
  20615. * @return {?Object} The deleted attribute data.
  20616. */
  20617. delete( attribute ) {
  20618. const attributeData = super.delete( attribute );
  20619. if ( attributeData !== null ) {
  20620. this.backend.destroyAttribute( attribute );
  20621. }
  20622. return attributeData;
  20623. }
  20624. /**
  20625. * Updates the given attribute. This method creates attribute buffers
  20626. * for new attributes and updates data for existing ones.
  20627. *
  20628. * @param {BufferAttribute} attribute - The attribute to update.
  20629. * @param {number} type - The attribute type.
  20630. */
  20631. update( attribute, type ) {
  20632. const data = this.get( attribute );
  20633. if ( data.version === undefined ) {
  20634. if ( type === AttributeType.VERTEX ) {
  20635. this.backend.createAttribute( attribute );
  20636. } else if ( type === AttributeType.INDEX ) {
  20637. this.backend.createIndexAttribute( attribute );
  20638. } else if ( type === AttributeType.STORAGE ) {
  20639. this.backend.createStorageAttribute( attribute );
  20640. } else if ( type === AttributeType.INDIRECT ) {
  20641. this.backend.createIndirectStorageAttribute( attribute );
  20642. }
  20643. data.version = this._getBufferAttribute( attribute ).version;
  20644. } else {
  20645. const bufferAttribute = this._getBufferAttribute( attribute );
  20646. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20647. this.backend.updateAttribute( attribute );
  20648. data.version = bufferAttribute.version;
  20649. }
  20650. }
  20651. }
  20652. /**
  20653. * Utility method for handling interleaved buffer attributes correctly.
  20654. * To process them, their `InterleavedBuffer` is returned.
  20655. *
  20656. * @param {BufferAttribute} attribute - The attribute.
  20657. * @return {BufferAttribute|InterleavedBuffer}
  20658. */
  20659. _getBufferAttribute( attribute ) {
  20660. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20661. return attribute;
  20662. }
  20663. }
  20664. /**
  20665. * Returns the wireframe version for the given geometry.
  20666. *
  20667. * @private
  20668. * @function
  20669. * @param {BufferGeometry} geometry - The geometry.
  20670. * @return {number} The version.
  20671. */
  20672. function getWireframeVersion( geometry ) {
  20673. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20674. }
  20675. /**
  20676. * Returns a wireframe index attribute for the given geometry.
  20677. *
  20678. * @private
  20679. * @function
  20680. * @param {BufferGeometry} geometry - The geometry.
  20681. * @return {BufferAttribute} The wireframe index attribute.
  20682. */
  20683. function getWireframeIndex( geometry ) {
  20684. const indices = [];
  20685. const geometryIndex = geometry.index;
  20686. const geometryPosition = geometry.attributes.position;
  20687. if ( geometryIndex !== null ) {
  20688. const array = geometryIndex.array;
  20689. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20690. const a = array[ i + 0 ];
  20691. const b = array[ i + 1 ];
  20692. const c = array[ i + 2 ];
  20693. indices.push( a, b, b, c, c, a );
  20694. }
  20695. } else {
  20696. const array = geometryPosition.array;
  20697. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20698. const a = i + 0;
  20699. const b = i + 1;
  20700. const c = i + 2;
  20701. indices.push( a, b, b, c, c, a );
  20702. }
  20703. }
  20704. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20705. attribute.version = getWireframeVersion( geometry );
  20706. return attribute;
  20707. }
  20708. /**
  20709. * This renderer module manages geometries.
  20710. *
  20711. * @private
  20712. * @augments DataMap
  20713. */
  20714. class Geometries extends DataMap {
  20715. /**
  20716. * Constructs a new geometry management component.
  20717. *
  20718. * @param {Attributes} attributes - Renderer component for managing attributes.
  20719. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20720. */
  20721. constructor( attributes, info ) {
  20722. super();
  20723. /**
  20724. * Renderer component for managing attributes.
  20725. *
  20726. * @type {Attributes}
  20727. */
  20728. this.attributes = attributes;
  20729. /**
  20730. * Renderer component for managing metrics and monitoring data.
  20731. *
  20732. * @type {Info}
  20733. */
  20734. this.info = info;
  20735. /**
  20736. * Weak Map for managing attributes for wireframe rendering.
  20737. *
  20738. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20739. */
  20740. this.wireframes = new WeakMap();
  20741. /**
  20742. * This Weak Map is used to make sure buffer attributes are
  20743. * updated only once per render call.
  20744. *
  20745. * @type {WeakMap<BufferAttribute,number>}
  20746. */
  20747. this.attributeCall = new WeakMap();
  20748. /**
  20749. * Stores the event listeners attached to geometries.
  20750. *
  20751. * @private
  20752. * @type {Map<BufferGeometry,Function>}
  20753. */
  20754. this._geometryDisposeListeners = new Map();
  20755. }
  20756. /**
  20757. * Returns `true` if the given render object has an initialized geometry.
  20758. *
  20759. * @param {RenderObject} renderObject - The render object.
  20760. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20761. */
  20762. has( renderObject ) {
  20763. const geometry = renderObject.geometry;
  20764. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20765. }
  20766. /**
  20767. * Prepares the geometry of the given render object for rendering.
  20768. *
  20769. * @param {RenderObject} renderObject - The render object.
  20770. */
  20771. updateForRender( renderObject ) {
  20772. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20773. this.updateAttributes( renderObject );
  20774. }
  20775. /**
  20776. * Initializes the geometry of the given render object.
  20777. *
  20778. * @param {RenderObject} renderObject - The render object.
  20779. */
  20780. initGeometry( renderObject ) {
  20781. const geometry = renderObject.geometry;
  20782. const geometryData = this.get( geometry );
  20783. geometryData.initialized = true;
  20784. this.info.memory.geometries ++;
  20785. const onDispose = () => {
  20786. this.info.memory.geometries --;
  20787. const index = geometry.index;
  20788. const geometryAttributes = renderObject.getAttributes();
  20789. if ( index !== null ) {
  20790. this.attributes.delete( index );
  20791. }
  20792. for ( const geometryAttribute of geometryAttributes ) {
  20793. this.attributes.delete( geometryAttribute );
  20794. }
  20795. const wireframeAttribute = this.wireframes.get( geometry );
  20796. if ( wireframeAttribute !== undefined ) {
  20797. this.attributes.delete( wireframeAttribute );
  20798. }
  20799. geometry.removeEventListener( 'dispose', onDispose );
  20800. this._geometryDisposeListeners.delete( geometry );
  20801. };
  20802. geometry.addEventListener( 'dispose', onDispose );
  20803. // see #31798 why tracking separate remove listeners is required right now
  20804. // TODO: Re-evaluate how onDispose() is managed in this component
  20805. this._geometryDisposeListeners.set( geometry, onDispose );
  20806. }
  20807. /**
  20808. * Updates the geometry attributes of the given render object.
  20809. *
  20810. * @param {RenderObject} renderObject - The render object.
  20811. */
  20812. updateAttributes( renderObject ) {
  20813. // attributes
  20814. const attributes = renderObject.getAttributes();
  20815. for ( const attribute of attributes ) {
  20816. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20817. this.updateAttribute( attribute, AttributeType.STORAGE );
  20818. } else {
  20819. this.updateAttribute( attribute, AttributeType.VERTEX );
  20820. }
  20821. }
  20822. // indexes
  20823. const index = this.getIndex( renderObject );
  20824. if ( index !== null ) {
  20825. this.updateAttribute( index, AttributeType.INDEX );
  20826. }
  20827. // indirect
  20828. const indirect = renderObject.geometry.indirect;
  20829. if ( indirect !== null ) {
  20830. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20831. }
  20832. }
  20833. /**
  20834. * Updates the given attribute.
  20835. *
  20836. * @param {BufferAttribute} attribute - The attribute to update.
  20837. * @param {number} type - The attribute type.
  20838. */
  20839. updateAttribute( attribute, type ) {
  20840. const callId = this.info.render.calls;
  20841. if ( ! attribute.isInterleavedBufferAttribute ) {
  20842. if ( this.attributeCall.get( attribute ) !== callId ) {
  20843. this.attributes.update( attribute, type );
  20844. this.attributeCall.set( attribute, callId );
  20845. }
  20846. } else {
  20847. if ( this.attributeCall.get( attribute ) === undefined ) {
  20848. this.attributes.update( attribute, type );
  20849. this.attributeCall.set( attribute, callId );
  20850. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20851. this.attributes.update( attribute, type );
  20852. this.attributeCall.set( attribute.data, callId );
  20853. this.attributeCall.set( attribute, callId );
  20854. }
  20855. }
  20856. }
  20857. /**
  20858. * Returns the indirect buffer attribute of the given render object.
  20859. *
  20860. * @param {RenderObject} renderObject - The render object.
  20861. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20862. */
  20863. getIndirect( renderObject ) {
  20864. return renderObject.geometry.indirect;
  20865. }
  20866. /**
  20867. * Returns the index of the given render object's geometry. This is implemented
  20868. * in a method to return a wireframe index if necessary.
  20869. *
  20870. * @param {RenderObject} renderObject - The render object.
  20871. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20872. */
  20873. getIndex( renderObject ) {
  20874. const { geometry, material } = renderObject;
  20875. let index = geometry.index;
  20876. if ( material.wireframe === true ) {
  20877. const wireframes = this.wireframes;
  20878. let wireframeAttribute = wireframes.get( geometry );
  20879. if ( wireframeAttribute === undefined ) {
  20880. wireframeAttribute = getWireframeIndex( geometry );
  20881. wireframes.set( geometry, wireframeAttribute );
  20882. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20883. this.attributes.delete( wireframeAttribute );
  20884. wireframeAttribute = getWireframeIndex( geometry );
  20885. wireframes.set( geometry, wireframeAttribute );
  20886. }
  20887. index = wireframeAttribute;
  20888. }
  20889. return index;
  20890. }
  20891. dispose() {
  20892. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  20893. geometry.removeEventListener( 'dispose', onDispose );
  20894. }
  20895. this._geometryDisposeListeners.clear();
  20896. }
  20897. }
  20898. /**
  20899. * This renderer module provides a series of statistical information
  20900. * about the GPU memory and the rendering process. Useful for debugging
  20901. * and monitoring.
  20902. */
  20903. class Info {
  20904. /**
  20905. * Constructs a new info component.
  20906. */
  20907. constructor() {
  20908. /**
  20909. * Whether frame related metrics should automatically
  20910. * be resetted or not. This property should be set to `false`
  20911. * by apps which manage their own animation loop. They must
  20912. * then call `renderer.info.reset()` once per frame manually.
  20913. *
  20914. * @type {boolean}
  20915. * @default true
  20916. */
  20917. this.autoReset = true;
  20918. /**
  20919. * The current frame ID. This ID is managed
  20920. * by `NodeFrame`.
  20921. *
  20922. * @type {number}
  20923. * @readonly
  20924. * @default 0
  20925. */
  20926. this.frame = 0;
  20927. /**
  20928. * The number of render calls since the
  20929. * app has been started.
  20930. *
  20931. * @type {number}
  20932. * @readonly
  20933. * @default 0
  20934. */
  20935. this.calls = 0;
  20936. /**
  20937. * Render related metrics.
  20938. *
  20939. * @type {Object}
  20940. * @readonly
  20941. * @property {number} calls - The number of render calls since the app has been started.
  20942. * @property {number} frameCalls - The number of render calls of the current frame.
  20943. * @property {number} drawCalls - The number of draw calls of the current frame.
  20944. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20945. * @property {number} points - The number of rendered point primitives of the current frame.
  20946. * @property {number} lines - The number of rendered line primitives of the current frame.
  20947. * @property {number} timestamp - The timestamp of the frame.
  20948. */
  20949. this.render = {
  20950. calls: 0,
  20951. frameCalls: 0,
  20952. drawCalls: 0,
  20953. triangles: 0,
  20954. points: 0,
  20955. lines: 0,
  20956. timestamp: 0,
  20957. };
  20958. /**
  20959. * Compute related metrics.
  20960. *
  20961. * @type {Object}
  20962. * @readonly
  20963. * @property {number} calls - The number of compute calls since the app has been started.
  20964. * @property {number} frameCalls - The number of compute calls of the current frame.
  20965. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20966. */
  20967. this.compute = {
  20968. calls: 0,
  20969. frameCalls: 0,
  20970. timestamp: 0
  20971. };
  20972. /**
  20973. * Memory related metrics.
  20974. *
  20975. * @type {Object}
  20976. * @readonly
  20977. * @property {number} geometries - The number of active geometries.
  20978. * @property {number} frameCalls - The number of active textures.
  20979. */
  20980. this.memory = {
  20981. geometries: 0,
  20982. textures: 0
  20983. };
  20984. }
  20985. /**
  20986. * This method should be executed per draw call and updates the corresponding metrics.
  20987. *
  20988. * @param {Object3D} object - The 3D object that is going to be rendered.
  20989. * @param {number} count - The vertex or index count.
  20990. * @param {number} instanceCount - The instance count.
  20991. */
  20992. update( object, count, instanceCount ) {
  20993. this.render.drawCalls ++;
  20994. if ( object.isMesh || object.isSprite ) {
  20995. this.render.triangles += instanceCount * ( count / 3 );
  20996. } else if ( object.isPoints ) {
  20997. this.render.points += instanceCount * count;
  20998. } else if ( object.isLineSegments ) {
  20999. this.render.lines += instanceCount * ( count / 2 );
  21000. } else if ( object.isLine ) {
  21001. this.render.lines += instanceCount * ( count - 1 );
  21002. } else {
  21003. error( 'WebGPUInfo: Unknown object type.' );
  21004. }
  21005. }
  21006. /**
  21007. * Resets frame related metrics.
  21008. */
  21009. reset() {
  21010. this.render.drawCalls = 0;
  21011. this.render.frameCalls = 0;
  21012. this.compute.frameCalls = 0;
  21013. this.render.triangles = 0;
  21014. this.render.points = 0;
  21015. this.render.lines = 0;
  21016. }
  21017. /**
  21018. * Performs a complete reset of the object.
  21019. */
  21020. dispose() {
  21021. this.reset();
  21022. this.calls = 0;
  21023. this.render.calls = 0;
  21024. this.compute.calls = 0;
  21025. this.render.timestamp = 0;
  21026. this.compute.timestamp = 0;
  21027. this.memory.geometries = 0;
  21028. this.memory.textures = 0;
  21029. }
  21030. }
  21031. /**
  21032. * Abstract class for representing pipelines.
  21033. *
  21034. * @private
  21035. * @abstract
  21036. */
  21037. class Pipeline {
  21038. /**
  21039. * Constructs a new pipeline.
  21040. *
  21041. * @param {string} cacheKey - The pipeline's cache key.
  21042. */
  21043. constructor( cacheKey ) {
  21044. /**
  21045. * The pipeline's cache key.
  21046. *
  21047. * @type {string}
  21048. */
  21049. this.cacheKey = cacheKey;
  21050. /**
  21051. * How often the pipeline is currently in use.
  21052. *
  21053. * @type {number}
  21054. * @default 0
  21055. */
  21056. this.usedTimes = 0;
  21057. }
  21058. }
  21059. /**
  21060. * Class for representing render pipelines.
  21061. *
  21062. * @private
  21063. * @augments Pipeline
  21064. */
  21065. class RenderPipeline extends Pipeline {
  21066. /**
  21067. * Constructs a new render pipeline.
  21068. *
  21069. * @param {string} cacheKey - The pipeline's cache key.
  21070. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21071. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21072. */
  21073. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21074. super( cacheKey );
  21075. /**
  21076. * The pipeline's vertex shader.
  21077. *
  21078. * @type {ProgrammableStage}
  21079. */
  21080. this.vertexProgram = vertexProgram;
  21081. /**
  21082. * The pipeline's fragment shader.
  21083. *
  21084. * @type {ProgrammableStage}
  21085. */
  21086. this.fragmentProgram = fragmentProgram;
  21087. }
  21088. }
  21089. /**
  21090. * Class for representing compute pipelines.
  21091. *
  21092. * @private
  21093. * @augments Pipeline
  21094. */
  21095. class ComputePipeline extends Pipeline {
  21096. /**
  21097. * Constructs a new render pipeline.
  21098. *
  21099. * @param {string} cacheKey - The pipeline's cache key.
  21100. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21101. */
  21102. constructor( cacheKey, computeProgram ) {
  21103. super( cacheKey );
  21104. /**
  21105. * The pipeline's compute shader.
  21106. *
  21107. * @type {ProgrammableStage}
  21108. */
  21109. this.computeProgram = computeProgram;
  21110. /**
  21111. * This flag can be used for type testing.
  21112. *
  21113. * @type {boolean}
  21114. * @readonly
  21115. * @default true
  21116. */
  21117. this.isComputePipeline = true;
  21118. }
  21119. }
  21120. let _id$8 = 0;
  21121. /**
  21122. * Class for representing programmable stages which are vertex,
  21123. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21124. * they represent the programmable part of a pipeline.
  21125. *
  21126. * @private
  21127. */
  21128. class ProgrammableStage {
  21129. /**
  21130. * Constructs a new programmable stage.
  21131. *
  21132. * @param {string} code - The shader code.
  21133. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21134. * @param {string} name - The name of the shader.
  21135. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21136. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21137. */
  21138. constructor( code, stage, name, transforms = null, attributes = null ) {
  21139. /**
  21140. * The id of the programmable stage.
  21141. *
  21142. * @type {number}
  21143. */
  21144. this.id = _id$8 ++;
  21145. /**
  21146. * The shader code.
  21147. *
  21148. * @type {string}
  21149. */
  21150. this.code = code;
  21151. /**
  21152. * The type of stage.
  21153. *
  21154. * @type {string}
  21155. */
  21156. this.stage = stage;
  21157. /**
  21158. * The name of the stage.
  21159. * This is used for debugging purposes.
  21160. *
  21161. * @type {string}
  21162. */
  21163. this.name = name;
  21164. /**
  21165. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21166. *
  21167. * @type {?Array<Object>}
  21168. */
  21169. this.transforms = transforms;
  21170. /**
  21171. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21172. *
  21173. * @type {?Array<Object>}
  21174. */
  21175. this.attributes = attributes;
  21176. /**
  21177. * How often the programmable stage is currently in use.
  21178. *
  21179. * @type {number}
  21180. * @default 0
  21181. */
  21182. this.usedTimes = 0;
  21183. }
  21184. }
  21185. /**
  21186. * This renderer module manages the pipelines of the renderer.
  21187. *
  21188. * @private
  21189. * @augments DataMap
  21190. */
  21191. class Pipelines extends DataMap {
  21192. /**
  21193. * Constructs a new pipeline management component.
  21194. *
  21195. * @param {Backend} backend - The renderer's backend.
  21196. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21197. */
  21198. constructor( backend, nodes ) {
  21199. super();
  21200. /**
  21201. * The renderer's backend.
  21202. *
  21203. * @type {Backend}
  21204. */
  21205. this.backend = backend;
  21206. /**
  21207. * Renderer component for managing nodes related logic.
  21208. *
  21209. * @type {Nodes}
  21210. */
  21211. this.nodes = nodes;
  21212. /**
  21213. * A references to the bindings management component.
  21214. * This reference will be set inside the `Bindings`
  21215. * constructor.
  21216. *
  21217. * @type {?Bindings}
  21218. * @default null
  21219. */
  21220. this.bindings = null;
  21221. /**
  21222. * Internal cache for maintaining pipelines.
  21223. * The key of the map is a cache key, the value the pipeline.
  21224. *
  21225. * @type {Map<string,Pipeline>}
  21226. */
  21227. this.caches = new Map();
  21228. /**
  21229. * This dictionary maintains for each shader stage type (vertex,
  21230. * fragment and compute) the programmable stage objects which
  21231. * represent the actual shader code.
  21232. *
  21233. * @type {Object<string,Map<string, ProgrammableStage>>}
  21234. */
  21235. this.programs = {
  21236. vertex: new Map(),
  21237. fragment: new Map(),
  21238. compute: new Map()
  21239. };
  21240. }
  21241. /**
  21242. * Returns a compute pipeline for the given compute node.
  21243. *
  21244. * @param {Node} computeNode - The compute node.
  21245. * @param {Array<BindGroup>} bindings - The bindings.
  21246. * @return {ComputePipeline} The compute pipeline.
  21247. */
  21248. getForCompute( computeNode, bindings ) {
  21249. const { backend } = this;
  21250. const data = this.get( computeNode );
  21251. if ( this._needsComputeUpdate( computeNode ) ) {
  21252. const previousPipeline = data.pipeline;
  21253. if ( previousPipeline ) {
  21254. previousPipeline.usedTimes --;
  21255. previousPipeline.computeProgram.usedTimes --;
  21256. }
  21257. // get shader
  21258. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21259. // programmable stage
  21260. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21261. if ( stageCompute === undefined ) {
  21262. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21263. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21264. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21265. backend.createProgram( stageCompute );
  21266. }
  21267. // determine compute pipeline
  21268. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21269. let pipeline = this.caches.get( cacheKey );
  21270. if ( pipeline === undefined ) {
  21271. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21272. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21273. }
  21274. // keep track of all used times
  21275. pipeline.usedTimes ++;
  21276. stageCompute.usedTimes ++;
  21277. //
  21278. data.version = computeNode.version;
  21279. data.pipeline = pipeline;
  21280. }
  21281. return data.pipeline;
  21282. }
  21283. /**
  21284. * Returns a render pipeline for the given render object.
  21285. *
  21286. * @param {RenderObject} renderObject - The render object.
  21287. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21288. * @return {RenderPipeline} The render pipeline.
  21289. */
  21290. getForRender( renderObject, promises = null ) {
  21291. const { backend } = this;
  21292. const data = this.get( renderObject );
  21293. if ( this._needsRenderUpdate( renderObject ) ) {
  21294. const previousPipeline = data.pipeline;
  21295. if ( previousPipeline ) {
  21296. previousPipeline.usedTimes --;
  21297. previousPipeline.vertexProgram.usedTimes --;
  21298. previousPipeline.fragmentProgram.usedTimes --;
  21299. }
  21300. // get shader
  21301. const nodeBuilderState = renderObject.getNodeBuilderState();
  21302. const name = renderObject.material ? renderObject.material.name : '';
  21303. // programmable stages
  21304. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21305. if ( stageVertex === undefined ) {
  21306. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21307. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21308. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21309. backend.createProgram( stageVertex );
  21310. }
  21311. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21312. if ( stageFragment === undefined ) {
  21313. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21314. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21315. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21316. backend.createProgram( stageFragment );
  21317. }
  21318. // determine render pipeline
  21319. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21320. let pipeline = this.caches.get( cacheKey );
  21321. if ( pipeline === undefined ) {
  21322. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21323. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21324. } else {
  21325. renderObject.pipeline = pipeline;
  21326. }
  21327. // keep track of all used times
  21328. pipeline.usedTimes ++;
  21329. stageVertex.usedTimes ++;
  21330. stageFragment.usedTimes ++;
  21331. //
  21332. data.pipeline = pipeline;
  21333. }
  21334. return data.pipeline;
  21335. }
  21336. /**
  21337. * Deletes the pipeline for the given render object.
  21338. *
  21339. * @param {RenderObject} object - The render object.
  21340. * @return {?Object} The deleted dictionary.
  21341. */
  21342. delete( object ) {
  21343. const pipeline = this.get( object ).pipeline;
  21344. if ( pipeline ) {
  21345. // pipeline
  21346. pipeline.usedTimes --;
  21347. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21348. // programs
  21349. if ( pipeline.isComputePipeline ) {
  21350. pipeline.computeProgram.usedTimes --;
  21351. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21352. } else {
  21353. pipeline.fragmentProgram.usedTimes --;
  21354. pipeline.vertexProgram.usedTimes --;
  21355. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21356. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21357. }
  21358. }
  21359. return super.delete( object );
  21360. }
  21361. /**
  21362. * Frees internal resources.
  21363. */
  21364. dispose() {
  21365. super.dispose();
  21366. this.caches = new Map();
  21367. this.programs = {
  21368. vertex: new Map(),
  21369. fragment: new Map(),
  21370. compute: new Map()
  21371. };
  21372. }
  21373. /**
  21374. * Updates the pipeline for the given render object.
  21375. *
  21376. * @param {RenderObject} renderObject - The render object.
  21377. */
  21378. updateForRender( renderObject ) {
  21379. this.getForRender( renderObject );
  21380. }
  21381. /**
  21382. * Returns a compute pipeline for the given parameters.
  21383. *
  21384. * @private
  21385. * @param {Node} computeNode - The compute node.
  21386. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21387. * @param {string} cacheKey - The cache key.
  21388. * @param {Array<BindGroup>} bindings - The bindings.
  21389. * @return {ComputePipeline} The compute pipeline.
  21390. */
  21391. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21392. // check for existing pipeline
  21393. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21394. let pipeline = this.caches.get( cacheKey );
  21395. if ( pipeline === undefined ) {
  21396. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21397. this.caches.set( cacheKey, pipeline );
  21398. this.backend.createComputePipeline( pipeline, bindings );
  21399. }
  21400. return pipeline;
  21401. }
  21402. /**
  21403. * Returns a render pipeline for the given parameters.
  21404. *
  21405. * @private
  21406. * @param {RenderObject} renderObject - The render object.
  21407. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21408. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21409. * @param {string} cacheKey - The cache key.
  21410. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21411. * @return {ComputePipeline} The compute pipeline.
  21412. */
  21413. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21414. // check for existing pipeline
  21415. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21416. let pipeline = this.caches.get( cacheKey );
  21417. if ( pipeline === undefined ) {
  21418. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21419. this.caches.set( cacheKey, pipeline );
  21420. renderObject.pipeline = pipeline;
  21421. // The `promises` array is `null` by default and only set to an empty array when
  21422. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21423. // pending promises that resolve when the render pipelines are ready for rendering.
  21424. this.backend.createRenderPipeline( renderObject, promises );
  21425. }
  21426. return pipeline;
  21427. }
  21428. /**
  21429. * Computes a cache key representing a compute pipeline.
  21430. *
  21431. * @private
  21432. * @param {Node} computeNode - The compute node.
  21433. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21434. * @return {string} The cache key.
  21435. */
  21436. _getComputeCacheKey( computeNode, stageCompute ) {
  21437. return computeNode.id + ',' + stageCompute.id;
  21438. }
  21439. /**
  21440. * Computes a cache key representing a render pipeline.
  21441. *
  21442. * @private
  21443. * @param {RenderObject} renderObject - The render object.
  21444. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21445. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21446. * @return {string} The cache key.
  21447. */
  21448. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21449. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21450. }
  21451. /**
  21452. * Releases the given pipeline.
  21453. *
  21454. * @private
  21455. * @param {Pipeline} pipeline - The pipeline to release.
  21456. */
  21457. _releasePipeline( pipeline ) {
  21458. this.caches.delete( pipeline.cacheKey );
  21459. }
  21460. /**
  21461. * Releases the shader program.
  21462. *
  21463. * @private
  21464. * @param {Object} program - The shader program to release.
  21465. */
  21466. _releaseProgram( program ) {
  21467. const code = program.code;
  21468. const stage = program.stage;
  21469. this.programs[ stage ].delete( code );
  21470. }
  21471. /**
  21472. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21473. *
  21474. * @private
  21475. * @param {Node} computeNode - The compute node.
  21476. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21477. */
  21478. _needsComputeUpdate( computeNode ) {
  21479. const data = this.get( computeNode );
  21480. return data.pipeline === undefined || data.version !== computeNode.version;
  21481. }
  21482. /**
  21483. * Returns `true` if the render pipeline for the given render object requires an update.
  21484. *
  21485. * @private
  21486. * @param {RenderObject} renderObject - The render object.
  21487. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21488. */
  21489. _needsRenderUpdate( renderObject ) {
  21490. const data = this.get( renderObject );
  21491. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21492. }
  21493. }
  21494. /**
  21495. * This renderer module manages the bindings of the renderer.
  21496. *
  21497. * @private
  21498. * @augments DataMap
  21499. */
  21500. class Bindings extends DataMap {
  21501. /**
  21502. * Constructs a new bindings management component.
  21503. *
  21504. * @param {Backend} backend - The renderer's backend.
  21505. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21506. * @param {Textures} textures - Renderer component for managing textures.
  21507. * @param {Attributes} attributes - Renderer component for managing attributes.
  21508. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21509. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21510. */
  21511. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21512. super();
  21513. /**
  21514. * The renderer's backend.
  21515. *
  21516. * @type {Backend}
  21517. */
  21518. this.backend = backend;
  21519. /**
  21520. * Renderer component for managing textures.
  21521. *
  21522. * @type {Textures}
  21523. */
  21524. this.textures = textures;
  21525. /**
  21526. * Renderer component for managing pipelines.
  21527. *
  21528. * @type {Pipelines}
  21529. */
  21530. this.pipelines = pipelines;
  21531. /**
  21532. * Renderer component for managing attributes.
  21533. *
  21534. * @type {Attributes}
  21535. */
  21536. this.attributes = attributes;
  21537. /**
  21538. * Renderer component for managing nodes related logic.
  21539. *
  21540. * @type {Nodes}
  21541. */
  21542. this.nodes = nodes;
  21543. /**
  21544. * Renderer component for managing metrics and monitoring data.
  21545. *
  21546. * @type {Info}
  21547. */
  21548. this.info = info;
  21549. this.pipelines.bindings = this; // assign bindings to pipelines
  21550. }
  21551. /**
  21552. * Returns the bind groups for the given render object.
  21553. *
  21554. * @param {RenderObject} renderObject - The render object.
  21555. * @return {Array<BindGroup>} The bind groups.
  21556. */
  21557. getForRender( renderObject ) {
  21558. const bindings = renderObject.getBindings();
  21559. for ( const bindGroup of bindings ) {
  21560. const groupData = this.get( bindGroup );
  21561. if ( groupData.bindGroup === undefined ) {
  21562. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21563. this._init( bindGroup );
  21564. this.backend.createBindings( bindGroup, bindings, 0 );
  21565. groupData.bindGroup = bindGroup;
  21566. }
  21567. }
  21568. return bindings;
  21569. }
  21570. /**
  21571. * Returns the bind groups for the given compute node.
  21572. *
  21573. * @param {Node} computeNode - The compute node.
  21574. * @return {Array<BindGroup>} The bind groups.
  21575. */
  21576. getForCompute( computeNode ) {
  21577. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21578. for ( const bindGroup of bindings ) {
  21579. const groupData = this.get( bindGroup );
  21580. if ( groupData.bindGroup === undefined ) {
  21581. this._init( bindGroup );
  21582. this.backend.createBindings( bindGroup, bindings, 0 );
  21583. groupData.bindGroup = bindGroup;
  21584. }
  21585. }
  21586. return bindings;
  21587. }
  21588. /**
  21589. * Updates the bindings for the given compute node.
  21590. *
  21591. * @param {Node} computeNode - The compute node.
  21592. */
  21593. updateForCompute( computeNode ) {
  21594. this._updateBindings( this.getForCompute( computeNode ) );
  21595. }
  21596. /**
  21597. * Updates the bindings for the given render object.
  21598. *
  21599. * @param {RenderObject} renderObject - The render object.
  21600. */
  21601. updateForRender( renderObject ) {
  21602. this._updateBindings( this.getForRender( renderObject ) );
  21603. }
  21604. /**
  21605. * Deletes the bindings for the given compute node.
  21606. *
  21607. * @param {Node} computeNode - The compute node.
  21608. */
  21609. deleteForCompute( computeNode ) {
  21610. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21611. for ( const bindGroup of bindings ) {
  21612. this.delete( bindGroup );
  21613. }
  21614. }
  21615. /**
  21616. * Deletes the bindings for the given renderObject node.
  21617. *
  21618. * @param {RenderObject} renderObject - The renderObject.
  21619. */
  21620. deleteForRender( renderObject ) {
  21621. const bindings = renderObject.getBindings();
  21622. for ( const bindGroup of bindings ) {
  21623. this.delete( bindGroup );
  21624. }
  21625. }
  21626. /**
  21627. * Updates the given array of bindings.
  21628. *
  21629. * @param {Array<BindGroup>} bindings - The bind groups.
  21630. */
  21631. _updateBindings( bindings ) {
  21632. for ( const bindGroup of bindings ) {
  21633. this._update( bindGroup, bindings );
  21634. }
  21635. }
  21636. /**
  21637. * Initializes the given bind group.
  21638. *
  21639. * @param {BindGroup} bindGroup - The bind group to initialize.
  21640. */
  21641. _init( bindGroup ) {
  21642. for ( const binding of bindGroup.bindings ) {
  21643. if ( binding.isSampledTexture ) {
  21644. this.textures.updateTexture( binding.texture );
  21645. } else if ( binding.isSampler ) {
  21646. this.textures.updateSampler( binding.texture );
  21647. } else if ( binding.isStorageBuffer ) {
  21648. const attribute = binding.attribute;
  21649. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21650. this.attributes.update( attribute, attributeType );
  21651. }
  21652. }
  21653. }
  21654. /**
  21655. * Updates the given bind group.
  21656. *
  21657. * @param {BindGroup} bindGroup - The bind group to update.
  21658. * @param {Array<BindGroup>} bindings - The bind groups.
  21659. */
  21660. _update( bindGroup, bindings ) {
  21661. const { backend } = this;
  21662. let needsBindingsUpdate = false;
  21663. let cacheBindings = true;
  21664. let cacheIndex = 0;
  21665. let version = 0;
  21666. // iterate over all bindings and check if buffer updates or a new binding group is required
  21667. for ( const binding of bindGroup.bindings ) {
  21668. if ( binding.isNodeUniformsGroup ) {
  21669. const updated = this.nodes.updateGroup( binding );
  21670. // every uniforms group is a uniform buffer. So if no update is required,
  21671. // we move one with the next binding. Otherwise the next if block will update the group.
  21672. if ( updated === false ) continue;
  21673. }
  21674. if ( binding.isStorageBuffer ) {
  21675. const attribute = binding.attribute;
  21676. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21677. this.attributes.update( attribute, attributeType );
  21678. }
  21679. if ( binding.isUniformBuffer ) {
  21680. const updated = binding.update();
  21681. if ( updated ) {
  21682. backend.updateBinding( binding );
  21683. }
  21684. } else if ( binding.isSampledTexture ) {
  21685. const updated = binding.update();
  21686. // get the texture data after the update, to sync the texture reference from node
  21687. const texture = binding.texture;
  21688. const texturesTextureData = this.textures.get( texture );
  21689. if ( updated ) {
  21690. // version: update the texture data or create a new one
  21691. this.textures.updateTexture( texture );
  21692. // generation: update the bindings if a new texture has been created
  21693. if ( binding.generation !== texturesTextureData.generation ) {
  21694. binding.generation = texturesTextureData.generation;
  21695. needsBindingsUpdate = true;
  21696. cacheBindings = false;
  21697. }
  21698. }
  21699. const textureData = backend.get( texture );
  21700. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21701. cacheBindings = false;
  21702. } else {
  21703. cacheIndex = cacheIndex * 10 + texture.id;
  21704. version += texture.version;
  21705. }
  21706. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  21707. const textureData = this.get( texture );
  21708. if ( binding.store === true ) {
  21709. textureData.needsMipmap = true;
  21710. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21711. this.backend.generateMipmaps( texture );
  21712. textureData.needsMipmap = false;
  21713. }
  21714. }
  21715. } else if ( binding.isSampler ) {
  21716. const updated = binding.update();
  21717. if ( updated ) {
  21718. const samplerKey = this.textures.updateSampler( binding.texture );
  21719. if ( binding.samplerKey !== samplerKey ) {
  21720. binding.samplerKey = samplerKey;
  21721. needsBindingsUpdate = true;
  21722. cacheBindings = false;
  21723. }
  21724. }
  21725. }
  21726. }
  21727. if ( needsBindingsUpdate === true ) {
  21728. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21729. }
  21730. }
  21731. }
  21732. /**
  21733. * Default sorting function for opaque render items.
  21734. *
  21735. * @private
  21736. * @function
  21737. * @param {Object} a - The first render item.
  21738. * @param {Object} b - The second render item.
  21739. * @return {number} A numeric value which defines the sort order.
  21740. */
  21741. function painterSortStable( a, b ) {
  21742. if ( a.groupOrder !== b.groupOrder ) {
  21743. return a.groupOrder - b.groupOrder;
  21744. } else if ( a.renderOrder !== b.renderOrder ) {
  21745. return a.renderOrder - b.renderOrder;
  21746. } else if ( a.z !== b.z ) {
  21747. return a.z - b.z;
  21748. } else {
  21749. return a.id - b.id;
  21750. }
  21751. }
  21752. /**
  21753. * Default sorting function for transparent render items.
  21754. *
  21755. * @private
  21756. * @function
  21757. * @param {Object} a - The first render item.
  21758. * @param {Object} b - The second render item.
  21759. * @return {number} A numeric value which defines the sort order.
  21760. */
  21761. function reversePainterSortStable( a, b ) {
  21762. if ( a.groupOrder !== b.groupOrder ) {
  21763. return a.groupOrder - b.groupOrder;
  21764. } else if ( a.renderOrder !== b.renderOrder ) {
  21765. return a.renderOrder - b.renderOrder;
  21766. } else if ( a.z !== b.z ) {
  21767. return b.z - a.z;
  21768. } else {
  21769. return a.id - b.id;
  21770. }
  21771. }
  21772. /**
  21773. * Returns `true` if the given transparent material requires a double pass.
  21774. *
  21775. * @private
  21776. * @function
  21777. * @param {Material} material - The transparent material.
  21778. * @return {boolean} Whether the given material requires a double pass or not.
  21779. */
  21780. function needsDoublePass( material ) {
  21781. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21782. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21783. }
  21784. /**
  21785. * When the renderer analyzes the scene at the beginning of a render call,
  21786. * it stores 3D object for further processing in render lists. Depending on the
  21787. * properties of a 3D objects (like their transformation or material state), the
  21788. * objects are maintained in ordered lists for the actual rendering.
  21789. *
  21790. * Render lists are unique per scene and camera combination.
  21791. *
  21792. * @private
  21793. * @augments Pipeline
  21794. */
  21795. class RenderList {
  21796. /**
  21797. * Constructs a render list.
  21798. *
  21799. * @param {Lighting} lighting - The lighting management component.
  21800. * @param {Scene} scene - The scene.
  21801. * @param {Camera} camera - The camera the scene is rendered with.
  21802. */
  21803. constructor( lighting, scene, camera ) {
  21804. /**
  21805. * 3D objects are transformed into render items and stored in this array.
  21806. *
  21807. * @type {Array<Object>}
  21808. */
  21809. this.renderItems = [];
  21810. /**
  21811. * The current render items index.
  21812. *
  21813. * @type {number}
  21814. * @default 0
  21815. */
  21816. this.renderItemsIndex = 0;
  21817. /**
  21818. * A list with opaque render items.
  21819. *
  21820. * @type {Array<Object>}
  21821. */
  21822. this.opaque = [];
  21823. /**
  21824. * A list with transparent render items which require
  21825. * double pass rendering (e.g. transmissive objects).
  21826. *
  21827. * @type {Array<Object>}
  21828. */
  21829. this.transparentDoublePass = [];
  21830. /**
  21831. * A list with transparent render items.
  21832. *
  21833. * @type {Array<Object>}
  21834. */
  21835. this.transparent = [];
  21836. /**
  21837. * A list with transparent render bundle data.
  21838. *
  21839. * @type {Array<Object>}
  21840. */
  21841. this.bundles = [];
  21842. /**
  21843. * The render list's lights node. This node is later
  21844. * relevant for the actual analytical light nodes which
  21845. * compute the scene's lighting in the shader.
  21846. *
  21847. * @type {LightsNode}
  21848. */
  21849. this.lightsNode = lighting.getNode( scene, camera );
  21850. /**
  21851. * The scene's lights stored in an array. This array
  21852. * is used to setup the lights node.
  21853. *
  21854. * @type {Array<Light>}
  21855. */
  21856. this.lightsArray = [];
  21857. /**
  21858. * The scene.
  21859. *
  21860. * @type {Scene}
  21861. */
  21862. this.scene = scene;
  21863. /**
  21864. * The camera the scene is rendered with.
  21865. *
  21866. * @type {Camera}
  21867. */
  21868. this.camera = camera;
  21869. /**
  21870. * How many objects perform occlusion query tests.
  21871. *
  21872. * @type {number}
  21873. * @default 0
  21874. */
  21875. this.occlusionQueryCount = 0;
  21876. }
  21877. /**
  21878. * This method is called right at the beginning of a render call
  21879. * before the scene is analyzed. It prepares the internal data
  21880. * structures for the upcoming render lists generation.
  21881. *
  21882. * @return {RenderList} A reference to this render list.
  21883. */
  21884. begin() {
  21885. this.renderItemsIndex = 0;
  21886. this.opaque.length = 0;
  21887. this.transparentDoublePass.length = 0;
  21888. this.transparent.length = 0;
  21889. this.bundles.length = 0;
  21890. this.lightsArray.length = 0;
  21891. this.occlusionQueryCount = 0;
  21892. return this;
  21893. }
  21894. /**
  21895. * Returns a render item for the giving render item state. The state is defined
  21896. * by a series of object-related parameters.
  21897. *
  21898. * The method avoids object creation by holding render items and reusing them in
  21899. * subsequent render calls (just with different property values).
  21900. *
  21901. * @param {Object3D} object - The 3D object.
  21902. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21903. * @param {Material} material - The 3D object's material.
  21904. * @param {number} groupOrder - The current group order.
  21905. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21906. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21907. * @param {ClippingContext} clippingContext - The current clipping context.
  21908. * @return {Object} The render item.
  21909. */
  21910. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21911. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21912. if ( renderItem === undefined ) {
  21913. renderItem = {
  21914. id: object.id,
  21915. object: object,
  21916. geometry: geometry,
  21917. material: material,
  21918. groupOrder: groupOrder,
  21919. renderOrder: object.renderOrder,
  21920. z: z,
  21921. group: group,
  21922. clippingContext: clippingContext
  21923. };
  21924. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21925. } else {
  21926. renderItem.id = object.id;
  21927. renderItem.object = object;
  21928. renderItem.geometry = geometry;
  21929. renderItem.material = material;
  21930. renderItem.groupOrder = groupOrder;
  21931. renderItem.renderOrder = object.renderOrder;
  21932. renderItem.z = z;
  21933. renderItem.group = group;
  21934. renderItem.clippingContext = clippingContext;
  21935. }
  21936. this.renderItemsIndex ++;
  21937. return renderItem;
  21938. }
  21939. /**
  21940. * Pushes the given object as a render item to the internal render lists.
  21941. * The selected lists depend on the object properties.
  21942. *
  21943. * @param {Object3D} object - The 3D object.
  21944. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21945. * @param {Material} material - The 3D object's material.
  21946. * @param {number} groupOrder - The current group order.
  21947. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21948. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21949. * @param {ClippingContext} clippingContext - The current clipping context.
  21950. */
  21951. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21952. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21953. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21954. if ( material.transparent === true || material.transmission > 0 ) {
  21955. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21956. this.transparent.push( renderItem );
  21957. } else {
  21958. this.opaque.push( renderItem );
  21959. }
  21960. }
  21961. /**
  21962. * Inserts the given object as a render item at the start of the internal render lists.
  21963. * The selected lists depend on the object properties.
  21964. *
  21965. * @param {Object3D} object - The 3D object.
  21966. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21967. * @param {Material} material - The 3D object's material.
  21968. * @param {number} groupOrder - The current group order.
  21969. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21970. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21971. * @param {ClippingContext} clippingContext - The current clipping context.
  21972. */
  21973. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21974. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21975. if ( material.transparent === true || material.transmission > 0 ) {
  21976. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21977. this.transparent.unshift( renderItem );
  21978. } else {
  21979. this.opaque.unshift( renderItem );
  21980. }
  21981. }
  21982. /**
  21983. * Pushes render bundle group data into the render list.
  21984. *
  21985. * @param {Object} group - Bundle group data.
  21986. */
  21987. pushBundle( group ) {
  21988. this.bundles.push( group );
  21989. }
  21990. /**
  21991. * Pushes a light into the render list.
  21992. *
  21993. * @param {Light} light - The light.
  21994. */
  21995. pushLight( light ) {
  21996. this.lightsArray.push( light );
  21997. }
  21998. /**
  21999. * Sorts the internal render lists.
  22000. *
  22001. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22002. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22003. */
  22004. sort( customOpaqueSort, customTransparentSort ) {
  22005. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22006. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22007. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22008. }
  22009. /**
  22010. * This method performs finalizing tasks right after the render lists
  22011. * have been generated.
  22012. */
  22013. finish() {
  22014. // update lights
  22015. this.lightsNode.setLights( this.lightsArray );
  22016. // Clear references from inactive renderItems in the list
  22017. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22018. const renderItem = this.renderItems[ i ];
  22019. if ( renderItem.id === null ) break;
  22020. renderItem.id = null;
  22021. renderItem.object = null;
  22022. renderItem.geometry = null;
  22023. renderItem.material = null;
  22024. renderItem.groupOrder = null;
  22025. renderItem.renderOrder = null;
  22026. renderItem.z = null;
  22027. renderItem.group = null;
  22028. renderItem.clippingContext = null;
  22029. }
  22030. }
  22031. }
  22032. const _chainKeys$4 = [];
  22033. /**
  22034. * This renderer module manages the render lists which are unique
  22035. * per scene and camera combination.
  22036. *
  22037. * @private
  22038. */
  22039. class RenderLists {
  22040. /**
  22041. * Constructs a render lists management component.
  22042. *
  22043. * @param {Lighting} lighting - The lighting management component.
  22044. */
  22045. constructor( lighting ) {
  22046. /**
  22047. * The lighting management component.
  22048. *
  22049. * @type {Lighting}
  22050. */
  22051. this.lighting = lighting;
  22052. /**
  22053. * The internal chain map which holds the render lists.
  22054. *
  22055. * @type {ChainMap}
  22056. */
  22057. this.lists = new ChainMap();
  22058. }
  22059. /**
  22060. * Returns a render list for the given scene and camera.
  22061. *
  22062. * @param {Scene} scene - The scene.
  22063. * @param {Camera} camera - The camera.
  22064. * @return {RenderList} The render list.
  22065. */
  22066. get( scene, camera ) {
  22067. const lists = this.lists;
  22068. _chainKeys$4[ 0 ] = scene;
  22069. _chainKeys$4[ 1 ] = camera;
  22070. let list = lists.get( _chainKeys$4 );
  22071. if ( list === undefined ) {
  22072. list = new RenderList( this.lighting, scene, camera );
  22073. lists.set( _chainKeys$4, list );
  22074. }
  22075. _chainKeys$4.length = 0;
  22076. return list;
  22077. }
  22078. /**
  22079. * Frees all internal resources.
  22080. */
  22081. dispose() {
  22082. this.lists = new ChainMap();
  22083. }
  22084. }
  22085. let _id$7 = 0;
  22086. /**
  22087. * Any render or compute command is executed in a specific context that defines
  22088. * the state of the renderer and its backend. Typical examples for such context
  22089. * data are the current clear values or data from the active framebuffer. This
  22090. * module is used to represent these contexts as objects.
  22091. *
  22092. * @private
  22093. */
  22094. class RenderContext {
  22095. /**
  22096. * Constructs a new render context.
  22097. */
  22098. constructor() {
  22099. /**
  22100. * The context's ID.
  22101. *
  22102. * @type {number}
  22103. */
  22104. this.id = _id$7 ++;
  22105. /**
  22106. * Whether the current active framebuffer has a color attachment.
  22107. *
  22108. * @type {boolean}
  22109. * @default true
  22110. */
  22111. this.color = true;
  22112. /**
  22113. * Whether the color attachment should be cleared or not.
  22114. *
  22115. * @type {boolean}
  22116. * @default true
  22117. */
  22118. this.clearColor = true;
  22119. /**
  22120. * The clear color value.
  22121. *
  22122. * @type {Object}
  22123. * @default true
  22124. */
  22125. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22126. /**
  22127. * Whether the current active framebuffer has a depth attachment.
  22128. *
  22129. * @type {boolean}
  22130. * @default true
  22131. */
  22132. this.depth = true;
  22133. /**
  22134. * Whether the depth attachment should be cleared or not.
  22135. *
  22136. * @type {boolean}
  22137. * @default true
  22138. */
  22139. this.clearDepth = true;
  22140. /**
  22141. * The clear depth value.
  22142. *
  22143. * @type {number}
  22144. * @default 1
  22145. */
  22146. this.clearDepthValue = 1;
  22147. /**
  22148. * Whether the current active framebuffer has a stencil attachment.
  22149. *
  22150. * @type {boolean}
  22151. * @default false
  22152. */
  22153. this.stencil = false;
  22154. /**
  22155. * Whether the stencil attachment should be cleared or not.
  22156. *
  22157. * @type {boolean}
  22158. * @default true
  22159. */
  22160. this.clearStencil = true;
  22161. /**
  22162. * The clear stencil value.
  22163. *
  22164. * @type {number}
  22165. * @default 1
  22166. */
  22167. this.clearStencilValue = 1;
  22168. /**
  22169. * By default the viewport encloses the entire framebuffer If a smaller
  22170. * viewport is manually defined, this property is to `true` by the renderer.
  22171. *
  22172. * @type {boolean}
  22173. * @default false
  22174. */
  22175. this.viewport = false;
  22176. /**
  22177. * The viewport value. This value is in physical pixels meaning it incorporates
  22178. * the renderer's pixel ratio. The viewport property of render targets or
  22179. * the renderer is in logical pixels.
  22180. *
  22181. * @type {Vector4}
  22182. */
  22183. this.viewportValue = new Vector4();
  22184. /**
  22185. * When the scissor test is active and scissor rectangle smaller than the
  22186. * framebuffers dimensions, this property is to `true` by the renderer.
  22187. *
  22188. * @type {boolean}
  22189. * @default false
  22190. */
  22191. this.scissor = false;
  22192. /**
  22193. * The scissor rectangle.
  22194. *
  22195. * @type {Vector4}
  22196. */
  22197. this.scissorValue = new Vector4();
  22198. /**
  22199. * The active render target.
  22200. *
  22201. * @type {?RenderTarget}
  22202. * @default null
  22203. */
  22204. this.renderTarget = null;
  22205. /**
  22206. * The textures of the active render target.
  22207. * `null` when no render target is set.
  22208. *
  22209. * @type {?Array<Texture>}
  22210. * @default null
  22211. */
  22212. this.textures = null;
  22213. /**
  22214. * The depth texture of the active render target.
  22215. * `null` when no render target is set.
  22216. *
  22217. * @type {?DepthTexture}
  22218. * @default null
  22219. */
  22220. this.depthTexture = null;
  22221. /**
  22222. * The active cube face.
  22223. *
  22224. * @type {number}
  22225. * @default 0
  22226. */
  22227. this.activeCubeFace = 0;
  22228. /**
  22229. * The active mipmap level.
  22230. *
  22231. * @type {number}
  22232. * @default 0
  22233. */
  22234. this.activeMipmapLevel = 0;
  22235. /**
  22236. * The number of MSAA samples. This value is always `1` when
  22237. * MSAA isn't used.
  22238. *
  22239. * @type {number}
  22240. * @default 1
  22241. */
  22242. this.sampleCount = 1;
  22243. /**
  22244. * The active render target's width in physical pixels.
  22245. *
  22246. * @type {number}
  22247. * @default 0
  22248. */
  22249. this.width = 0;
  22250. /**
  22251. * The active render target's height in physical pixels.
  22252. *
  22253. * @type {number}
  22254. * @default 0
  22255. */
  22256. this.height = 0;
  22257. /**
  22258. * The occlusion query count.
  22259. *
  22260. * @type {number}
  22261. * @default 0
  22262. */
  22263. this.occlusionQueryCount = 0;
  22264. /**
  22265. * The current clipping context.
  22266. *
  22267. * @type {?ClippingContext}
  22268. * @default null
  22269. */
  22270. this.clippingContext = null;
  22271. /**
  22272. * This flag can be used for type testing.
  22273. *
  22274. * @type {boolean}
  22275. * @readonly
  22276. * @default true
  22277. */
  22278. this.isRenderContext = true;
  22279. }
  22280. /**
  22281. * Returns the cache key of this render context.
  22282. *
  22283. * @return {number} The cache key.
  22284. */
  22285. getCacheKey() {
  22286. return getCacheKey( this );
  22287. }
  22288. }
  22289. /**
  22290. * Computes a cache key for the given render context. This key
  22291. * should identify the render target state so it is possible to
  22292. * configure the correct attachments in the respective backend.
  22293. *
  22294. * @param {RenderContext} renderContext - The render context.
  22295. * @return {number} The cache key.
  22296. */
  22297. function getCacheKey( renderContext ) {
  22298. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22299. const values = [ activeCubeFace, activeMipmapLevel ];
  22300. for ( const texture of textures ) {
  22301. values.push( texture.id );
  22302. }
  22303. return hashArray( values );
  22304. }
  22305. const _chainKeys$3 = [];
  22306. const _defaultScene = /*@__PURE__*/ new Scene();
  22307. const _defaultCamera = /*@__PURE__*/ new Camera();
  22308. /**
  22309. * This module manages the render contexts of the renderer.
  22310. *
  22311. * @private
  22312. */
  22313. class RenderContexts {
  22314. /**
  22315. * Constructs a new render context management component.
  22316. */
  22317. constructor() {
  22318. /**
  22319. * A dictionary that manages render contexts in chain maps
  22320. * for each attachment state.
  22321. *
  22322. * @type {Object<string,ChainMap>}
  22323. */
  22324. this.chainMaps = {};
  22325. }
  22326. /**
  22327. * Returns a render context for the given scene, camera and render target.
  22328. *
  22329. * @param {Scene} scene - The scene.
  22330. * @param {Camera} camera - The camera that is used to render the scene.
  22331. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22332. * @return {RenderContext} The render context.
  22333. */
  22334. get( scene, camera, renderTarget = null ) {
  22335. _chainKeys$3[ 0 ] = scene;
  22336. _chainKeys$3[ 1 ] = camera;
  22337. let attachmentState;
  22338. if ( renderTarget === null ) {
  22339. attachmentState = 'default';
  22340. } else {
  22341. const format = renderTarget.texture.format;
  22342. const count = renderTarget.textures.length;
  22343. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22344. }
  22345. const chainMap = this._getChainMap( attachmentState );
  22346. let renderState = chainMap.get( _chainKeys$3 );
  22347. if ( renderState === undefined ) {
  22348. renderState = new RenderContext();
  22349. chainMap.set( _chainKeys$3, renderState );
  22350. }
  22351. _chainKeys$3.length = 0;
  22352. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22353. return renderState;
  22354. }
  22355. /**
  22356. * Returns a render context intended for clear operations.
  22357. *
  22358. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22359. * @return {RenderContext} The render context.
  22360. */
  22361. getForClear( renderTarget = null ) {
  22362. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22363. }
  22364. /**
  22365. * Returns a chain map for the given attachment state.
  22366. *
  22367. * @private
  22368. * @param {string} attachmentState - The attachment state.
  22369. * @return {ChainMap} The chain map.
  22370. */
  22371. _getChainMap( attachmentState ) {
  22372. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22373. }
  22374. /**
  22375. * Frees internal resources.
  22376. */
  22377. dispose() {
  22378. this.chainMaps = {};
  22379. }
  22380. }
  22381. const _size$3 = /*@__PURE__*/ new Vector3();
  22382. /**
  22383. * This module manages the textures of the renderer.
  22384. *
  22385. * @private
  22386. * @augments DataMap
  22387. */
  22388. class Textures extends DataMap {
  22389. /**
  22390. * Constructs a new texture management component.
  22391. *
  22392. * @param {Renderer} renderer - The renderer.
  22393. * @param {Backend} backend - The renderer's backend.
  22394. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22395. */
  22396. constructor( renderer, backend, info ) {
  22397. super();
  22398. /**
  22399. * The renderer.
  22400. *
  22401. * @type {Renderer}
  22402. */
  22403. this.renderer = renderer;
  22404. /**
  22405. * The backend.
  22406. *
  22407. * @type {Backend}
  22408. */
  22409. this.backend = backend;
  22410. /**
  22411. * Renderer component for managing metrics and monitoring data.
  22412. *
  22413. * @type {Info}
  22414. */
  22415. this.info = info;
  22416. }
  22417. /**
  22418. * Updates the given render target. Based on the given render target configuration,
  22419. * it updates the texture states representing the attachments of the framebuffer.
  22420. *
  22421. * @param {RenderTarget} renderTarget - The render target to update.
  22422. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22423. */
  22424. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22425. const renderTargetData = this.get( renderTarget );
  22426. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22427. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22428. const textures = renderTarget.textures;
  22429. const size = this.getSize( textures[ 0 ] );
  22430. const mipWidth = size.width >> activeMipmapLevel;
  22431. const mipHeight = size.height >> activeMipmapLevel;
  22432. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22433. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22434. let textureNeedsUpdate = false;
  22435. if ( depthTexture === undefined && useDepthTexture ) {
  22436. depthTexture = new DepthTexture();
  22437. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22438. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22439. depthTexture.image.width = mipWidth;
  22440. depthTexture.image.height = mipHeight;
  22441. depthTexture.image.depth = size.depth;
  22442. depthTexture.renderTarget = renderTarget;
  22443. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22444. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22445. }
  22446. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22447. textureNeedsUpdate = true;
  22448. if ( depthTexture ) {
  22449. depthTexture.needsUpdate = true;
  22450. depthTexture.image.width = mipWidth;
  22451. depthTexture.image.height = mipHeight;
  22452. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22453. }
  22454. }
  22455. renderTargetData.width = size.width;
  22456. renderTargetData.height = size.height;
  22457. renderTargetData.textures = textures;
  22458. renderTargetData.depthTexture = depthTexture || null;
  22459. renderTargetData.depth = renderTarget.depthBuffer;
  22460. renderTargetData.stencil = renderTarget.stencilBuffer;
  22461. renderTargetData.renderTarget = renderTarget;
  22462. if ( renderTargetData.sampleCount !== sampleCount ) {
  22463. textureNeedsUpdate = true;
  22464. if ( depthTexture ) {
  22465. depthTexture.needsUpdate = true;
  22466. }
  22467. renderTargetData.sampleCount = sampleCount;
  22468. }
  22469. //
  22470. const options = { sampleCount };
  22471. // XR render targets require no texture updates
  22472. if ( renderTarget.isXRRenderTarget !== true ) {
  22473. for ( let i = 0; i < textures.length; i ++ ) {
  22474. const texture = textures[ i ];
  22475. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22476. this.updateTexture( texture, options );
  22477. }
  22478. if ( depthTexture ) {
  22479. this.updateTexture( depthTexture, options );
  22480. }
  22481. }
  22482. // dispose handler
  22483. if ( renderTargetData.initialized !== true ) {
  22484. renderTargetData.initialized = true;
  22485. // dispose
  22486. const onDispose = () => {
  22487. renderTarget.removeEventListener( 'dispose', onDispose );
  22488. for ( let i = 0; i < textures.length; i ++ ) {
  22489. this._destroyTexture( textures[ i ] );
  22490. }
  22491. if ( depthTexture ) {
  22492. this._destroyTexture( depthTexture );
  22493. }
  22494. this.delete( renderTarget );
  22495. this.backend.delete( renderTarget );
  22496. };
  22497. renderTarget.addEventListener( 'dispose', onDispose );
  22498. }
  22499. }
  22500. /**
  22501. * Updates the given texture. Depending on the texture state, this method
  22502. * triggers the upload of texture data to the GPU memory. If the texture data are
  22503. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22504. *
  22505. * @param {Texture} texture - The texture to update.
  22506. * @param {Object} [options={}] - The options.
  22507. */
  22508. updateTexture( texture, options = {} ) {
  22509. const textureData = this.get( texture );
  22510. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22511. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22512. const backend = this.backend;
  22513. if ( isRenderTarget && textureData.initialized === true ) {
  22514. // it's an update
  22515. backend.destroyTexture( texture );
  22516. }
  22517. //
  22518. if ( texture.isFramebufferTexture ) {
  22519. const renderTarget = this.renderer.getRenderTarget();
  22520. if ( renderTarget ) {
  22521. texture.type = renderTarget.texture.type;
  22522. } else {
  22523. texture.type = UnsignedByteType;
  22524. }
  22525. }
  22526. //
  22527. const { width, height, depth } = this.getSize( texture );
  22528. options.width = width;
  22529. options.height = height;
  22530. options.depth = depth;
  22531. options.needsMipmaps = this.needsMipmaps( texture );
  22532. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22533. // TODO: Uniformly handle mipmap definitions
  22534. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22535. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22536. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22537. //
  22538. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22539. backend.createTexture( texture, options );
  22540. textureData.generation = texture.version;
  22541. } else {
  22542. if ( texture.version > 0 ) {
  22543. const image = texture.image;
  22544. if ( image === undefined ) {
  22545. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22546. } else if ( image.complete === false ) {
  22547. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22548. } else {
  22549. if ( texture.images ) {
  22550. const images = [];
  22551. for ( const image of texture.images ) {
  22552. images.push( image );
  22553. }
  22554. options.images = images;
  22555. } else {
  22556. options.image = image;
  22557. }
  22558. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22559. backend.createTexture( texture, options );
  22560. textureData.isDefaultTexture = false;
  22561. textureData.generation = texture.version;
  22562. }
  22563. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22564. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  22565. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  22566. backend.generateMipmaps( texture );
  22567. }
  22568. if ( texture.onUpdate ) texture.onUpdate( texture );
  22569. }
  22570. } else {
  22571. // async update
  22572. backend.createDefaultTexture( texture );
  22573. textureData.isDefaultTexture = true;
  22574. textureData.generation = texture.version;
  22575. }
  22576. }
  22577. // dispose handler
  22578. if ( textureData.initialized !== true ) {
  22579. textureData.initialized = true;
  22580. textureData.generation = texture.version;
  22581. //
  22582. this.info.memory.textures ++;
  22583. //
  22584. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22585. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22586. }
  22587. // dispose
  22588. const onDispose = () => {
  22589. texture.removeEventListener( 'dispose', onDispose );
  22590. this._destroyTexture( texture );
  22591. };
  22592. texture.addEventListener( 'dispose', onDispose );
  22593. }
  22594. //
  22595. textureData.version = texture.version;
  22596. }
  22597. /**
  22598. * Updates the sampler for the given texture. This method has no effect
  22599. * for the WebGL backend since it has no concept of samplers. Texture
  22600. * parameters are configured with the `texParameter()` command for each
  22601. * texture.
  22602. *
  22603. * In WebGPU, samplers are objects like textures and it's possible to share
  22604. * them when the texture parameters match.
  22605. *
  22606. * @param {Texture} texture - The texture to update the sampler for.
  22607. * @return {string} The current sampler key.
  22608. */
  22609. updateSampler( texture ) {
  22610. return this.backend.updateSampler( texture );
  22611. }
  22612. /**
  22613. * Computes the size of the given texture and writes the result
  22614. * into the target vector. This vector is also returned by the
  22615. * method.
  22616. *
  22617. * If no texture data are available for the compute yet, the method
  22618. * returns default size values.
  22619. *
  22620. * @param {Texture} texture - The texture to compute the size for.
  22621. * @param {Vector3} target - The target vector.
  22622. * @return {Vector3} The target vector.
  22623. */
  22624. getSize( texture, target = _size$3 ) {
  22625. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22626. if ( image ) {
  22627. if ( image.image !== undefined ) image = image.image;
  22628. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22629. target.width = image.videoWidth || 1;
  22630. target.height = image.videoHeight || 1;
  22631. target.depth = 1;
  22632. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22633. target.width = image.displayWidth || 1;
  22634. target.height = image.displayHeight || 1;
  22635. target.depth = 1;
  22636. } else {
  22637. target.width = image.width || 1;
  22638. target.height = image.height || 1;
  22639. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22640. }
  22641. } else {
  22642. target.width = target.height = target.depth = 1;
  22643. }
  22644. return target;
  22645. }
  22646. /**
  22647. * Computes the number of mipmap levels for the given texture.
  22648. *
  22649. * @param {Texture} texture - The texture.
  22650. * @param {number} width - The texture's width.
  22651. * @param {number} height - The texture's height.
  22652. * @return {number} The number of mipmap levels.
  22653. */
  22654. getMipLevels( texture, width, height ) {
  22655. let mipLevelCount;
  22656. if ( texture.mipmaps.length > 0 ) {
  22657. mipLevelCount = texture.mipmaps.length;
  22658. } else {
  22659. if ( texture.isCompressedTexture === true ) {
  22660. // it is not possible to compute mipmaps for compressed textures. So
  22661. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22662. // level of 1
  22663. mipLevelCount = 1;
  22664. } else {
  22665. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22666. }
  22667. }
  22668. return mipLevelCount;
  22669. }
  22670. /**
  22671. * Returns `true` if the given texture makes use of mipmapping.
  22672. *
  22673. * @param {Texture} texture - The texture.
  22674. * @return {boolean} Whether mipmaps are required or not.
  22675. */
  22676. needsMipmaps( texture ) {
  22677. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22678. }
  22679. /**
  22680. * Frees internal resource when the given texture isn't
  22681. * required anymore.
  22682. *
  22683. * @param {Texture} texture - The texture to destroy.
  22684. */
  22685. _destroyTexture( texture ) {
  22686. if ( this.has( texture ) === true ) {
  22687. // if a texture is not ready for use, it falls back to a default texture so it's possible
  22688. // to use it for rendering. If a texture in this state is disposed, it's important to
  22689. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  22690. // other textures.
  22691. const isDefaultTexture = this.get( texture ).isDefaultTexture;
  22692. this.backend.destroyTexture( texture, isDefaultTexture );
  22693. this.delete( texture );
  22694. this.info.memory.textures --;
  22695. }
  22696. }
  22697. }
  22698. /**
  22699. * A four-component version of {@link Color} which is internally
  22700. * used by the renderer to represents clear color with alpha as
  22701. * one object.
  22702. *
  22703. * @private
  22704. * @augments Color
  22705. */
  22706. class Color4 extends Color {
  22707. /**
  22708. * Constructs a new four-component color.
  22709. * You can also pass a single THREE.Color, hex or
  22710. * string argument to this constructor.
  22711. *
  22712. * @param {number|string} [r=1] - The red value.
  22713. * @param {number} [g=1] - The green value.
  22714. * @param {number} [b=1] - The blue value.
  22715. * @param {number} [a=1] - The alpha value.
  22716. */
  22717. constructor( r, g, b, a = 1 ) {
  22718. super( r, g, b );
  22719. this.a = a;
  22720. }
  22721. /**
  22722. * Overwrites the default to honor alpha.
  22723. * You can also pass a single THREE.Color, hex or
  22724. * string argument to this method.
  22725. *
  22726. * @param {number|string|Color} r - The red value.
  22727. * @param {number} [g] - The green value.
  22728. * @param {number} [b] - The blue value.
  22729. * @param {number} [a=1] - The alpha value.
  22730. * @return {Color4} A reference to this object.
  22731. */
  22732. set( r, g, b, a = 1 ) {
  22733. this.a = a;
  22734. return super.set( r, g, b );
  22735. }
  22736. /**
  22737. * Overwrites the default to honor alpha.
  22738. *
  22739. * @param {Color4} color - The color to copy.
  22740. * @return {Color4} A reference to this object.
  22741. */
  22742. copy( color ) {
  22743. if ( color.a !== undefined ) this.a = color.a;
  22744. return super.copy( color );
  22745. }
  22746. /**
  22747. * Overwrites the default to honor alpha.
  22748. *
  22749. * @return {Color4} The cloned color.
  22750. */
  22751. clone() {
  22752. return new this.constructor( this.r, this.g, this.b, this.a );
  22753. }
  22754. }
  22755. /**
  22756. * Special version of {@link PropertyNode} which is used for parameters.
  22757. *
  22758. * @augments PropertyNode
  22759. */
  22760. class ParameterNode extends PropertyNode {
  22761. static get type() {
  22762. return 'ParameterNode';
  22763. }
  22764. /**
  22765. * Constructs a new parameter node.
  22766. *
  22767. * @param {string} nodeType - The type of the node.
  22768. * @param {?string} [name=null] - The name of the parameter in the shader.
  22769. */
  22770. constructor( nodeType, name = null ) {
  22771. super( nodeType, name );
  22772. /**
  22773. * This flag can be used for type testing.
  22774. *
  22775. * @type {boolean}
  22776. * @readonly
  22777. * @default true
  22778. */
  22779. this.isParameterNode = true;
  22780. }
  22781. /**
  22782. * Gets the type of a member variable in the parameter node.
  22783. *
  22784. * @param {NodeBuilder} builder - The node builder.
  22785. * @param {string} name - The name of the member variable.
  22786. * @returns {string}
  22787. */
  22788. getMemberType( builder, name ) {
  22789. const type = this.getNodeType( builder );
  22790. const struct = builder.getStructTypeNode( type );
  22791. let memberType;
  22792. if ( struct !== null ) {
  22793. memberType = struct.getMemberType( builder, name );
  22794. } else {
  22795. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  22796. memberType = 'float';
  22797. }
  22798. return memberType;
  22799. }
  22800. getHash() {
  22801. return this.uuid;
  22802. }
  22803. generate() {
  22804. return this.name;
  22805. }
  22806. }
  22807. /**
  22808. * TSL function for creating a parameter node.
  22809. *
  22810. * @tsl
  22811. * @function
  22812. * @param {string} type - The type of the node.
  22813. * @param {?string} name - The name of the parameter in the shader.
  22814. * @returns {ParameterNode}
  22815. */
  22816. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22817. /**
  22818. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22819. * They are usually needed in cases like `If`, `Else`.
  22820. *
  22821. * @augments Node
  22822. */
  22823. class StackNode extends Node {
  22824. static get type() {
  22825. return 'StackNode';
  22826. }
  22827. /**
  22828. * Constructs a new stack node.
  22829. *
  22830. * @param {?StackNode} [parent=null] - The parent stack node.
  22831. */
  22832. constructor( parent = null ) {
  22833. super();
  22834. /**
  22835. * List of nodes.
  22836. *
  22837. * @type {Array<Node>}
  22838. */
  22839. this.nodes = [];
  22840. /**
  22841. * The output node.
  22842. *
  22843. * @type {?Node}
  22844. * @default null
  22845. */
  22846. this.outputNode = null;
  22847. /**
  22848. * The parent stack node.
  22849. *
  22850. * @type {?StackNode}
  22851. * @default null
  22852. */
  22853. this.parent = parent;
  22854. /**
  22855. * The current conditional node.
  22856. *
  22857. * @private
  22858. * @type {ConditionalNode}
  22859. * @default null
  22860. */
  22861. this._currentCond = null;
  22862. /**
  22863. * The expression node. Only
  22864. * relevant for Switch/Case.
  22865. *
  22866. * @private
  22867. * @type {Node}
  22868. * @default null
  22869. */
  22870. this._expressionNode = null;
  22871. /**
  22872. * This flag can be used for type testing.
  22873. *
  22874. * @type {boolean}
  22875. * @readonly
  22876. * @default true
  22877. */
  22878. this.isStackNode = true;
  22879. }
  22880. getNodeType( builder ) {
  22881. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22882. }
  22883. getMemberType( builder, name ) {
  22884. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22885. }
  22886. /**
  22887. * Adds a node to this stack.
  22888. *
  22889. * @param {Node} node - The node to add.
  22890. * @return {StackNode} A reference to this stack node.
  22891. */
  22892. addToStack( node ) {
  22893. if ( node.isNode !== true ) {
  22894. error( 'TSL: Invalid node added to stack.' );
  22895. return this;
  22896. }
  22897. this.nodes.push( node );
  22898. return this;
  22899. }
  22900. /**
  22901. * Represent an `if` statement in TSL.
  22902. *
  22903. * @param {Node} boolNode - Represents the condition.
  22904. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22905. * @return {StackNode} A reference to this stack node.
  22906. */
  22907. If( boolNode, method ) {
  22908. const methodNode = new ShaderNode( method );
  22909. this._currentCond = select( boolNode, methodNode );
  22910. return this.addToStack( this._currentCond );
  22911. }
  22912. /**
  22913. * Represent an `elseif` statement in TSL.
  22914. *
  22915. * @param {Node} boolNode - Represents the condition.
  22916. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22917. * @return {StackNode} A reference to this stack node.
  22918. */
  22919. ElseIf( boolNode, method ) {
  22920. const methodNode = new ShaderNode( method );
  22921. const ifNode = select( boolNode, methodNode );
  22922. this._currentCond.elseNode = ifNode;
  22923. this._currentCond = ifNode;
  22924. return this;
  22925. }
  22926. /**
  22927. * Represent an `else` statement in TSL.
  22928. *
  22929. * @param {Function} method - TSL code which is executed in the `else` case.
  22930. * @return {StackNode} A reference to this stack node.
  22931. */
  22932. Else( method ) {
  22933. this._currentCond.elseNode = new ShaderNode( method );
  22934. return this;
  22935. }
  22936. /**
  22937. * Represents a `switch` statement in TSL.
  22938. *
  22939. * @param {any} expression - Represents the expression.
  22940. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22941. * @return {StackNode} A reference to this stack node.
  22942. */
  22943. Switch( expression ) {
  22944. this._expressionNode = nodeObject( expression );
  22945. return this;
  22946. }
  22947. /**
  22948. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22949. * The last parameter must be the callback method that should be executed in the `true` case.
  22950. *
  22951. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22952. * @return {StackNode} A reference to this stack node.
  22953. */
  22954. Case( ...params ) {
  22955. const caseNodes = [];
  22956. // extract case nodes from the parameter list
  22957. if ( params.length >= 2 ) {
  22958. for ( let i = 0; i < params.length - 1; i ++ ) {
  22959. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22960. }
  22961. } else {
  22962. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22963. }
  22964. // extract method
  22965. const method = params[ params.length - 1 ];
  22966. const methodNode = new ShaderNode( method );
  22967. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22968. let caseNode = caseNodes[ 0 ];
  22969. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22970. caseNode = caseNode.or( caseNodes[ i ] );
  22971. }
  22972. // build condition
  22973. const condNode = select( caseNode, methodNode );
  22974. if ( this._currentCond === null ) {
  22975. this._currentCond = condNode;
  22976. return this.addToStack( this._currentCond );
  22977. } else {
  22978. this._currentCond.elseNode = condNode;
  22979. this._currentCond = condNode;
  22980. return this;
  22981. }
  22982. }
  22983. /**
  22984. * Represents the default code block of a Switch/Case statement.
  22985. *
  22986. * @param {Function} method - TSL code which is executed in the `else` case.
  22987. * @return {StackNode} A reference to this stack node.
  22988. */
  22989. Default( method ) {
  22990. this.Else( method );
  22991. return this;
  22992. }
  22993. setup( builder ) {
  22994. const nodeProperties = builder.getNodeProperties( this );
  22995. let index = 0;
  22996. for ( const childNode of this.getChildren() ) {
  22997. if ( childNode.isVarNode && childNode.intent === true ) {
  22998. if ( childNode.isAssign( builder ) !== true ) {
  22999. continue;
  23000. }
  23001. }
  23002. nodeProperties[ 'node' + index ++ ] = childNode;
  23003. }
  23004. // return a outputNode if exists or null
  23005. return nodeProperties.outputNode || null;
  23006. }
  23007. get hasOutput() {
  23008. return this.outputNode && this.outputNode.isNode;
  23009. }
  23010. build( builder, ...params ) {
  23011. const previousBuildStack = builder.currentStack;
  23012. const previousStack = getCurrentStack();
  23013. setCurrentStack( this );
  23014. builder.currentStack = this;
  23015. const buildStage = builder.buildStage;
  23016. for ( const node of this.nodes ) {
  23017. if ( node.isVarNode && node.intent === true ) {
  23018. if ( node.isAssign( builder ) !== true ) {
  23019. continue;
  23020. }
  23021. }
  23022. if ( buildStage === 'setup' ) {
  23023. node.build( builder );
  23024. } else if ( buildStage === 'analyze' ) {
  23025. node.build( builder, this );
  23026. } else if ( buildStage === 'generate' ) {
  23027. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23028. const parents = stages && stages[ builder.shaderStage ];
  23029. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23030. continue; // skip var nodes that are only used in .toVarying()
  23031. }
  23032. node.build( builder, 'void' );
  23033. }
  23034. }
  23035. //
  23036. let result;
  23037. if ( this.hasOutput ) {
  23038. result = this.outputNode.build( builder, ...params );
  23039. } else {
  23040. result = super.build( builder, ...params );
  23041. }
  23042. setCurrentStack( previousStack );
  23043. builder.currentStack = previousBuildStack;
  23044. return result;
  23045. }
  23046. }
  23047. /**
  23048. * TSL function for creating a stack node.
  23049. *
  23050. * @tsl
  23051. * @function
  23052. * @param {?StackNode} [parent=null] - The parent stack node.
  23053. * @returns {StackNode}
  23054. */
  23055. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23056. /**
  23057. * Generates a layout for struct members.
  23058. * This function takes an object representing struct members and returns an array of member layouts.
  23059. * Each member layout includes the member's name, type, and whether it is atomic.
  23060. *
  23061. * @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.
  23062. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23063. */
  23064. function getMembersLayout( members ) {
  23065. return Object.entries( members ).map( ( [ name, value ] ) => {
  23066. if ( typeof value === 'string' ) {
  23067. return { name, type: value, atomic: false };
  23068. }
  23069. return { name, type: value.type, atomic: value.atomic || false };
  23070. } );
  23071. }
  23072. /**
  23073. * Represents a struct type node in the node-based system.
  23074. * This class is used to define and manage the layout and types of struct members.
  23075. * It extends the base Node class and provides methods to get the length of the struct,
  23076. * retrieve member types, and generate the struct type for a builder.
  23077. *
  23078. * @augments Node
  23079. */
  23080. class StructTypeNode extends Node {
  23081. static get type() {
  23082. return 'StructTypeNode';
  23083. }
  23084. /**
  23085. * Creates an instance of StructTypeNode.
  23086. *
  23087. * @param {Object} membersLayout - The layout of the members for the struct.
  23088. * @param {?string} [name=null] - The optional name of the struct.
  23089. */
  23090. constructor( membersLayout, name = null ) {
  23091. super( 'struct' );
  23092. /**
  23093. * The layout of the members for the struct
  23094. *
  23095. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23096. */
  23097. this.membersLayout = getMembersLayout( membersLayout );
  23098. /**
  23099. * The name of the struct.
  23100. *
  23101. * @type {?string}
  23102. * @default null
  23103. */
  23104. this.name = name;
  23105. /**
  23106. * This flag can be used for type testing.
  23107. *
  23108. * @type {boolean}
  23109. * @readonly
  23110. * @default true
  23111. */
  23112. this.isStructLayoutNode = true;
  23113. }
  23114. /**
  23115. * Returns the length of the struct.
  23116. * The length is calculated by summing the lengths of the struct's members.
  23117. *
  23118. * @returns {number} The length of the struct.
  23119. */
  23120. getLength() {
  23121. const GPU_CHUNK_BYTES = 8;
  23122. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23123. let offset = 0; // global buffer offset in bytes
  23124. for ( const member of this.membersLayout ) {
  23125. const type = member.type;
  23126. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23127. const boundary = getByteBoundaryFromType( type );
  23128. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23129. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23130. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23131. offset += chunkPadding;
  23132. // Check for chunk overflow
  23133. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23134. // Add padding to the end of the chunk
  23135. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23136. }
  23137. offset += itemSize;
  23138. }
  23139. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23140. }
  23141. getMemberType( builder, name ) {
  23142. const member = this.membersLayout.find( m => m.name === name );
  23143. return member ? member.type : 'void';
  23144. }
  23145. getNodeType( builder ) {
  23146. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23147. return structType.name;
  23148. }
  23149. setup( builder ) {
  23150. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23151. builder.addInclude( this );
  23152. }
  23153. generate( builder ) {
  23154. return this.getNodeType( builder );
  23155. }
  23156. }
  23157. /**
  23158. * StructNode allows to create custom structures with multiple members.
  23159. * This can also be used to define structures in attribute and uniform data.
  23160. *
  23161. * ```js
  23162. * // Define a custom struct
  23163. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23164. *
  23165. * // Create a new instance of the struct
  23166. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23167. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23168. *
  23169. * // Access the struct members
  23170. * const min = bb.get( 'min' );
  23171. *
  23172. * // Assign a new value to a member
  23173. * min.assign( vec3() );
  23174. * ```
  23175. * @augments Node
  23176. */
  23177. class StructNode extends Node {
  23178. static get type() {
  23179. return 'StructNode';
  23180. }
  23181. constructor( structTypeNode, values ) {
  23182. super( 'vec3' );
  23183. this.structTypeNode = structTypeNode;
  23184. this.values = values;
  23185. this.isStructNode = true;
  23186. }
  23187. getNodeType( builder ) {
  23188. return this.structTypeNode.getNodeType( builder );
  23189. }
  23190. getMemberType( builder, name ) {
  23191. return this.structTypeNode.getMemberType( builder, name );
  23192. }
  23193. generate( builder ) {
  23194. const nodeVar = builder.getVarFromNode( this );
  23195. const structType = nodeVar.type;
  23196. const propertyName = builder.getPropertyName( nodeVar );
  23197. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23198. return nodeVar.name;
  23199. }
  23200. }
  23201. /**
  23202. * TSL function for creating a struct node.
  23203. *
  23204. * @tsl
  23205. * @function
  23206. * @param {Object} membersLayout - The layout of the struct members.
  23207. * @param {?string} [name=null] - The name of the struct.
  23208. * @returns {Function} The struct function.
  23209. */
  23210. const struct = ( membersLayout, name = null ) => {
  23211. const structLayout = new StructTypeNode( membersLayout, name );
  23212. const struct = ( ...params ) => {
  23213. let values = null;
  23214. if ( params.length > 0 ) {
  23215. if ( params[ 0 ].isNode ) {
  23216. values = {};
  23217. const names = Object.keys( membersLayout );
  23218. for ( let i = 0; i < params.length; i ++ ) {
  23219. values[ names[ i ] ] = params[ i ];
  23220. }
  23221. } else {
  23222. values = params[ 0 ];
  23223. }
  23224. }
  23225. return nodeObject( new StructNode( structLayout, values ) );
  23226. };
  23227. struct.layout = structLayout;
  23228. struct.isStruct = true;
  23229. return struct;
  23230. };
  23231. /**
  23232. * This node can be used to define multiple outputs in a shader programs.
  23233. *
  23234. * @augments Node
  23235. */
  23236. class OutputStructNode extends Node {
  23237. static get type() {
  23238. return 'OutputStructNode';
  23239. }
  23240. /**
  23241. * Constructs a new output struct node. The constructor can be invoked with an
  23242. * arbitrary number of nodes representing the members.
  23243. *
  23244. * @param {...Node} members - A parameter list of nodes.
  23245. */
  23246. constructor( ...members ) {
  23247. super();
  23248. /**
  23249. * An array of nodes which defines the output.
  23250. *
  23251. * @type {Array<Node>}
  23252. */
  23253. this.members = members;
  23254. /**
  23255. * This flag can be used for type testing.
  23256. *
  23257. * @type {boolean}
  23258. * @readonly
  23259. * @default true
  23260. */
  23261. this.isOutputStructNode = true;
  23262. }
  23263. getNodeType( builder ) {
  23264. const properties = builder.getNodeProperties( this );
  23265. if ( properties.membersLayout === undefined ) {
  23266. const members = this.members;
  23267. const membersLayout = [];
  23268. for ( let i = 0; i < members.length; i ++ ) {
  23269. const name = 'm' + i;
  23270. const type = members[ i ].getNodeType( builder );
  23271. membersLayout.push( { name, type, index: i } );
  23272. }
  23273. properties.membersLayout = membersLayout;
  23274. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23275. }
  23276. return properties.structType.name;
  23277. }
  23278. generate( builder ) {
  23279. const propertyName = builder.getOutputStructName();
  23280. const members = this.members;
  23281. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23282. for ( let i = 0; i < members.length; i ++ ) {
  23283. const snippet = members[ i ].build( builder );
  23284. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23285. }
  23286. return propertyName;
  23287. }
  23288. }
  23289. /**
  23290. * TSL function for creating an output struct node.
  23291. *
  23292. * @tsl
  23293. * @function
  23294. * @param {...Node} members - A parameter list of nodes.
  23295. * @returns {OutputStructNode}
  23296. */
  23297. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23298. /**
  23299. * Returns the MRT texture index for the given name.
  23300. *
  23301. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23302. * @param {string} name - The name of the MRT texture which index is requested.
  23303. * @return {number} The texture index.
  23304. */
  23305. function getTextureIndex( textures, name ) {
  23306. for ( let i = 0; i < textures.length; i ++ ) {
  23307. if ( textures[ i ].name === name ) {
  23308. return i;
  23309. }
  23310. }
  23311. return -1;
  23312. }
  23313. /**
  23314. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23315. * post-processing is shown below:
  23316. * ```js
  23317. * const mrtNode = mrt( {
  23318. * output: output,
  23319. * normal: normalView
  23320. * } ) );
  23321. * ```
  23322. * The MRT output is defined as a dictionary.
  23323. *
  23324. * @augments OutputStructNode
  23325. */
  23326. class MRTNode extends OutputStructNode {
  23327. static get type() {
  23328. return 'MRTNode';
  23329. }
  23330. /**
  23331. * Constructs a new output struct node.
  23332. *
  23333. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23334. */
  23335. constructor( outputNodes ) {
  23336. super();
  23337. /**
  23338. * A dictionary representing the MRT outputs. The key
  23339. * is the name of the output, the value the node which produces
  23340. * the output result.
  23341. *
  23342. * @type {Object<string, Node>}
  23343. */
  23344. this.outputNodes = outputNodes;
  23345. /**
  23346. * This flag can be used for type testing.
  23347. *
  23348. * @type {boolean}
  23349. * @readonly
  23350. * @default true
  23351. */
  23352. this.isMRTNode = true;
  23353. }
  23354. /**
  23355. * Returns `true` if the MRT node has an output with the given name.
  23356. *
  23357. * @param {string} name - The name of the output.
  23358. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23359. */
  23360. has( name ) {
  23361. return this.outputNodes[ name ] !== undefined;
  23362. }
  23363. /**
  23364. * Returns the output node for the given name.
  23365. *
  23366. * @param {string} name - The name of the output.
  23367. * @return {Node} The output node.
  23368. */
  23369. get( name ) {
  23370. return this.outputNodes[ name ];
  23371. }
  23372. /**
  23373. * Merges the outputs of the given MRT node with the outputs of this node.
  23374. *
  23375. * @param {MRTNode} mrtNode - The MRT to merge.
  23376. * @return {MRTNode} A new MRT node with merged outputs..
  23377. */
  23378. merge( mrtNode ) {
  23379. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23380. return mrt( outputs );
  23381. }
  23382. setup( builder ) {
  23383. const outputNodes = this.outputNodes;
  23384. const mrt = builder.renderer.getRenderTarget();
  23385. const members = [];
  23386. const textures = mrt.textures;
  23387. for ( const name in outputNodes ) {
  23388. const index = getTextureIndex( textures, name );
  23389. members[ index ] = vec4( outputNodes[ name ] );
  23390. }
  23391. this.members = members;
  23392. return super.setup( builder );
  23393. }
  23394. }
  23395. /**
  23396. * TSL function for creating a MRT node.
  23397. *
  23398. * @tsl
  23399. * @function
  23400. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23401. * @returns {MRTNode}
  23402. */
  23403. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23404. /**
  23405. * This node represents an operation that reinterprets the bit representation of a value
  23406. * in one type as a value in another type.
  23407. *
  23408. * @augments TempNode
  23409. */
  23410. class BitcastNode extends TempNode {
  23411. static get type() {
  23412. return 'BitcastNode';
  23413. }
  23414. /**
  23415. * Constructs a new bitcast node.
  23416. *
  23417. * @param {Node} valueNode - The value to convert.
  23418. * @param {string} conversionType - The type to convert to.
  23419. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23420. */
  23421. constructor( valueNode, conversionType, inputType = null ) {
  23422. super();
  23423. /**
  23424. * The data to bitcast to a new type.
  23425. *
  23426. * @type {Node}
  23427. */
  23428. this.valueNode = valueNode;
  23429. /**
  23430. * The type the value will be converted to.
  23431. *
  23432. * @type {string}
  23433. */
  23434. this.conversionType = conversionType;
  23435. /**
  23436. * The expected input data type of the bitcast operation.
  23437. *
  23438. *
  23439. * @type {string}
  23440. * @default null
  23441. */
  23442. this.inputType = inputType;
  23443. /**
  23444. * This flag can be used for type testing.
  23445. *
  23446. * @type {boolean}
  23447. * @readonly
  23448. * @default true
  23449. */
  23450. this.isBitcastNode = true;
  23451. }
  23452. getNodeType( builder ) {
  23453. // GLSL aliasing
  23454. if ( this.inputType !== null ) {
  23455. const valueType = this.valueNode.getNodeType( builder );
  23456. const valueLength = builder.getTypeLength( valueType );
  23457. return builder.getTypeFromLength( valueLength, this.conversionType );
  23458. }
  23459. return this.conversionType;
  23460. }
  23461. generate( builder ) {
  23462. const type = this.getNodeType( builder );
  23463. let inputType = '';
  23464. if ( this.inputType !== null ) {
  23465. const valueType = this.valueNode.getNodeType( builder );
  23466. const valueTypeLength = builder.getTypeLength( valueType );
  23467. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23468. } else {
  23469. inputType = this.valueNode.getNodeType( builder );
  23470. }
  23471. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23472. }
  23473. }
  23474. /**
  23475. * Reinterpret the bit representation of a value in one type as a value in another type.
  23476. *
  23477. * @tsl
  23478. * @function
  23479. * @param {Node | number} x - The parameter.
  23480. * @param {string} y - The new type.
  23481. * @returns {Node}
  23482. */
  23483. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23484. /**
  23485. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23486. *
  23487. * @tsl
  23488. * @function
  23489. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23490. * @returns {BitcastNode}
  23491. */
  23492. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23493. /**
  23494. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23495. *
  23496. * @tsl
  23497. * @function
  23498. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23499. * @returns {BitcastNode}
  23500. */
  23501. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23502. /**
  23503. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23504. *
  23505. * @tsl
  23506. * @function
  23507. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23508. * @returns {BitcastNode}
  23509. */
  23510. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23511. /**
  23512. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23513. *
  23514. * @tsl
  23515. * @function
  23516. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23517. * @returns {BitcastNode}
  23518. */
  23519. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23520. /**
  23521. * Generates a hash value in the range `[0, 1]` from the given seed.
  23522. *
  23523. * @tsl
  23524. * @function
  23525. * @param {Node<float>} seed - The seed.
  23526. * @return {Node<float>} The hash value.
  23527. */
  23528. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23529. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23530. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23531. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23532. const result = word.shiftRight( 22 ).bitXor( word );
  23533. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23534. } );
  23535. /**
  23536. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23537. * The corners are mapped to `0` and the center to `1`.
  23538. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23539. *
  23540. * @tsl
  23541. * @function
  23542. * @param {Node<float>} x - The value to remap.
  23543. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23544. * @return {Node<float>} The remapped value.
  23545. */
  23546. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23547. /**
  23548. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23549. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23550. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23551. *
  23552. * @tsl
  23553. * @function
  23554. * @param {Node<float>} x - The value to remap.
  23555. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23556. * @return {Node<float>} The remapped value.
  23557. */
  23558. 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 ) );
  23559. /**
  23560. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23561. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23562. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23563. *
  23564. * @tsl
  23565. * @function
  23566. * @param {Node<float>} x - The value to remap.
  23567. * @param {Node<float>} a - First control parameter.
  23568. * @param {Node<float>} b - Second control parameter.
  23569. * @return {Node<float>} The remapped value.
  23570. */
  23571. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23572. /**
  23573. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23574. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23575. *
  23576. * @tsl
  23577. * @function
  23578. * @param {Node<float>} x - The value to compute the sin for.
  23579. * @param {Node<float>} k - Controls the amount of bounces.
  23580. * @return {Node<float>} The result value.
  23581. */
  23582. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23583. // https://github.com/cabbibo/glsl-tri-noise-3d
  23584. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23585. return x.fract().sub( .5 ).abs();
  23586. } ).setLayout( {
  23587. name: 'tri',
  23588. type: 'float',
  23589. inputs: [
  23590. { name: 'x', type: 'float' }
  23591. ]
  23592. } );
  23593. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23594. 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. ) ) ) ) );
  23595. } ).setLayout( {
  23596. name: 'tri3',
  23597. type: 'vec3',
  23598. inputs: [
  23599. { name: 'p', type: 'vec3' }
  23600. ]
  23601. } );
  23602. /**
  23603. * Generates a noise value from the given position, speed and time parameters.
  23604. *
  23605. * @tsl
  23606. * @function
  23607. * @param {Node<vec3>} position - The position.
  23608. * @param {Node<float>} speed - The speed.
  23609. * @param {Node<float>} time - The time.
  23610. * @return {Node<float>} The generated noise.
  23611. */
  23612. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23613. const p = vec3( position ).toVar();
  23614. const z = float( 1.4 ).toVar();
  23615. const rz = float( 0.0 ).toVar();
  23616. const bp = vec3( p ).toVar();
  23617. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23618. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23619. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23620. bp.mulAssign( 1.8 );
  23621. z.mulAssign( 1.5 );
  23622. p.mulAssign( 1.2 );
  23623. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23624. rz.addAssign( t.div( z ) );
  23625. bp.addAssign( 0.14 );
  23626. } );
  23627. return rz;
  23628. } ).setLayout( {
  23629. name: 'triNoise3D',
  23630. type: 'float',
  23631. inputs: [
  23632. { name: 'position', type: 'vec3' },
  23633. { name: 'speed', type: 'float' },
  23634. { name: 'time', type: 'float' }
  23635. ]
  23636. } );
  23637. /**
  23638. * This class allows to define multiple overloaded versions
  23639. * of the same function. Depending on the parameters of the function
  23640. * call, the node picks the best-fit overloaded version.
  23641. *
  23642. * @augments Node
  23643. */
  23644. class FunctionOverloadingNode extends Node {
  23645. static get type() {
  23646. return 'FunctionOverloadingNode';
  23647. }
  23648. /**
  23649. * Constructs a new function overloading node.
  23650. *
  23651. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23652. * @param {...Node} parametersNodes - A list of parameter nodes.
  23653. */
  23654. constructor( functionNodes = [], ...parametersNodes ) {
  23655. super();
  23656. /**
  23657. * Array of `Fn` function definitions.
  23658. *
  23659. * @type {Array<Function>}
  23660. */
  23661. this.functionNodes = functionNodes;
  23662. /**
  23663. * A list of parameter nodes.
  23664. *
  23665. * @type {Array<Node>}
  23666. */
  23667. this.parametersNodes = parametersNodes;
  23668. /**
  23669. * The selected overloaded function call.
  23670. *
  23671. * @private
  23672. * @type {ShaderCallNodeInternal}
  23673. */
  23674. this._candidateFnCall = null;
  23675. /**
  23676. * This node is marked as global.
  23677. *
  23678. * @type {boolean}
  23679. * @default true
  23680. */
  23681. this.global = true;
  23682. }
  23683. /**
  23684. * This method is overwritten since the node type is inferred from
  23685. * the function's return type.
  23686. *
  23687. * @param {NodeBuilder} builder - The current node builder.
  23688. * @return {string} The node type.
  23689. */
  23690. getNodeType() {
  23691. return this.functionNodes[ 0 ].shaderNode.layout.type;
  23692. }
  23693. setup( builder ) {
  23694. const params = this.parametersNodes;
  23695. let candidateFnCall = this._candidateFnCall;
  23696. if ( candidateFnCall === null ) {
  23697. let candidateFn = null;
  23698. let candidateScore = -1;
  23699. for ( const functionNode of this.functionNodes ) {
  23700. const shaderNode = functionNode.shaderNode;
  23701. const layout = shaderNode.layout;
  23702. if ( layout === null ) {
  23703. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23704. }
  23705. const inputs = layout.inputs;
  23706. if ( params.length === inputs.length ) {
  23707. let score = 0;
  23708. for ( let i = 0; i < params.length; i ++ ) {
  23709. const param = params[ i ];
  23710. const input = inputs[ i ];
  23711. if ( param.getNodeType( builder ) === input.type ) {
  23712. score ++;
  23713. } else {
  23714. score = 0;
  23715. }
  23716. }
  23717. if ( score > candidateScore ) {
  23718. candidateFn = functionNode;
  23719. candidateScore = score;
  23720. }
  23721. }
  23722. }
  23723. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  23724. }
  23725. return candidateFnCall;
  23726. }
  23727. }
  23728. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23729. /**
  23730. * TSL function for creating a function overloading node.
  23731. *
  23732. * @tsl
  23733. * @function
  23734. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23735. * @returns {FunctionOverloadingNode}
  23736. */
  23737. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23738. /**
  23739. * Represents the elapsed time in seconds.
  23740. *
  23741. * @tsl
  23742. * @type {UniformNode<float>}
  23743. */
  23744. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23745. /**
  23746. * Represents the delta time in seconds.
  23747. *
  23748. * @tsl
  23749. * @type {UniformNode<float>}
  23750. */
  23751. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23752. /**
  23753. * Represents the current frame ID.
  23754. *
  23755. * @tsl
  23756. * @type {UniformNode<uint>}
  23757. */
  23758. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23759. /**
  23760. * Generates a sine wave oscillation based on a timer.
  23761. *
  23762. * @tsl
  23763. * @function
  23764. * @param {Node<float>} t - The timer to generate the oscillation with.
  23765. * @return {Node<float>} The oscillation node.
  23766. */
  23767. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23768. /**
  23769. * Generates a square wave oscillation based on a timer.
  23770. *
  23771. * @tsl
  23772. * @function
  23773. * @param {Node<float>} t - The timer to generate the oscillation with.
  23774. * @return {Node<float>} The oscillation node.
  23775. */
  23776. const oscSquare = ( t = time ) => t.fract().round();
  23777. /**
  23778. * Generates a triangle wave oscillation based on a timer.
  23779. *
  23780. * @tsl
  23781. * @function
  23782. * @param {Node<float>} t - The timer to generate the oscillation with.
  23783. * @return {Node<float>} The oscillation node.
  23784. */
  23785. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23786. /**
  23787. * Generates a sawtooth wave oscillation based on a timer.
  23788. *
  23789. * @tsl
  23790. * @function
  23791. * @param {Node<float>} t - The timer to generate the oscillation with.
  23792. * @return {Node<float>} The oscillation node.
  23793. */
  23794. const oscSawtooth = ( t = time ) => t.fract();
  23795. /**
  23796. * Rotates the given uv coordinates around a center point
  23797. *
  23798. * @tsl
  23799. * @function
  23800. * @param {Node<vec2>} uv - The uv coordinates.
  23801. * @param {Node<float>} rotation - The rotation defined in radians.
  23802. * @param {Node<vec2>} center - The center of rotation
  23803. * @return {Node<vec2>} The rotated uv coordinates.
  23804. */
  23805. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23806. return rotate( uv.sub( center ), rotation ).add( center );
  23807. } );
  23808. /**
  23809. * Applies a spherical warping effect to the given uv coordinates.
  23810. *
  23811. * @tsl
  23812. * @function
  23813. * @param {Node<vec2>} uv - The uv coordinates.
  23814. * @param {Node<float>} strength - The strength of the effect.
  23815. * @param {Node<vec2>} center - The center point
  23816. * @return {Node<vec2>} The updated uv coordinates.
  23817. */
  23818. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23819. const delta = uv.sub( center );
  23820. const delta2 = delta.dot( delta );
  23821. const delta4 = delta2.mul( delta2 );
  23822. const deltaOffset = delta4.mul( strength );
  23823. return uv.add( delta.mul( deltaOffset ) );
  23824. } );
  23825. /**
  23826. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23827. * oriented always towards the camera.
  23828. *
  23829. * ```js
  23830. * material.vertexNode = billboarding();
  23831. * ```
  23832. *
  23833. * @tsl
  23834. * @function
  23835. * @param {Object} config - The configuration object.
  23836. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23837. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23838. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23839. * @return {Node<vec3>} The updated vertex position in clip space.
  23840. */
  23841. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23842. let worldMatrix;
  23843. if ( position !== null ) {
  23844. worldMatrix = modelWorldMatrix.toVar();
  23845. worldMatrix[ 3 ][ 0 ] = position.x;
  23846. worldMatrix[ 3 ][ 1 ] = position.y;
  23847. worldMatrix[ 3 ][ 2 ] = position.z;
  23848. } else {
  23849. worldMatrix = modelWorldMatrix;
  23850. }
  23851. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23852. if ( defined( horizontal ) ) {
  23853. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23854. modelViewMatrix[ 0 ][ 1 ] = 0;
  23855. modelViewMatrix[ 0 ][ 2 ] = 0;
  23856. }
  23857. if ( defined( vertical ) ) {
  23858. modelViewMatrix[ 1 ][ 0 ] = 0;
  23859. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23860. modelViewMatrix[ 1 ][ 2 ] = 0;
  23861. }
  23862. modelViewMatrix[ 2 ][ 0 ] = 0;
  23863. modelViewMatrix[ 2 ][ 1 ] = 0;
  23864. modelViewMatrix[ 2 ][ 2 ] = 1;
  23865. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23866. } );
  23867. /**
  23868. * A special version of a screen uv function that involves a depth comparison
  23869. * when computing the final uvs. The function mitigates visual errors when
  23870. * using viewport texture nodes for refraction purposes. Without this function
  23871. * objects in front of a refractive surface might appear on the refractive surface
  23872. * which is incorrect.
  23873. *
  23874. * @tsl
  23875. * @function
  23876. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23877. * @return {Node<vec2>} The update uv coordinates.
  23878. */
  23879. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23880. const depth = linearDepth();
  23881. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23882. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23883. return finalUV;
  23884. } );
  23885. /**
  23886. * Can be used to compute texture coordinates for animated sprite sheets.
  23887. *
  23888. * ```js
  23889. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23890. *
  23891. * material.colorNode = texture( spriteSheet, uvNode );
  23892. * ```
  23893. *
  23894. * @augments Node
  23895. */
  23896. class SpriteSheetUVNode extends Node {
  23897. static get type() {
  23898. return 'SpriteSheetUVNode';
  23899. }
  23900. /**
  23901. * Constructs a new sprite sheet uv node.
  23902. *
  23903. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23904. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23905. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23906. */
  23907. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23908. super( 'vec2' );
  23909. /**
  23910. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23911. *
  23912. * @type {Node<vec2>}
  23913. */
  23914. this.countNode = countNode;
  23915. /**
  23916. * The uv node.
  23917. *
  23918. * @type {Node<vec2>}
  23919. */
  23920. this.uvNode = uvNode;
  23921. /**
  23922. * The node that defines the current frame/sprite.
  23923. *
  23924. * @type {Node<float>}
  23925. */
  23926. this.frameNode = frameNode;
  23927. }
  23928. setup() {
  23929. const { frameNode, uvNode, countNode } = this;
  23930. const { width, height } = countNode;
  23931. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23932. const column = frameNum.mod( width );
  23933. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23934. const scale = countNode.reciprocal();
  23935. const uvFrameOffset = vec2( column, row );
  23936. return uvNode.add( uvFrameOffset ).mul( scale );
  23937. }
  23938. }
  23939. /**
  23940. * TSL function for creating a sprite sheet uv node.
  23941. *
  23942. * @tsl
  23943. * @function
  23944. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23945. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23946. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23947. * @returns {SpriteSheetUVNode}
  23948. */
  23949. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23950. /**
  23951. * TSL function for creating a triplanar textures node.
  23952. *
  23953. * Can be used for triplanar texture mapping.
  23954. *
  23955. * ```js
  23956. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23957. * ```
  23958. *
  23959. * @tsl
  23960. * @function
  23961. * @param {Node} textureXNode - First texture node.
  23962. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23963. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23964. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23965. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23966. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23967. * @returns {Node<vec4>}
  23968. */
  23969. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23970. // Reference: https://github.com/keijiro/StandardTriplanar
  23971. // Blending factor of triplanar mapping
  23972. let bf = normalNode.abs().normalize();
  23973. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23974. // Triplanar mapping
  23975. const tx = positionNode.yz.mul( scaleNode );
  23976. const ty = positionNode.zx.mul( scaleNode );
  23977. const tz = positionNode.xy.mul( scaleNode );
  23978. // Base color
  23979. const textureX = textureXNode.value;
  23980. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23981. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23982. const cx = texture( textureX, tx ).mul( bf.x );
  23983. const cy = texture( textureY, ty ).mul( bf.y );
  23984. const cz = texture( textureZ, tz ).mul( bf.z );
  23985. return add( cx, cy, cz );
  23986. } );
  23987. /**
  23988. * TSL function for creating a triplanar textures node.
  23989. *
  23990. * @tsl
  23991. * @function
  23992. * @param {Node} textureXNode - First texture node.
  23993. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23994. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23995. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23996. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23997. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23998. * @returns {Node<vec4>}
  23999. */
  24000. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  24001. const _reflectorPlane = new Plane();
  24002. const _normal = new Vector3();
  24003. const _reflectorWorldPosition = new Vector3();
  24004. const _cameraWorldPosition = new Vector3();
  24005. const _rotationMatrix = new Matrix4();
  24006. const _lookAtPosition = new Vector3( 0, 0, -1 );
  24007. const clipPlane = new Vector4();
  24008. const _view = new Vector3();
  24009. const _target = new Vector3();
  24010. const _q = new Vector4();
  24011. const _size$2 = new Vector2();
  24012. const _defaultRT = new RenderTarget();
  24013. const _defaultUV = screenUV.flipX();
  24014. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  24015. let _inReflector = false;
  24016. /**
  24017. * This node can be used to implement mirror-like flat reflective surfaces.
  24018. *
  24019. * ```js
  24020. * const groundReflector = reflector();
  24021. * material.colorNode = groundReflector;
  24022. *
  24023. * const plane = new Mesh( geometry, material );
  24024. * plane.add( groundReflector.target );
  24025. * ```
  24026. *
  24027. * @augments TextureNode
  24028. */
  24029. class ReflectorNode extends TextureNode {
  24030. static get type() {
  24031. return 'ReflectorNode';
  24032. }
  24033. /**
  24034. * Constructs a new reflector node.
  24035. *
  24036. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24037. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24038. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24039. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24040. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24041. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24042. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24043. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24044. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24045. */
  24046. constructor( parameters = {} ) {
  24047. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  24048. /**
  24049. * A reference to the internal reflector base node which holds the actual implementation.
  24050. *
  24051. * @private
  24052. * @type {ReflectorBaseNode}
  24053. * @default ReflectorBaseNode
  24054. */
  24055. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  24056. /**
  24057. * A reference to the internal depth node.
  24058. *
  24059. * @private
  24060. * @type {?Node}
  24061. * @default null
  24062. */
  24063. this._depthNode = null;
  24064. this.setUpdateMatrix( false );
  24065. }
  24066. /**
  24067. * A reference to the internal reflector node.
  24068. *
  24069. * @type {ReflectorBaseNode}
  24070. */
  24071. get reflector() {
  24072. return this._reflectorBaseNode;
  24073. }
  24074. /**
  24075. * A reference to 3D object the reflector is linked to.
  24076. *
  24077. * @type {Object3D}
  24078. */
  24079. get target() {
  24080. return this._reflectorBaseNode.target;
  24081. }
  24082. /**
  24083. * Returns a node representing the mirror's depth. That can be used
  24084. * to implement more advanced reflection effects like distance attenuation.
  24085. *
  24086. * @return {Node} The depth node.
  24087. */
  24088. getDepthNode() {
  24089. if ( this._depthNode === null ) {
  24090. if ( this._reflectorBaseNode.depth !== true ) {
  24091. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  24092. }
  24093. this._depthNode = nodeObject( new ReflectorNode( {
  24094. defaultTexture: _defaultRT.depthTexture,
  24095. reflector: this._reflectorBaseNode
  24096. } ) );
  24097. }
  24098. return this._depthNode;
  24099. }
  24100. setup( builder ) {
  24101. // ignore if used in post-processing
  24102. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  24103. return super.setup( builder );
  24104. }
  24105. clone() {
  24106. const newNode = new this.constructor( this.reflectorNode );
  24107. newNode.uvNode = this.uvNode;
  24108. newNode.levelNode = this.levelNode;
  24109. newNode.biasNode = this.biasNode;
  24110. newNode.sampler = this.sampler;
  24111. newNode.depthNode = this.depthNode;
  24112. newNode.compareNode = this.compareNode;
  24113. newNode.gradNode = this.gradNode;
  24114. newNode.offsetNode = this.offsetNode;
  24115. newNode._reflectorBaseNode = this._reflectorBaseNode;
  24116. return newNode;
  24117. }
  24118. /**
  24119. * Frees internal resources. Should be called when the node is no longer in use.
  24120. */
  24121. dispose() {
  24122. super.dispose();
  24123. this._reflectorBaseNode.dispose();
  24124. }
  24125. }
  24126. /**
  24127. * Holds the actual implementation of the reflector.
  24128. *
  24129. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  24130. * in `ReflectorNode`, see #29619.
  24131. *
  24132. * @private
  24133. * @augments Node
  24134. */
  24135. class ReflectorBaseNode extends Node {
  24136. static get type() {
  24137. return 'ReflectorBaseNode';
  24138. }
  24139. /**
  24140. * Constructs a new reflector base node.
  24141. *
  24142. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  24143. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24144. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24145. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24146. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24147. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24148. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24149. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24150. */
  24151. constructor( textureNode, parameters = {} ) {
  24152. super();
  24153. const {
  24154. target = new Object3D(),
  24155. resolutionScale = 1,
  24156. generateMipmaps = false,
  24157. bounces = true,
  24158. depth = false,
  24159. samples = 0
  24160. } = parameters;
  24161. /**
  24162. * Represents the rendered reflections as a texture node.
  24163. *
  24164. * @type {TextureNode}
  24165. */
  24166. this.textureNode = textureNode;
  24167. /**
  24168. * The 3D object the reflector is linked to.
  24169. *
  24170. * @type {Object3D}
  24171. * @default {new Object3D()}
  24172. */
  24173. this.target = target;
  24174. /**
  24175. * The resolution scale.
  24176. *
  24177. * @type {number}
  24178. * @default {1}
  24179. */
  24180. this.resolutionScale = resolutionScale;
  24181. if ( parameters.resolution !== undefined ) {
  24182. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  24183. this.resolutionScale = parameters.resolution;
  24184. }
  24185. /**
  24186. * Whether mipmaps should be generated or not.
  24187. *
  24188. * @type {boolean}
  24189. * @default {false}
  24190. */
  24191. this.generateMipmaps = generateMipmaps;
  24192. /**
  24193. * Whether reflectors can render other reflector nodes or not.
  24194. *
  24195. * @type {boolean}
  24196. * @default {true}
  24197. */
  24198. this.bounces = bounces;
  24199. /**
  24200. * Whether depth data should be generated or not.
  24201. *
  24202. * @type {boolean}
  24203. * @default {false}
  24204. */
  24205. this.depth = depth;
  24206. /**
  24207. * The number of anti-aliasing samples for the render-target
  24208. *
  24209. * @type {number}
  24210. * @default {0}
  24211. */
  24212. this.samples = samples;
  24213. /**
  24214. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  24215. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  24216. *
  24217. * @type {string}
  24218. * @default 'render'
  24219. */
  24220. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  24221. /**
  24222. * Weak map for managing virtual cameras.
  24223. *
  24224. * @type {WeakMap<Camera, Camera>}
  24225. */
  24226. this.virtualCameras = new WeakMap();
  24227. /**
  24228. * Weak map for managing render targets.
  24229. *
  24230. * @type {Map<Camera, RenderTarget>}
  24231. */
  24232. this.renderTargets = new Map();
  24233. /**
  24234. * Force render even if reflector is facing away from camera.
  24235. *
  24236. * @type {boolean}
  24237. * @default {false}
  24238. */
  24239. this.forceUpdate = false;
  24240. /**
  24241. * Whether the reflector has been rendered or not.
  24242. *
  24243. * When the reflector is facing away from the camera,
  24244. * this flag is set to `false` and the texture will be empty(black).
  24245. *
  24246. * @type {boolean}
  24247. * @default {false}
  24248. */
  24249. this.hasOutput = false;
  24250. }
  24251. /**
  24252. * Updates the resolution of the internal render target.
  24253. *
  24254. * @private
  24255. * @param {RenderTarget} renderTarget - The render target to resize.
  24256. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  24257. */
  24258. _updateResolution( renderTarget, renderer ) {
  24259. const resolution = this.resolutionScale;
  24260. renderer.getDrawingBufferSize( _size$2 );
  24261. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  24262. }
  24263. setup( builder ) {
  24264. this._updateResolution( _defaultRT, builder.renderer );
  24265. return super.setup( builder );
  24266. }
  24267. /**
  24268. * Frees internal resources. Should be called when the node is no longer in use.
  24269. */
  24270. dispose() {
  24271. super.dispose();
  24272. for ( const renderTarget of this.renderTargets.values() ) {
  24273. renderTarget.dispose();
  24274. }
  24275. }
  24276. /**
  24277. * Returns a virtual camera for the given camera. The virtual camera is used to
  24278. * render the scene from the reflector's view so correct reflections can be produced.
  24279. *
  24280. * @param {Camera} camera - The scene's camera.
  24281. * @return {Camera} The corresponding virtual camera.
  24282. */
  24283. getVirtualCamera( camera ) {
  24284. let virtualCamera = this.virtualCameras.get( camera );
  24285. if ( virtualCamera === undefined ) {
  24286. virtualCamera = camera.clone();
  24287. this.virtualCameras.set( camera, virtualCamera );
  24288. }
  24289. return virtualCamera;
  24290. }
  24291. /**
  24292. * Returns a render target for the given camera. The reflections are rendered
  24293. * into this render target.
  24294. *
  24295. * @param {Camera} camera - The scene's camera.
  24296. * @return {RenderTarget} The render target.
  24297. */
  24298. getRenderTarget( camera ) {
  24299. let renderTarget = this.renderTargets.get( camera );
  24300. if ( renderTarget === undefined ) {
  24301. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  24302. if ( this.generateMipmaps === true ) {
  24303. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  24304. renderTarget.texture.generateMipmaps = true;
  24305. }
  24306. if ( this.depth === true ) {
  24307. renderTarget.depthTexture = new DepthTexture();
  24308. }
  24309. this.renderTargets.set( camera, renderTarget );
  24310. }
  24311. return renderTarget;
  24312. }
  24313. updateBefore( frame ) {
  24314. if ( this.bounces === false && _inReflector ) return false;
  24315. _inReflector = true;
  24316. const { scene, camera, renderer, material } = frame;
  24317. const { target } = this;
  24318. const virtualCamera = this.getVirtualCamera( camera );
  24319. const renderTarget = this.getRenderTarget( virtualCamera );
  24320. renderer.getDrawingBufferSize( _size$2 );
  24321. this._updateResolution( renderTarget, renderer );
  24322. //
  24323. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  24324. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  24325. _rotationMatrix.extractRotation( target.matrixWorld );
  24326. _normal.set( 0, 0, 1 );
  24327. _normal.applyMatrix4( _rotationMatrix );
  24328. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  24329. // Avoid rendering when reflector is facing away unless forcing an update
  24330. const isFacingAway = _view.dot( _normal ) > 0;
  24331. let needsClear = false;
  24332. if ( isFacingAway === true && this.forceUpdate === false ) {
  24333. if ( this.hasOutput === false ) {
  24334. _inReflector = false;
  24335. return;
  24336. }
  24337. needsClear = true;
  24338. }
  24339. _view.reflect( _normal ).negate();
  24340. _view.add( _reflectorWorldPosition );
  24341. _rotationMatrix.extractRotation( camera.matrixWorld );
  24342. _lookAtPosition.set( 0, 0, -1 );
  24343. _lookAtPosition.applyMatrix4( _rotationMatrix );
  24344. _lookAtPosition.add( _cameraWorldPosition );
  24345. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  24346. _target.reflect( _normal ).negate();
  24347. _target.add( _reflectorWorldPosition );
  24348. //
  24349. virtualCamera.coordinateSystem = camera.coordinateSystem;
  24350. virtualCamera.position.copy( _view );
  24351. virtualCamera.up.set( 0, 1, 0 );
  24352. virtualCamera.up.applyMatrix4( _rotationMatrix );
  24353. virtualCamera.up.reflect( _normal );
  24354. virtualCamera.lookAt( _target );
  24355. virtualCamera.near = camera.near;
  24356. virtualCamera.far = camera.far;
  24357. virtualCamera.updateMatrixWorld();
  24358. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  24359. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  24360. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  24361. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  24362. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  24363. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  24364. const projectionMatrix = virtualCamera.projectionMatrix;
  24365. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  24366. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  24367. _q.z = -1;
  24368. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  24369. // Calculate the scaled plane vector
  24370. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  24371. const clipBias = 0;
  24372. // Replacing the third row of the projection matrix
  24373. projectionMatrix.elements[ 2 ] = clipPlane.x;
  24374. projectionMatrix.elements[ 6 ] = clipPlane.y;
  24375. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  24376. projectionMatrix.elements[ 14 ] = clipPlane.w;
  24377. //
  24378. this.textureNode.value = renderTarget.texture;
  24379. if ( this.depth === true ) {
  24380. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  24381. }
  24382. material.visible = false;
  24383. const currentRenderTarget = renderer.getRenderTarget();
  24384. const currentMRT = renderer.getMRT();
  24385. const currentAutoClear = renderer.autoClear;
  24386. renderer.setMRT( null );
  24387. renderer.setRenderTarget( renderTarget );
  24388. renderer.autoClear = true;
  24389. const previousName = scene.name;
  24390. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  24391. if ( needsClear ) {
  24392. renderer.clear();
  24393. this.hasOutput = false;
  24394. } else {
  24395. renderer.render( scene, virtualCamera );
  24396. this.hasOutput = true;
  24397. }
  24398. scene.name = previousName;
  24399. renderer.setMRT( currentMRT );
  24400. renderer.setRenderTarget( currentRenderTarget );
  24401. renderer.autoClear = currentAutoClear;
  24402. material.visible = true;
  24403. _inReflector = false;
  24404. this.forceUpdate = false;
  24405. }
  24406. /**
  24407. * The resolution scale.
  24408. *
  24409. * @deprecated
  24410. * @type {number}
  24411. * @default {1}
  24412. */
  24413. get resolution() {
  24414. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24415. return this.resolutionScale;
  24416. }
  24417. set resolution( value ) {
  24418. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24419. this.resolutionScale = value;
  24420. }
  24421. }
  24422. /**
  24423. * TSL function for creating a reflector node.
  24424. *
  24425. * @tsl
  24426. * @function
  24427. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24428. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24429. * @param {number} [parameters.resolution=1] - The resolution scale.
  24430. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24431. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24432. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24433. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24434. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24435. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24436. * @returns {ReflectorNode}
  24437. */
  24438. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24439. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24440. /**
  24441. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24442. *
  24443. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24444. *
  24445. * @private
  24446. * @augments BufferGeometry
  24447. */
  24448. class QuadGeometry extends BufferGeometry {
  24449. /**
  24450. * Constructs a new quad geometry.
  24451. *
  24452. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24453. */
  24454. constructor( flipY = false ) {
  24455. super();
  24456. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24457. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24458. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24459. }
  24460. }
  24461. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24462. /**
  24463. * This module is a helper for passes which need to render a full
  24464. * screen effect which is quite common in context of post processing.
  24465. *
  24466. * The intended usage is to reuse a single quad mesh for rendering
  24467. * subsequent passes by just reassigning the `material` reference.
  24468. *
  24469. * Note: This module can only be used with `WebGPURenderer`.
  24470. *
  24471. * @augments Mesh
  24472. */
  24473. class QuadMesh extends Mesh {
  24474. /**
  24475. * Constructs a new quad mesh.
  24476. *
  24477. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24478. */
  24479. constructor( material = null ) {
  24480. super( _geometry, material );
  24481. /**
  24482. * The camera to render the quad mesh with.
  24483. *
  24484. * @type {OrthographicCamera}
  24485. * @readonly
  24486. */
  24487. this.camera = _camera;
  24488. /**
  24489. * This flag can be used for type testing.
  24490. *
  24491. * @type {boolean}
  24492. * @readonly
  24493. * @default true
  24494. */
  24495. this.isQuadMesh = true;
  24496. }
  24497. /**
  24498. * Async version of `render()`.
  24499. *
  24500. * @async
  24501. * @deprecated
  24502. * @param {Renderer} renderer - The renderer.
  24503. * @return {Promise} A Promise that resolves when the render has been finished.
  24504. */
  24505. async renderAsync( renderer ) {
  24506. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  24507. await renderer.init();
  24508. renderer.render( this, _camera );
  24509. }
  24510. /**
  24511. * Renders the quad mesh
  24512. *
  24513. * @param {Renderer} renderer - The renderer.
  24514. */
  24515. render( renderer ) {
  24516. renderer.render( this, _camera );
  24517. }
  24518. }
  24519. const _size$1 = /*@__PURE__*/ new Vector2();
  24520. /**
  24521. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24522. * This module is especially relevant in context of post processing where certain nodes require
  24523. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24524. * on this module, the node system can automatically ensure texture input if required.
  24525. *
  24526. * @augments TextureNode
  24527. */
  24528. class RTTNode extends TextureNode {
  24529. static get type() {
  24530. return 'RTTNode';
  24531. }
  24532. /**
  24533. * Constructs a new RTT node.
  24534. *
  24535. * @param {Node} node - The node to render a texture with.
  24536. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24537. * @param {?number} [height=null] - The height of the internal render target.
  24538. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24539. */
  24540. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24541. const renderTarget = new RenderTarget( width, height, options );
  24542. super( renderTarget.texture, uv$1() );
  24543. /**
  24544. * This flag can be used for type testing.
  24545. *
  24546. * @type {boolean}
  24547. * @readonly
  24548. * @default true
  24549. */
  24550. this.isRTTNode = true;
  24551. /**
  24552. * The node to render a texture with.
  24553. *
  24554. * @type {Node}
  24555. */
  24556. this.node = node;
  24557. /**
  24558. * The width of the internal render target.
  24559. * If not width is applied, the render target is automatically resized.
  24560. *
  24561. * @type {?number}
  24562. * @default null
  24563. */
  24564. this.width = width;
  24565. /**
  24566. * The height of the internal render target.
  24567. *
  24568. * @type {?number}
  24569. * @default null
  24570. */
  24571. this.height = height;
  24572. /**
  24573. * The pixel ratio
  24574. *
  24575. * @type {number}
  24576. * @default 1
  24577. */
  24578. this.pixelRatio = 1;
  24579. /**
  24580. * The render target
  24581. *
  24582. * @type {RenderTarget}
  24583. */
  24584. this.renderTarget = renderTarget;
  24585. /**
  24586. * Whether the texture requires an update or not.
  24587. *
  24588. * @type {boolean}
  24589. * @default true
  24590. */
  24591. this.textureNeedsUpdate = true;
  24592. /**
  24593. * Whether the texture should automatically be updated or not.
  24594. *
  24595. * @type {boolean}
  24596. * @default true
  24597. */
  24598. this.autoUpdate = true;
  24599. /**
  24600. * The node which is used with the quad mesh for RTT.
  24601. *
  24602. * @private
  24603. * @type {Node}
  24604. * @default null
  24605. */
  24606. this._rttNode = null;
  24607. /**
  24608. * The internal quad mesh for RTT.
  24609. *
  24610. * @private
  24611. * @type {QuadMesh}
  24612. */
  24613. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24614. /**
  24615. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24616. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24617. *
  24618. * @type {string}
  24619. * @default 'render'
  24620. */
  24621. this.updateBeforeType = NodeUpdateType.RENDER;
  24622. }
  24623. /**
  24624. * Whether the internal render target should automatically be resized or not.
  24625. *
  24626. * @type {boolean}
  24627. * @readonly
  24628. * @default true
  24629. */
  24630. get autoResize() {
  24631. return this.width === null;
  24632. }
  24633. setup( builder ) {
  24634. this._rttNode = this.node.context( builder.getSharedContext() );
  24635. this._quadMesh.material.name = 'RTT';
  24636. this._quadMesh.material.needsUpdate = true;
  24637. return super.setup( builder );
  24638. }
  24639. /**
  24640. * Sets the size of the internal render target
  24641. *
  24642. * @param {number} width - The width to set.
  24643. * @param {number} height - The width to set.
  24644. */
  24645. setSize( width, height ) {
  24646. this.width = width;
  24647. this.height = height;
  24648. const effectiveWidth = width * this.pixelRatio;
  24649. const effectiveHeight = height * this.pixelRatio;
  24650. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24651. this.textureNeedsUpdate = true;
  24652. }
  24653. /**
  24654. * Sets the pixel ratio. This will also resize the render target.
  24655. *
  24656. * @param {number} pixelRatio - The pixel ratio to set.
  24657. */
  24658. setPixelRatio( pixelRatio ) {
  24659. this.pixelRatio = pixelRatio;
  24660. this.setSize( this.width, this.height );
  24661. }
  24662. updateBefore( { renderer } ) {
  24663. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24664. this.textureNeedsUpdate = false;
  24665. //
  24666. if ( this.autoResize === true ) {
  24667. const pixelRatio = renderer.getPixelRatio();
  24668. const size = renderer.getSize( _size$1 );
  24669. const effectiveWidth = size.width * pixelRatio;
  24670. const effectiveHeight = size.height * pixelRatio;
  24671. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24672. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24673. this.textureNeedsUpdate = true;
  24674. }
  24675. }
  24676. //
  24677. let name = 'RTT';
  24678. if ( this.node.name ) {
  24679. name = this.node.name + ' [ ' + name + ' ]';
  24680. }
  24681. this._quadMesh.material.fragmentNode = this._rttNode;
  24682. this._quadMesh.name = name;
  24683. //
  24684. const currentRenderTarget = renderer.getRenderTarget();
  24685. renderer.setRenderTarget( this.renderTarget );
  24686. this._quadMesh.render( renderer );
  24687. renderer.setRenderTarget( currentRenderTarget );
  24688. }
  24689. clone() {
  24690. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24691. newNode.sampler = this.sampler;
  24692. newNode.referenceNode = this;
  24693. return newNode;
  24694. }
  24695. }
  24696. /**
  24697. * TSL function for creating a RTT node.
  24698. *
  24699. * @tsl
  24700. * @function
  24701. * @param {Node} node - The node to render a texture with.
  24702. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24703. * @param {?number} [height=null] - The height of the internal render target.
  24704. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24705. * @returns {RTTNode}
  24706. */
  24707. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24708. /**
  24709. * TSL function for converting nodes to textures nodes.
  24710. *
  24711. * @tsl
  24712. * @function
  24713. * @param {Node} node - The node to render a texture with.
  24714. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24715. * @param {?number} [height=null] - The height of the internal render target.
  24716. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24717. * @returns {RTTNode}
  24718. */
  24719. const convertToTexture = ( node, ...params ) => {
  24720. if ( node.isSampleNode || node.isTextureNode ) return node;
  24721. if ( node.isPassNode ) return node.getTextureNode();
  24722. return rtt( node, ...params );
  24723. };
  24724. /**
  24725. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24726. * depth value and the camera's inverse projection matrix.
  24727. *
  24728. * @tsl
  24729. * @function
  24730. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24731. * @param {Node<float>} depth - The fragment's depth value.
  24732. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24733. * @return {Node<vec3>} The fragments position in view space.
  24734. */
  24735. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24736. let clipSpacePosition;
  24737. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24738. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24739. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24740. } else {
  24741. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24742. }
  24743. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24744. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24745. } );
  24746. /**
  24747. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24748. * and the camera's projection matrix
  24749. *
  24750. * @tsl
  24751. * @function
  24752. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24753. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24754. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24755. */
  24756. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24757. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24758. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24759. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24760. } );
  24761. /**
  24762. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24763. * target is available or if flat surface normals are required.
  24764. *
  24765. * @tsl
  24766. * @function
  24767. * @param {Node<vec2>} uv - The texture coordinate.
  24768. * @param {DepthTexture} depthTexture - The depth texture.
  24769. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24770. * @return {Node<vec3>} The computed normal vector.
  24771. */
  24772. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24773. const size = textureSize( textureLoad( depthTexture ) );
  24774. const p = ivec2( uv.mul( size ) ).toVar();
  24775. const c0 = textureLoad( depthTexture, p ).toVar();
  24776. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24777. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24778. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24779. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24780. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24781. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24782. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24783. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24784. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24785. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24786. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24787. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24788. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24789. 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 ) ) );
  24790. 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 ) ) );
  24791. return normalize( cross( dpdx, dpdy ) );
  24792. } );
  24793. /**
  24794. * Class representing a node that samples a value using a provided callback function.
  24795. *
  24796. * @extends Node
  24797. */
  24798. class SampleNode extends Node {
  24799. /**
  24800. * Returns the type of the node.
  24801. *
  24802. * @type {string}
  24803. * @readonly
  24804. * @static
  24805. */
  24806. static get type() {
  24807. return 'SampleNode';
  24808. }
  24809. /**
  24810. * Creates an instance of SampleNode.
  24811. *
  24812. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24813. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24814. */
  24815. constructor( callback, uvNode = null ) {
  24816. super();
  24817. this.callback = callback;
  24818. /**
  24819. * Represents the texture coordinates.
  24820. *
  24821. * @type {?Node<vec2|vec3>}
  24822. * @default null
  24823. */
  24824. this.uvNode = uvNode;
  24825. /**
  24826. * This flag can be used for type testing.
  24827. *
  24828. * @type {boolean}
  24829. * @readonly
  24830. * @default true
  24831. */
  24832. this.isSampleNode = true;
  24833. }
  24834. /**
  24835. * Sets up the node by sampling with the default UV accessor.
  24836. *
  24837. * @returns {Node} The result of the callback function when called with the UV node.
  24838. */
  24839. setup() {
  24840. return this.sample( uv$1() );
  24841. }
  24842. /**
  24843. * Calls the callback function with the provided UV node.
  24844. *
  24845. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24846. * @returns {Node} The result of the callback function.
  24847. */
  24848. sample( uv ) {
  24849. return this.callback( uv );
  24850. }
  24851. }
  24852. /**
  24853. * Helper function to create a SampleNode wrapped as a node object.
  24854. *
  24855. * @function
  24856. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24857. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24858. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24859. */
  24860. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24861. /**
  24862. * EventNode is a node that executes a callback during specific update phases.
  24863. *
  24864. * @augments Node
  24865. */
  24866. class EventNode extends Node {
  24867. static get type() {
  24868. return 'EventNode';
  24869. }
  24870. /**
  24871. * Creates an EventNode.
  24872. *
  24873. * @param {string} eventType - The type of event
  24874. * @param {Function} callback - The callback to execute on update.
  24875. */
  24876. constructor( eventType, callback ) {
  24877. super( 'void' );
  24878. this.eventType = eventType;
  24879. this.callback = callback;
  24880. if ( eventType === EventNode.OBJECT ) {
  24881. this.updateType = NodeUpdateType.OBJECT;
  24882. } else if ( eventType === EventNode.MATERIAL ) {
  24883. this.updateType = NodeUpdateType.RENDER;
  24884. }
  24885. }
  24886. update( frame ) {
  24887. this.callback( frame );
  24888. }
  24889. }
  24890. EventNode.OBJECT = 'object';
  24891. EventNode.MATERIAL = 'material';
  24892. /**
  24893. * Helper to create an EventNode and add it to the stack.
  24894. *
  24895. * @param {string} type - The event type.
  24896. * @param {Function} callback - The callback function.
  24897. * @returns {EventNode}
  24898. */
  24899. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24900. /**
  24901. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24902. *
  24903. * 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.
  24904. *
  24905. * @param {Function} callback - The callback function.
  24906. * @returns {EventNode}
  24907. */
  24908. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24909. /**
  24910. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24911. *
  24912. * 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.
  24913. *
  24914. * @param {Function} callback - The callback function.
  24915. * @returns {EventNode}
  24916. */
  24917. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24918. /**
  24919. * This special type of instanced buffer attribute is intended for compute shaders.
  24920. * In earlier three.js versions it was only possible to update attribute data
  24921. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24922. * new material system and renderer it is now possible to use compute shaders
  24923. * to compute the data for an attribute more efficiently on the GPU.
  24924. *
  24925. * The idea is to create an instance of this class and provide it as an input
  24926. * to {@link StorageBufferNode}.
  24927. *
  24928. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24929. *
  24930. * @augments InstancedBufferAttribute
  24931. */
  24932. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24933. /**
  24934. * Constructs a new storage instanced buffer attribute.
  24935. *
  24936. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24937. * The subsequent parameters are then obsolete.
  24938. * @param {number} itemSize - The item size.
  24939. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24940. */
  24941. constructor( count, itemSize, typeClass = Float32Array ) {
  24942. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24943. super( array, itemSize );
  24944. /**
  24945. * This flag can be used for type testing.
  24946. *
  24947. * @type {boolean}
  24948. * @readonly
  24949. * @default true
  24950. */
  24951. this.isStorageInstancedBufferAttribute = true;
  24952. }
  24953. }
  24954. /**
  24955. * This special type of buffer attribute is intended for compute shaders.
  24956. * In earlier three.js versions it was only possible to update attribute data
  24957. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24958. * new material system and renderer it is now possible to use compute shaders
  24959. * to compute the data for an attribute more efficiently on the GPU.
  24960. *
  24961. * The idea is to create an instance of this class and provide it as an input
  24962. * to {@link StorageBufferNode}.
  24963. *
  24964. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24965. *
  24966. * @augments BufferAttribute
  24967. */
  24968. class StorageBufferAttribute extends BufferAttribute {
  24969. /**
  24970. * Constructs a new storage buffer attribute.
  24971. *
  24972. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24973. * The subsequent parameters are then obsolete.
  24974. * @param {number} itemSize - The item size.
  24975. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24976. */
  24977. constructor( count, itemSize, typeClass = Float32Array ) {
  24978. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24979. super( array, itemSize );
  24980. /**
  24981. * This flag can be used for type testing.
  24982. *
  24983. * @type {boolean}
  24984. * @readonly
  24985. * @default true
  24986. */
  24987. this.isStorageBufferAttribute = true;
  24988. }
  24989. }
  24990. /**
  24991. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24992. *
  24993. * @tsl
  24994. * @function
  24995. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24996. * @param {string|Struct} [type='float'] - The data type.
  24997. * @returns {StorageBufferNode}
  24998. */
  24999. const attributeArray = ( count, type = 'float' ) => {
  25000. let itemSize, typedArray;
  25001. if ( type.isStruct === true ) {
  25002. itemSize = type.layout.getLength();
  25003. typedArray = getTypedArrayFromType( 'float' );
  25004. } else {
  25005. itemSize = getLengthFromType( type );
  25006. typedArray = getTypedArrayFromType( type );
  25007. }
  25008. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  25009. const node = storage( buffer, type, count );
  25010. return node;
  25011. };
  25012. /**
  25013. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  25014. *
  25015. * @tsl
  25016. * @function
  25017. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25018. * @param {string|Struct} [type='float'] - The data type.
  25019. * @returns {StorageBufferNode}
  25020. */
  25021. const instancedArray = ( count, type = 'float' ) => {
  25022. let itemSize, typedArray;
  25023. if ( type.isStruct === true ) {
  25024. itemSize = type.layout.getLength();
  25025. typedArray = getTypedArrayFromType( 'float' );
  25026. } else {
  25027. itemSize = getLengthFromType( type );
  25028. typedArray = getTypedArrayFromType( type );
  25029. }
  25030. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  25031. const node = storage( buffer, type, count );
  25032. return node;
  25033. };
  25034. /**
  25035. * A node for representing the uv coordinates of points.
  25036. *
  25037. * Can only be used with a WebGL backend. In WebGPU, point
  25038. * primitives always have the size of one pixel and can thus
  25039. * can't be used as sprite-like objects that display textures.
  25040. *
  25041. * @augments Node
  25042. */
  25043. class PointUVNode extends Node {
  25044. static get type() {
  25045. return 'PointUVNode';
  25046. }
  25047. /**
  25048. * Constructs a new point uv node.
  25049. */
  25050. constructor() {
  25051. super( 'vec2' );
  25052. /**
  25053. * This flag can be used for type testing.
  25054. *
  25055. * @type {boolean}
  25056. * @readonly
  25057. * @default true
  25058. */
  25059. this.isPointUVNode = true;
  25060. }
  25061. generate( /*builder*/ ) {
  25062. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  25063. }
  25064. }
  25065. /**
  25066. * TSL object that represents the uv coordinates of points.
  25067. *
  25068. * @tsl
  25069. * @type {PointUVNode}
  25070. */
  25071. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  25072. const _e1 = /*@__PURE__*/ new Euler();
  25073. const _m1 = /*@__PURE__*/ new Matrix4();
  25074. /**
  25075. * This module allows access to a collection of scene properties. The following predefined TSL objects
  25076. * are available for easier use:
  25077. *
  25078. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  25079. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  25080. * - `backgroundRotation`: A node that represents the scene's background rotation.
  25081. *
  25082. * @augments Node
  25083. */
  25084. class SceneNode extends Node {
  25085. static get type() {
  25086. return 'SceneNode';
  25087. }
  25088. /**
  25089. * Constructs a new scene node.
  25090. *
  25091. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  25092. * @param {?Scene} [scene=null] - A reference to the scene.
  25093. */
  25094. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  25095. super();
  25096. /**
  25097. * The scope defines the type of scene property that is accessed.
  25098. *
  25099. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  25100. */
  25101. this.scope = scope;
  25102. /**
  25103. * A reference to the scene that is going to be accessed.
  25104. *
  25105. * @type {?Scene}
  25106. * @default null
  25107. */
  25108. this.scene = scene;
  25109. }
  25110. /**
  25111. * Depending on the scope, the method returns a different type of node that represents
  25112. * the respective scene property.
  25113. *
  25114. * @param {NodeBuilder} builder - The current node builder.
  25115. * @return {Node} The output node.
  25116. */
  25117. setup( builder ) {
  25118. const scope = this.scope;
  25119. const scene = this.scene !== null ? this.scene : builder.scene;
  25120. let output;
  25121. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  25122. output = reference( 'backgroundBlurriness', 'float', scene );
  25123. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  25124. output = reference( 'backgroundIntensity', 'float', scene );
  25125. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  25126. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25127. const background = scene.background;
  25128. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  25129. _e1.copy( scene.backgroundRotation );
  25130. // accommodate left-handed frame
  25131. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  25132. _m1.makeRotationFromEuler( _e1 );
  25133. } else {
  25134. _m1.identity();
  25135. }
  25136. return _m1;
  25137. } );
  25138. } else {
  25139. error( 'SceneNode: Unknown scope:', scope );
  25140. }
  25141. return output;
  25142. }
  25143. }
  25144. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  25145. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  25146. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  25147. /**
  25148. * TSL object that represents the scene's background blurriness.
  25149. *
  25150. * @tsl
  25151. * @type {SceneNode}
  25152. */
  25153. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  25154. /**
  25155. * TSL object that represents the scene's background intensity.
  25156. *
  25157. * @tsl
  25158. * @type {SceneNode}
  25159. */
  25160. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  25161. /**
  25162. * TSL object that represents the scene's background rotation.
  25163. *
  25164. * @tsl
  25165. * @type {SceneNode}
  25166. */
  25167. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  25168. /**
  25169. * This special version of a texture node can be used to
  25170. * write data into a storage texture with a compute shader.
  25171. *
  25172. * ```js
  25173. * const storageTexture = new THREE.StorageTexture( width, height );
  25174. *
  25175. * const computeTexture = Fn( ( { storageTexture } ) => {
  25176. *
  25177. * const posX = instanceIndex.mod( width );
  25178. * const posY = instanceIndex.div( width );
  25179. * const indexUV = uvec2( posX, posY );
  25180. *
  25181. * // generate RGB values
  25182. *
  25183. * const r = 1;
  25184. * const g = 1;
  25185. * const b = 1;
  25186. *
  25187. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  25188. *
  25189. * } );
  25190. *
  25191. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  25192. * renderer.computeAsync( computeNode );
  25193. * ```
  25194. *
  25195. * This node can only be used with a WebGPU backend.
  25196. *
  25197. * @augments TextureNode
  25198. */
  25199. class StorageTextureNode extends TextureNode {
  25200. static get type() {
  25201. return 'StorageTextureNode';
  25202. }
  25203. /**
  25204. * Constructs a new storage texture node.
  25205. *
  25206. * @param {StorageTexture} value - The storage texture.
  25207. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25208. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25209. */
  25210. constructor( value, uvNode, storeNode = null ) {
  25211. super( value, uvNode );
  25212. /**
  25213. * The value node that should be stored in the texture.
  25214. *
  25215. * @type {?Node}
  25216. * @default null
  25217. */
  25218. this.storeNode = storeNode;
  25219. /**
  25220. * The mip level to write to for storage textures.
  25221. *
  25222. * @type {number}
  25223. * @default 0
  25224. */
  25225. this.mipLevel = 0;
  25226. /**
  25227. * This flag can be used for type testing.
  25228. *
  25229. * @type {boolean}
  25230. * @readonly
  25231. * @default true
  25232. */
  25233. this.isStorageTextureNode = true;
  25234. /**
  25235. * The access type of the texture node.
  25236. *
  25237. * @type {string}
  25238. * @default 'writeOnly'
  25239. */
  25240. this.access = NodeAccess.WRITE_ONLY;
  25241. }
  25242. /**
  25243. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  25244. *
  25245. * @param {NodeBuilder} builder - The current node builder.
  25246. * @return {string} The input type.
  25247. */
  25248. getInputType( /*builder*/ ) {
  25249. return 'storageTexture';
  25250. }
  25251. setup( builder ) {
  25252. super.setup( builder );
  25253. const properties = builder.getNodeProperties( this );
  25254. properties.storeNode = this.storeNode;
  25255. return properties;
  25256. }
  25257. /**
  25258. * Defines the node access.
  25259. *
  25260. * @param {string} value - The node access.
  25261. * @return {StorageTextureNode} A reference to this node.
  25262. */
  25263. setAccess( value ) {
  25264. this.access = value;
  25265. return this;
  25266. }
  25267. /**
  25268. * Sets the mip level to write to.
  25269. *
  25270. * @param {number} level - The mip level.
  25271. * @return {StorageTextureNode} A reference to this node.
  25272. */
  25273. setMipLevel( level ) {
  25274. this.mipLevel = level;
  25275. return this;
  25276. }
  25277. /**
  25278. * Generates the code snippet of the storage node. If no `storeNode`
  25279. * is defined, the texture node is generated as normal texture.
  25280. *
  25281. * @param {NodeBuilder} builder - The current node builder.
  25282. * @param {string} output - The current output.
  25283. * @return {string} The generated code snippet.
  25284. */
  25285. generate( builder, output ) {
  25286. let snippet;
  25287. if ( this.storeNode !== null ) {
  25288. snippet = this.generateStore( builder );
  25289. } else {
  25290. snippet = super.generate( builder, output );
  25291. }
  25292. return snippet;
  25293. }
  25294. /**
  25295. * Convenience method for configuring a read/write node access.
  25296. *
  25297. * @return {StorageTextureNode} A reference to this node.
  25298. */
  25299. toReadWrite() {
  25300. return this.setAccess( NodeAccess.READ_WRITE );
  25301. }
  25302. /**
  25303. * Convenience method for configuring a read-only node access.
  25304. *
  25305. * @return {StorageTextureNode} A reference to this node.
  25306. */
  25307. toReadOnly() {
  25308. return this.setAccess( NodeAccess.READ_ONLY );
  25309. }
  25310. /**
  25311. * Convenience method for configuring a write-only node access.
  25312. *
  25313. * @return {StorageTextureNode} A reference to this node.
  25314. */
  25315. toWriteOnly() {
  25316. return this.setAccess( NodeAccess.WRITE_ONLY );
  25317. }
  25318. /**
  25319. * Generates the code snippet of the storage texture node.
  25320. *
  25321. * @param {NodeBuilder} builder - The current node builder.
  25322. */
  25323. generateStore( builder ) {
  25324. const properties = builder.getNodeProperties( this );
  25325. const { uvNode, storeNode, depthNode } = properties;
  25326. const textureProperty = super.generate( builder, 'property' );
  25327. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  25328. const storeSnippet = storeNode.build( builder, 'vec4' );
  25329. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  25330. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  25331. builder.addLineFlowCode( snippet, this );
  25332. }
  25333. clone() {
  25334. const newNode = super.clone();
  25335. newNode.storeNode = this.storeNode;
  25336. newNode.mipLevel = this.mipLevel;
  25337. return newNode;
  25338. }
  25339. }
  25340. /**
  25341. * TSL function for creating a storage texture node.
  25342. *
  25343. * @tsl
  25344. * @function
  25345. * @param {StorageTexture} value - The storage texture.
  25346. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  25347. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25348. * @returns {StorageTextureNode}
  25349. */
  25350. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  25351. /**
  25352. * TODO: Explain difference to `storageTexture()`.
  25353. *
  25354. * @tsl
  25355. * @function
  25356. * @param {StorageTexture} value - The storage texture.
  25357. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25358. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25359. * @returns {StorageTextureNode}
  25360. */
  25361. const textureStore = ( value, uvNode, storeNode ) => {
  25362. const node = storageTexture( value, uvNode, storeNode );
  25363. if ( storeNode !== null ) node.toStack();
  25364. return node;
  25365. };
  25366. const normal = Fn( ( { texture, uv } ) => {
  25367. const epsilon = 0.0001;
  25368. const ret = vec3().toVar();
  25369. If( uv.x.lessThan( epsilon ), () => {
  25370. ret.assign( vec3( 1, 0, 0 ) );
  25371. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  25372. ret.assign( vec3( 0, 1, 0 ) );
  25373. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  25374. ret.assign( vec3( 0, 0, 1 ) );
  25375. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  25376. ret.assign( vec3( -1, 0, 0 ) );
  25377. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  25378. ret.assign( vec3( 0, -1, 0 ) );
  25379. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  25380. ret.assign( vec3( 0, 0, -1 ) );
  25381. } ).Else( () => {
  25382. const step = 0.01;
  25383. 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 );
  25384. 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 );
  25385. 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 );
  25386. ret.assign( vec3( x, y, z ) );
  25387. } );
  25388. return ret.normalize();
  25389. } );
  25390. /**
  25391. * This type of uniform node represents a 3D texture.
  25392. *
  25393. * @augments TextureNode
  25394. */
  25395. class Texture3DNode extends TextureNode {
  25396. static get type() {
  25397. return 'Texture3DNode';
  25398. }
  25399. /**
  25400. * Constructs a new 3D texture node.
  25401. *
  25402. * @param {Data3DTexture} value - The 3D texture.
  25403. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25404. * @param {?Node<int>} [levelNode=null] - The level node.
  25405. */
  25406. constructor( value, uvNode = null, levelNode = null ) {
  25407. super( value, uvNode, levelNode );
  25408. /**
  25409. * This flag can be used for type testing.
  25410. *
  25411. * @type {boolean}
  25412. * @readonly
  25413. * @default true
  25414. */
  25415. this.isTexture3DNode = true;
  25416. }
  25417. /**
  25418. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  25419. *
  25420. * @param {NodeBuilder} builder - The current node builder.
  25421. * @return {string} The input type.
  25422. */
  25423. getInputType( /*builder*/ ) {
  25424. return 'texture3D';
  25425. }
  25426. /**
  25427. * Returns a default uv node which is in context of 3D textures a three-dimensional
  25428. * uv node.
  25429. *
  25430. * @return {Node<vec3>} The default uv node.
  25431. */
  25432. getDefaultUV() {
  25433. return vec3( 0.5, 0.5, 0.5 );
  25434. }
  25435. /**
  25436. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  25437. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  25438. *
  25439. * @param {boolean} value - The update toggle.
  25440. */
  25441. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  25442. /**
  25443. * Overwrites the default implementation to return the unmodified uv node.
  25444. *
  25445. * @param {NodeBuilder} builder - The current node builder.
  25446. * @param {Node} uvNode - The uv node to setup.
  25447. * @return {Node} The unmodified uv node.
  25448. */
  25449. setupUV( builder, uvNode ) {
  25450. const texture = this.value;
  25451. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25452. if ( this.sampler ) {
  25453. uvNode = uvNode.flipY();
  25454. } else {
  25455. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25456. }
  25457. }
  25458. return uvNode;
  25459. }
  25460. /**
  25461. * Generates the uv code snippet.
  25462. *
  25463. * @param {NodeBuilder} builder - The current node builder.
  25464. * @param {Node} uvNode - The uv node to generate code for.
  25465. * @return {string} The generated code snippet.
  25466. */
  25467. generateUV( builder, uvNode ) {
  25468. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25469. }
  25470. /**
  25471. * Generates the offset code snippet.
  25472. *
  25473. * @param {NodeBuilder} builder - The current node builder.
  25474. * @param {Node} offsetNode - The offset node to generate code for.
  25475. * @return {string} The generated code snippet.
  25476. */
  25477. generateOffset( builder, offsetNode ) {
  25478. return offsetNode.build( builder, 'ivec3' );
  25479. }
  25480. /**
  25481. * TODO.
  25482. *
  25483. * @param {Node<vec3>} uvNode - The uv node .
  25484. * @return {Node<vec3>} TODO.
  25485. */
  25486. normal( uvNode ) {
  25487. return normal( { texture: this, uv: uvNode } );
  25488. }
  25489. }
  25490. /**
  25491. * TSL function for creating a 3D texture node.
  25492. *
  25493. * @tsl
  25494. * @function
  25495. * @param {Data3DTexture} value - The 3D texture.
  25496. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25497. * @param {?Node<int>} [levelNode=null] - The level node.
  25498. * @returns {Texture3DNode}
  25499. */
  25500. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25501. /**
  25502. * A special type of reference node that allows to link values in
  25503. * `userData` fields to node objects.
  25504. * ```js
  25505. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25506. *
  25507. * const material = new THREE.SpriteNodeMaterial();
  25508. * material.rotationNode = userData( 'rotation', 'float' );
  25509. * ```
  25510. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25511. * will automatically be updated when the `rotation` user data field changes.
  25512. *
  25513. * @augments ReferenceNode
  25514. */
  25515. class UserDataNode extends ReferenceNode {
  25516. static get type() {
  25517. return 'UserDataNode';
  25518. }
  25519. /**
  25520. * Constructs a new user data node.
  25521. *
  25522. * @param {string} property - The property name that should be referenced by the node.
  25523. * @param {string} inputType - The node data type of the reference.
  25524. * @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.
  25525. */
  25526. constructor( property, inputType, userData = null ) {
  25527. super( property, inputType, userData );
  25528. /**
  25529. * A reference to the `userData` object. If not provided, the `userData`
  25530. * property of the 3D object that uses the node material is evaluated.
  25531. *
  25532. * @type {?Object}
  25533. * @default null
  25534. */
  25535. this.userData = userData;
  25536. }
  25537. /**
  25538. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25539. * `userData` field.
  25540. *
  25541. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25542. * @return {Object} A reference to the `userData` field.
  25543. */
  25544. updateReference( state ) {
  25545. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25546. return this.reference;
  25547. }
  25548. }
  25549. /**
  25550. * TSL function for creating a user data node.
  25551. *
  25552. * @tsl
  25553. * @function
  25554. * @param {string} name - The property name that should be referenced by the node.
  25555. * @param {string} inputType - The node data type of the reference.
  25556. * @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.
  25557. * @returns {UserDataNode}
  25558. */
  25559. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25560. const _objectData = new WeakMap();
  25561. /**
  25562. * A node for representing motion or velocity vectors. Foundation
  25563. * for advanced post processing effects like motion blur or TRAA.
  25564. *
  25565. * The node keeps track of the model, view and projection matrices
  25566. * of the previous frame and uses them to compute offsets in NDC space.
  25567. * These offsets represent the final velocity.
  25568. *
  25569. * @augments TempNode
  25570. */
  25571. class VelocityNode extends TempNode {
  25572. static get type() {
  25573. return 'VelocityNode';
  25574. }
  25575. /**
  25576. * Constructs a new vertex color node.
  25577. */
  25578. constructor() {
  25579. super( 'vec2' );
  25580. /**
  25581. * The current projection matrix.
  25582. *
  25583. * @type {?Matrix4}
  25584. * @default null
  25585. */
  25586. this.projectionMatrix = null;
  25587. /**
  25588. * Overwritten since velocity nodes are updated per object.
  25589. *
  25590. * @type {string}
  25591. * @default 'object'
  25592. */
  25593. this.updateType = NodeUpdateType.OBJECT;
  25594. /**
  25595. * Overwritten since velocity nodes save data after the update.
  25596. *
  25597. * @type {string}
  25598. * @default 'object'
  25599. */
  25600. this.updateAfterType = NodeUpdateType.OBJECT;
  25601. /**
  25602. * Uniform node representing the previous model matrix in world space.
  25603. *
  25604. * @type {UniformNode<mat4>}
  25605. * @default null
  25606. */
  25607. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25608. /**
  25609. * Uniform node representing the previous projection matrix.
  25610. *
  25611. * @type {UniformNode<mat4>}
  25612. * @default null
  25613. */
  25614. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25615. /**
  25616. * Uniform node representing the previous view matrix.
  25617. *
  25618. * @type {UniformNode<mat4>}
  25619. * @default null
  25620. */
  25621. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25622. }
  25623. /**
  25624. * Sets the given projection matrix.
  25625. *
  25626. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25627. */
  25628. setProjectionMatrix( projectionMatrix ) {
  25629. this.projectionMatrix = projectionMatrix;
  25630. }
  25631. /**
  25632. * Updates velocity specific uniforms.
  25633. *
  25634. * @param {NodeFrame} frame - A reference to the current node frame.
  25635. */
  25636. update( { frameId, camera, object } ) {
  25637. const previousModelMatrix = getPreviousMatrix( object );
  25638. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25639. //
  25640. const cameraData = getData( camera );
  25641. if ( cameraData.frameId !== frameId ) {
  25642. cameraData.frameId = frameId;
  25643. if ( cameraData.previousProjectionMatrix === undefined ) {
  25644. cameraData.previousProjectionMatrix = new Matrix4();
  25645. cameraData.previousCameraViewMatrix = new Matrix4();
  25646. cameraData.currentProjectionMatrix = new Matrix4();
  25647. cameraData.currentCameraViewMatrix = new Matrix4();
  25648. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25649. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25650. } else {
  25651. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25652. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25653. }
  25654. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25655. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25656. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25657. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25658. }
  25659. }
  25660. /**
  25661. * Overwritten to updated velocity specific uniforms.
  25662. *
  25663. * @param {NodeFrame} frame - A reference to the current node frame.
  25664. */
  25665. updateAfter( { object } ) {
  25666. getPreviousMatrix( object ).copy( object.matrixWorld );
  25667. }
  25668. /**
  25669. * Implements the velocity computation based on the previous and current vertex data.
  25670. *
  25671. * @param {NodeBuilder} builder - A reference to the current node builder.
  25672. * @return {Node<vec2>} The motion vector.
  25673. */
  25674. setup( /*builder*/ ) {
  25675. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25676. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25677. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25678. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25679. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25680. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25681. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25682. return velocity;
  25683. }
  25684. }
  25685. function getData( object ) {
  25686. let objectData = _objectData.get( object );
  25687. if ( objectData === undefined ) {
  25688. objectData = {};
  25689. _objectData.set( object, objectData );
  25690. }
  25691. return objectData;
  25692. }
  25693. function getPreviousMatrix( object, index = 0 ) {
  25694. const objectData = getData( object );
  25695. let matrix = objectData[ index ];
  25696. if ( matrix === undefined ) {
  25697. objectData[ index ] = matrix = new Matrix4();
  25698. objectData[ index ].copy( object.matrixWorld );
  25699. }
  25700. return matrix;
  25701. }
  25702. /**
  25703. * TSL object that represents the velocity of a render pass.
  25704. *
  25705. * @tsl
  25706. * @type {VelocityNode}
  25707. */
  25708. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25709. /**
  25710. * Computes a grayscale value for the given RGB color value.
  25711. *
  25712. * @tsl
  25713. * @function
  25714. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25715. * @return {Node<vec3>} The grayscale color.
  25716. */
  25717. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25718. return luminance( color.rgb );
  25719. } );
  25720. /**
  25721. * Super-saturates or desaturates the given RGB color.
  25722. *
  25723. * @tsl
  25724. * @function
  25725. * @param {Node<vec3>} color - The input color.
  25726. * @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.
  25727. * @return {Node<vec3>} The saturated color.
  25728. */
  25729. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25730. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25731. } );
  25732. /**
  25733. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25734. * in a more natural and visually appealing image with enhanced color depth
  25735. * compared to {@link ColorAdjustment#saturation}.
  25736. *
  25737. * @tsl
  25738. * @function
  25739. * @param {Node<vec3>} color - The input color.
  25740. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25741. * @return {Node<vec3>} The updated color.
  25742. */
  25743. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25744. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25745. const mx = color.r.max( color.g.max( color.b ) );
  25746. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25747. return mix( color.rgb, mx, amt );
  25748. } );
  25749. /**
  25750. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25751. *
  25752. * @tsl
  25753. * @function
  25754. * @param {Node<vec3>} color - The input color.
  25755. * @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.
  25756. * @return {Node<vec3>} The updated color.
  25757. */
  25758. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25759. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25760. const cosAngle = adjustment.cos();
  25761. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25762. } );
  25763. /**
  25764. * Computes the luminance for the given RGB color value.
  25765. *
  25766. * @tsl
  25767. * @function
  25768. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25769. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25770. * @return {Node<float>} The luminance.
  25771. */
  25772. const luminance = (
  25773. color,
  25774. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25775. ) => dot( color, luminanceCoefficients );
  25776. /**
  25777. * Color Decision List (CDL) v1.2
  25778. *
  25779. * Compact representation of color grading information, defined by slope, offset, power, and
  25780. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25781. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25782. *
  25783. * @tsl
  25784. * @function
  25785. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25786. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25787. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25788. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25789. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25790. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25791. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25792. *
  25793. * References:
  25794. * - ASC CDL v1.2
  25795. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25796. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25797. */
  25798. const cdl = /*@__PURE__*/ Fn( ( [
  25799. color,
  25800. slope = vec3( 1 ),
  25801. offset = vec3( 0 ),
  25802. power = vec3( 1 ),
  25803. saturation = float( 1 ),
  25804. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25805. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25806. ] ) => {
  25807. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25808. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25809. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25810. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25811. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25812. const pv = v.pow( power ).toVar();
  25813. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25814. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25815. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25816. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25817. return vec4( v.rgb, color.a );
  25818. } );
  25819. /**
  25820. * Represents a posterize effect which reduces the number of colors
  25821. * in an image, resulting in a more blocky and stylized appearance.
  25822. *
  25823. * @augments TempNode
  25824. */
  25825. class PosterizeNode extends TempNode {
  25826. static get type() {
  25827. return 'PosterizeNode';
  25828. }
  25829. /**
  25830. * Constructs a new posterize node.
  25831. *
  25832. * @param {Node} sourceNode - The input color.
  25833. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25834. */
  25835. constructor( sourceNode, stepsNode ) {
  25836. super();
  25837. /**
  25838. * The input color.
  25839. *
  25840. * @type {Node}
  25841. */
  25842. this.sourceNode = sourceNode;
  25843. /**
  25844. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25845. *
  25846. * @type {Node}
  25847. */
  25848. this.stepsNode = stepsNode;
  25849. }
  25850. setup() {
  25851. const { sourceNode, stepsNode } = this;
  25852. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25853. }
  25854. }
  25855. /**
  25856. * TSL function for creating a posterize node.
  25857. *
  25858. * @tsl
  25859. * @function
  25860. * @param {Node} sourceNode - The input color.
  25861. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25862. * @returns {PosterizeNode}
  25863. */
  25864. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25865. const _size = /*@__PURE__*/ new Vector2();
  25866. /**
  25867. * Represents the texture of a pass node.
  25868. *
  25869. * @augments TextureNode
  25870. */
  25871. class PassTextureNode extends TextureNode {
  25872. static get type() {
  25873. return 'PassTextureNode';
  25874. }
  25875. /**
  25876. * Constructs a new pass texture node.
  25877. *
  25878. * @param {PassNode} passNode - The pass node.
  25879. * @param {Texture} texture - The output texture.
  25880. */
  25881. constructor( passNode, texture ) {
  25882. super( texture );
  25883. /**
  25884. * A reference to the pass node.
  25885. *
  25886. * @type {PassNode}
  25887. */
  25888. this.passNode = passNode;
  25889. this.setUpdateMatrix( false );
  25890. }
  25891. setup( builder ) {
  25892. this.passNode.build( builder );
  25893. return super.setup( builder );
  25894. }
  25895. clone() {
  25896. return new this.constructor( this.passNode, this.value );
  25897. }
  25898. }
  25899. /**
  25900. * An extension of `PassTextureNode` which allows to manage more than one
  25901. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25902. *
  25903. * @augments PassTextureNode
  25904. */
  25905. class PassMultipleTextureNode extends PassTextureNode {
  25906. static get type() {
  25907. return 'PassMultipleTextureNode';
  25908. }
  25909. /**
  25910. * Constructs a new pass texture node.
  25911. *
  25912. * @param {PassNode} passNode - The pass node.
  25913. * @param {string} textureName - The output texture name.
  25914. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25915. */
  25916. constructor( passNode, textureName, previousTexture = false ) {
  25917. // null is passed to the super call since this class does not
  25918. // use an external texture for rendering pass data into. Instead
  25919. // the texture is managed by the pass node itself
  25920. super( passNode, null );
  25921. /**
  25922. * The output texture name.
  25923. *
  25924. * @type {string}
  25925. */
  25926. this.textureName = textureName;
  25927. /**
  25928. * Whether previous frame data should be used or not.
  25929. *
  25930. * @type {boolean}
  25931. */
  25932. this.previousTexture = previousTexture;
  25933. }
  25934. /**
  25935. * Updates the texture reference of this node.
  25936. */
  25937. updateTexture() {
  25938. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25939. }
  25940. setup( builder ) {
  25941. this.updateTexture();
  25942. return super.setup( builder );
  25943. }
  25944. clone() {
  25945. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25946. newNode.uvNode = this.uvNode;
  25947. newNode.levelNode = this.levelNode;
  25948. newNode.biasNode = this.biasNode;
  25949. newNode.sampler = this.sampler;
  25950. newNode.depthNode = this.depthNode;
  25951. newNode.compareNode = this.compareNode;
  25952. newNode.gradNode = this.gradNode;
  25953. newNode.offsetNode = this.offsetNode;
  25954. return newNode;
  25955. }
  25956. }
  25957. /**
  25958. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25959. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25960. * via MRT for further processing.
  25961. *
  25962. * ```js
  25963. * const postProcessing = new PostProcessing( renderer );
  25964. *
  25965. * const scenePass = pass( scene, camera );
  25966. *
  25967. * postProcessing.outputNode = scenePass;
  25968. * ```
  25969. *
  25970. * @augments TempNode
  25971. */
  25972. class PassNode extends TempNode {
  25973. static get type() {
  25974. return 'PassNode';
  25975. }
  25976. /**
  25977. * Constructs a new pass node.
  25978. *
  25979. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25980. * @param {Scene} scene - A reference to the scene.
  25981. * @param {Camera} camera - A reference to the camera.
  25982. * @param {Object} options - Options for the internal render target.
  25983. */
  25984. constructor( scope, scene, camera, options = {} ) {
  25985. super( 'vec4' );
  25986. /**
  25987. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25988. *
  25989. * @type {('color'|'depth')}
  25990. */
  25991. this.scope = scope;
  25992. /**
  25993. * A reference to the scene.
  25994. *
  25995. * @type {Scene}
  25996. */
  25997. this.scene = scene;
  25998. /**
  25999. * A reference to the camera.
  26000. *
  26001. * @type {Camera}
  26002. */
  26003. this.camera = camera;
  26004. /**
  26005. * Options for the internal render target.
  26006. *
  26007. * @type {Object}
  26008. */
  26009. this.options = options;
  26010. /**
  26011. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  26012. *
  26013. * @private
  26014. * @type {number}
  26015. * @default 1
  26016. */
  26017. this._pixelRatio = 1;
  26018. /**
  26019. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  26020. * @private
  26021. * @type {number}
  26022. * @default 1
  26023. */
  26024. this._width = 1;
  26025. /**
  26026. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  26027. * @private
  26028. * @type {number}
  26029. * @default 1
  26030. */
  26031. this._height = 1;
  26032. const depthTexture = new DepthTexture();
  26033. depthTexture.isRenderTargetTexture = true;
  26034. //depthTexture.type = FloatType;
  26035. depthTexture.name = 'depth';
  26036. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  26037. renderTarget.texture.name = 'output';
  26038. renderTarget.depthTexture = depthTexture;
  26039. /**
  26040. * The pass's render target.
  26041. *
  26042. * @type {RenderTarget}
  26043. */
  26044. this.renderTarget = renderTarget;
  26045. /**
  26046. * A dictionary holding the internal result textures.
  26047. *
  26048. * @private
  26049. * @type {Object<string, Texture>}
  26050. */
  26051. this._textures = {
  26052. output: renderTarget.texture,
  26053. depth: depthTexture
  26054. };
  26055. /**
  26056. * A dictionary holding the internal texture nodes.
  26057. *
  26058. * @private
  26059. * @type {Object<string, TextureNode>}
  26060. */
  26061. this._textureNodes = {};
  26062. /**
  26063. * A dictionary holding the internal depth nodes.
  26064. *
  26065. * @private
  26066. * @type {Object}
  26067. */
  26068. this._linearDepthNodes = {};
  26069. /**
  26070. * A dictionary holding the internal viewZ nodes.
  26071. *
  26072. * @private
  26073. * @type {Object}
  26074. */
  26075. this._viewZNodes = {};
  26076. /**
  26077. * A dictionary holding the texture data of the previous frame.
  26078. * Used for computing velocity/motion vectors.
  26079. *
  26080. * @private
  26081. * @type {Object<string, Texture>}
  26082. */
  26083. this._previousTextures = {};
  26084. /**
  26085. * A dictionary holding the texture nodes of the previous frame.
  26086. * Used for computing velocity/motion vectors.
  26087. *
  26088. * @private
  26089. * @type {Object<string, TextureNode>}
  26090. */
  26091. this._previousTextureNodes = {};
  26092. /**
  26093. * The `near` property of the camera as a uniform.
  26094. *
  26095. * @private
  26096. * @type {UniformNode}
  26097. */
  26098. this._cameraNear = uniform( 0 );
  26099. /**
  26100. * The `far` property of the camera as a uniform.
  26101. *
  26102. * @private
  26103. * @type {UniformNode}
  26104. */
  26105. this._cameraFar = uniform( 0 );
  26106. /**
  26107. * A MRT node configuring the MRT settings.
  26108. *
  26109. * @private
  26110. * @type {?MRTNode}
  26111. * @default null
  26112. */
  26113. this._mrt = null;
  26114. /**
  26115. * Layer object for configuring the camera that is used
  26116. * to produce the pass.
  26117. *
  26118. * @private
  26119. * @type {?Layers}
  26120. * @default null
  26121. */
  26122. this._layers = null;
  26123. /**
  26124. * Scales the resolution of the internal render target.
  26125. *
  26126. * @private
  26127. * @type {number}
  26128. * @default 1
  26129. */
  26130. this._resolutionScale = 1;
  26131. /**
  26132. * Custom viewport definition.
  26133. *
  26134. * @private
  26135. * @type {?Vector4}
  26136. * @default null
  26137. */
  26138. this._viewport = null;
  26139. /**
  26140. * Custom scissor definition.
  26141. *
  26142. * @private
  26143. * @type {?Vector4}
  26144. * @default null
  26145. */
  26146. this._scissor = null;
  26147. /**
  26148. * This flag can be used for type testing.
  26149. *
  26150. * @type {boolean}
  26151. * @readonly
  26152. * @default true
  26153. */
  26154. this.isPassNode = true;
  26155. /**
  26156. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  26157. * scene once per frame in its {@link PassNode#updateBefore} method.
  26158. *
  26159. * @type {string}
  26160. * @default 'frame'
  26161. */
  26162. this.updateBeforeType = NodeUpdateType.FRAME;
  26163. /**
  26164. * This flag is used for global cache.
  26165. *
  26166. * @type {boolean}
  26167. * @default true
  26168. */
  26169. this.global = true;
  26170. }
  26171. /**
  26172. * Sets the resolution scale for the pass.
  26173. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  26174. *
  26175. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  26176. * @return {PassNode} A reference to this pass.
  26177. */
  26178. setResolutionScale( resolutionScale ) {
  26179. this._resolutionScale = resolutionScale;
  26180. return this;
  26181. }
  26182. /**
  26183. * Gets the current resolution scale of the pass.
  26184. *
  26185. * @return {number} The current resolution scale. A value of `1` means full resolution.
  26186. */
  26187. getResolutionScale() {
  26188. return this._resolutionScale;
  26189. }
  26190. /**
  26191. * Sets the resolution for the pass.
  26192. * The resolution is a factor that is multiplied with the renderer's width and height.
  26193. *
  26194. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  26195. * @return {PassNode} A reference to this pass.
  26196. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  26197. */
  26198. setResolution( resolution ) { // @deprecated, r181
  26199. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  26200. return this.setResolutionScale( resolution );
  26201. }
  26202. /**
  26203. * Gets the current resolution of the pass.
  26204. *
  26205. * @return {number} The current resolution. A value of `1` means full resolution.
  26206. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  26207. */
  26208. getResolution() { // @deprecated, r181
  26209. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  26210. return this.getResolutionScale();
  26211. }
  26212. /**
  26213. * Sets the layer configuration that should be used when rendering the pass.
  26214. *
  26215. * @param {Layers} layers - The layers object to set.
  26216. * @return {PassNode} A reference to this pass.
  26217. */
  26218. setLayers( layers ) {
  26219. this._layers = layers;
  26220. return this;
  26221. }
  26222. /**
  26223. * Gets the current layer configuration of the pass.
  26224. *
  26225. * @return {?Layers} .
  26226. */
  26227. getLayers() {
  26228. return this._layers;
  26229. }
  26230. /**
  26231. * Sets the given MRT node to setup MRT for this pass.
  26232. *
  26233. * @param {MRTNode} mrt - The MRT object.
  26234. * @return {PassNode} A reference to this pass.
  26235. */
  26236. setMRT( mrt ) {
  26237. this._mrt = mrt;
  26238. return this;
  26239. }
  26240. /**
  26241. * Returns the current MRT node.
  26242. *
  26243. * @return {MRTNode} The current MRT node.
  26244. */
  26245. getMRT() {
  26246. return this._mrt;
  26247. }
  26248. /**
  26249. * Returns the texture for the given output name.
  26250. *
  26251. * @param {string} name - The output name to get the texture for.
  26252. * @return {Texture} The texture.
  26253. */
  26254. getTexture( name ) {
  26255. let texture = this._textures[ name ];
  26256. if ( texture === undefined ) {
  26257. const refTexture = this.renderTarget.texture;
  26258. texture = refTexture.clone();
  26259. texture.name = name;
  26260. this._textures[ name ] = texture;
  26261. this.renderTarget.textures.push( texture );
  26262. }
  26263. return texture;
  26264. }
  26265. /**
  26266. * Returns the texture holding the data of the previous frame for the given output name.
  26267. *
  26268. * @param {string} name - The output name to get the texture for.
  26269. * @return {Texture} The texture holding the data of the previous frame.
  26270. */
  26271. getPreviousTexture( name ) {
  26272. let texture = this._previousTextures[ name ];
  26273. if ( texture === undefined ) {
  26274. texture = this.getTexture( name ).clone();
  26275. this._previousTextures[ name ] = texture;
  26276. }
  26277. return texture;
  26278. }
  26279. /**
  26280. * Switches current and previous textures for the given output name.
  26281. *
  26282. * @param {string} name - The output name.
  26283. */
  26284. toggleTexture( name ) {
  26285. const prevTexture = this._previousTextures[ name ];
  26286. if ( prevTexture !== undefined ) {
  26287. const texture = this._textures[ name ];
  26288. const index = this.renderTarget.textures.indexOf( texture );
  26289. this.renderTarget.textures[ index ] = prevTexture;
  26290. this._textures[ name ] = prevTexture;
  26291. this._previousTextures[ name ] = texture;
  26292. this._textureNodes[ name ].updateTexture();
  26293. this._previousTextureNodes[ name ].updateTexture();
  26294. }
  26295. }
  26296. /**
  26297. * Returns the texture node for the given output name.
  26298. *
  26299. * @param {string} [name='output'] - The output name to get the texture node for.
  26300. * @return {TextureNode} The texture node.
  26301. */
  26302. getTextureNode( name = 'output' ) {
  26303. let textureNode = this._textureNodes[ name ];
  26304. if ( textureNode === undefined ) {
  26305. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  26306. textureNode.updateTexture();
  26307. this._textureNodes[ name ] = textureNode;
  26308. }
  26309. return textureNode;
  26310. }
  26311. /**
  26312. * Returns the previous texture node for the given output name.
  26313. *
  26314. * @param {string} [name='output'] - The output name to get the previous texture node for.
  26315. * @return {TextureNode} The previous texture node.
  26316. */
  26317. getPreviousTextureNode( name = 'output' ) {
  26318. let textureNode = this._previousTextureNodes[ name ];
  26319. if ( textureNode === undefined ) {
  26320. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  26321. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  26322. textureNode.updateTexture();
  26323. this._previousTextureNodes[ name ] = textureNode;
  26324. }
  26325. return textureNode;
  26326. }
  26327. /**
  26328. * Returns a viewZ node of this pass.
  26329. *
  26330. * @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.
  26331. * @return {Node} The viewZ node.
  26332. */
  26333. getViewZNode( name = 'depth' ) {
  26334. let viewZNode = this._viewZNodes[ name ];
  26335. if ( viewZNode === undefined ) {
  26336. const cameraNear = this._cameraNear;
  26337. const cameraFar = this._cameraFar;
  26338. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  26339. }
  26340. return viewZNode;
  26341. }
  26342. /**
  26343. * Returns a linear depth node of this pass.
  26344. *
  26345. * @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.
  26346. * @return {Node} The linear depth node.
  26347. */
  26348. getLinearDepthNode( name = 'depth' ) {
  26349. let linearDepthNode = this._linearDepthNodes[ name ];
  26350. if ( linearDepthNode === undefined ) {
  26351. const cameraNear = this._cameraNear;
  26352. const cameraFar = this._cameraFar;
  26353. const viewZNode = this.getViewZNode( name );
  26354. // TODO: just if ( builder.camera.isPerspectiveCamera )
  26355. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  26356. }
  26357. return linearDepthNode;
  26358. }
  26359. /**
  26360. * Precompiles the pass.
  26361. *
  26362. * Note that this method must be called after the pass configuration is complete.
  26363. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  26364. *
  26365. * @async
  26366. * @param {Renderer} renderer - The renderer.
  26367. * @return {Promise} A Promise that resolves when the compile has been finished.
  26368. * @see {@link Renderer#compileAsync}
  26369. */
  26370. async compileAsync( renderer ) {
  26371. const currentRenderTarget = renderer.getRenderTarget();
  26372. const currentMRT = renderer.getMRT();
  26373. renderer.setRenderTarget( this.renderTarget );
  26374. renderer.setMRT( this._mrt );
  26375. await renderer.compileAsync( this.scene, this.camera );
  26376. renderer.setRenderTarget( currentRenderTarget );
  26377. renderer.setMRT( currentMRT );
  26378. }
  26379. setup( { renderer } ) {
  26380. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  26381. this.renderTarget.texture.type = renderer.getColorBufferType();
  26382. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  26383. }
  26384. updateBefore( frame ) {
  26385. const { renderer } = frame;
  26386. const { scene } = this;
  26387. let camera;
  26388. let pixelRatio;
  26389. const outputRenderTarget = renderer.getOutputRenderTarget();
  26390. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  26391. pixelRatio = 1;
  26392. camera = renderer.xr.getCamera();
  26393. renderer.xr.updateCamera( camera );
  26394. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  26395. } else {
  26396. camera = this.camera;
  26397. pixelRatio = renderer.getPixelRatio();
  26398. renderer.getSize( _size );
  26399. }
  26400. this._pixelRatio = pixelRatio;
  26401. this.setSize( _size.width, _size.height );
  26402. const currentRenderTarget = renderer.getRenderTarget();
  26403. const currentMRT = renderer.getMRT();
  26404. const currentAutoClear = renderer.autoClear;
  26405. const currentMask = camera.layers.mask;
  26406. this._cameraNear.value = camera.near;
  26407. this._cameraFar.value = camera.far;
  26408. if ( this._layers !== null ) {
  26409. camera.layers.mask = this._layers.mask;
  26410. }
  26411. for ( const name in this._previousTextures ) {
  26412. this.toggleTexture( name );
  26413. }
  26414. renderer.setRenderTarget( this.renderTarget );
  26415. renderer.setMRT( this._mrt );
  26416. renderer.autoClear = true;
  26417. const currentSceneName = scene.name;
  26418. scene.name = this.name ? this.name : scene.name;
  26419. renderer.render( scene, camera );
  26420. scene.name = currentSceneName;
  26421. renderer.setRenderTarget( currentRenderTarget );
  26422. renderer.setMRT( currentMRT );
  26423. renderer.autoClear = currentAutoClear;
  26424. camera.layers.mask = currentMask;
  26425. }
  26426. /**
  26427. * Sets the size of the pass's render target. Honors the pixel ratio.
  26428. *
  26429. * @param {number} width - The width to set.
  26430. * @param {number} height - The height to set.
  26431. */
  26432. setSize( width, height ) {
  26433. this._width = width;
  26434. this._height = height;
  26435. const effectiveWidth = this._width * this._pixelRatio * this._resolutionScale;
  26436. const effectiveHeight = this._height * this._pixelRatio * this._resolutionScale;
  26437. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26438. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  26439. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  26440. }
  26441. /**
  26442. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  26443. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26444. * with `null` as the single argument.
  26445. *
  26446. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  26447. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  26448. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  26449. * @param {number} width - The width of the scissor box in logical pixel unit.
  26450. * @param {number} height - The height of the scissor box in logical pixel unit.
  26451. */
  26452. setScissor( x, y, width, height ) {
  26453. if ( x === null ) {
  26454. this._scissor = null;
  26455. } else {
  26456. if ( this._scissor === null ) this._scissor = new Vector4();
  26457. if ( x.isVector4 ) {
  26458. this._scissor.copy( x );
  26459. } else {
  26460. this._scissor.set( x, y, width, height );
  26461. }
  26462. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26463. }
  26464. }
  26465. /**
  26466. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  26467. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26468. * with `null` as the single argument.
  26469. *
  26470. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26471. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26472. * @param {number} width - The width of the viewport in logical pixel unit.
  26473. * @param {number} height - The height of the viewport in logical pixel unit.
  26474. */
  26475. setViewport( x, y, width, height ) {
  26476. if ( x === null ) {
  26477. this._viewport = null;
  26478. } else {
  26479. if ( this._viewport === null ) this._viewport = new Vector4();
  26480. if ( x.isVector4 ) {
  26481. this._viewport.copy( x );
  26482. } else {
  26483. this._viewport.set( x, y, width, height );
  26484. }
  26485. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26486. }
  26487. }
  26488. /**
  26489. * Sets the pixel ratio the pass's render target and updates the size.
  26490. *
  26491. * @param {number} pixelRatio - The pixel ratio to set.
  26492. */
  26493. setPixelRatio( pixelRatio ) {
  26494. this._pixelRatio = pixelRatio;
  26495. this.setSize( this._width, this._height );
  26496. }
  26497. /**
  26498. * Frees internal resources. Should be called when the node is no longer in use.
  26499. */
  26500. dispose() {
  26501. this.renderTarget.dispose();
  26502. }
  26503. }
  26504. /**
  26505. * @static
  26506. * @type {'color'}
  26507. * @default 'color'
  26508. */
  26509. PassNode.COLOR = 'color';
  26510. /**
  26511. * @static
  26512. * @type {'depth'}
  26513. * @default 'depth'
  26514. */
  26515. PassNode.DEPTH = 'depth';
  26516. /**
  26517. * TSL function for creating a pass node.
  26518. *
  26519. * @tsl
  26520. * @function
  26521. * @param {Scene} scene - A reference to the scene.
  26522. * @param {Camera} camera - A reference to the camera.
  26523. * @param {Object} options - Options for the internal render target.
  26524. * @returns {PassNode}
  26525. */
  26526. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26527. /**
  26528. * TSL function for creating a pass texture node.
  26529. *
  26530. * @tsl
  26531. * @function
  26532. * @param {PassNode} pass - The pass node.
  26533. * @param {Texture} texture - The output texture.
  26534. * @returns {PassTextureNode}
  26535. */
  26536. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26537. /**
  26538. * TSL function for creating a depth pass node.
  26539. *
  26540. * @tsl
  26541. * @function
  26542. * @param {Scene} scene - A reference to the scene.
  26543. * @param {Camera} camera - A reference to the camera.
  26544. * @param {Object} options - Options for the internal render target.
  26545. * @returns {PassNode}
  26546. */
  26547. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26548. /**
  26549. * Represents a render pass for producing a toon outline effect on compatible objects.
  26550. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26551. * will receive the outline.
  26552. *
  26553. * ```js
  26554. * const postProcessing = new PostProcessing( renderer );
  26555. *
  26556. * const scenePass = toonOutlinePass( scene, camera );
  26557. *
  26558. * postProcessing.outputNode = scenePass;
  26559. * ```
  26560. * @augments PassNode
  26561. */
  26562. class ToonOutlinePassNode extends PassNode {
  26563. static get type() {
  26564. return 'ToonOutlinePassNode';
  26565. }
  26566. /**
  26567. * Constructs a new outline pass node.
  26568. *
  26569. * @param {Scene} scene - A reference to the scene.
  26570. * @param {Camera} camera - A reference to the camera.
  26571. * @param {Node} colorNode - Defines the outline's color.
  26572. * @param {Node} thicknessNode - Defines the outline's thickness.
  26573. * @param {Node} alphaNode - Defines the outline's alpha.
  26574. */
  26575. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26576. super( PassNode.COLOR, scene, camera );
  26577. /**
  26578. * Defines the outline's color.
  26579. *
  26580. * @type {Node}
  26581. */
  26582. this.colorNode = colorNode;
  26583. /**
  26584. * Defines the outline's thickness.
  26585. *
  26586. * @type {Node}
  26587. */
  26588. this.thicknessNode = thicknessNode;
  26589. /**
  26590. * Defines the outline's alpha.
  26591. *
  26592. * @type {Node}
  26593. */
  26594. this.alphaNode = alphaNode;
  26595. /**
  26596. * An internal material cache.
  26597. *
  26598. * @private
  26599. * @type {WeakMap<Material, NodeMaterial>}
  26600. */
  26601. this._materialCache = new WeakMap();
  26602. /**
  26603. * The name of this pass.
  26604. *
  26605. * @type {string}
  26606. * @default 'Outline Pass'
  26607. */
  26608. this.name = 'Outline Pass';
  26609. }
  26610. updateBefore( frame ) {
  26611. const { renderer } = frame;
  26612. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26613. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26614. // only render outline for supported materials
  26615. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26616. if ( material.wireframe === false ) {
  26617. const outlineMaterial = this._getOutlineMaterial( material );
  26618. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26619. }
  26620. }
  26621. // default
  26622. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26623. } );
  26624. super.updateBefore( frame );
  26625. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26626. }
  26627. /**
  26628. * Creates the material used for outline rendering.
  26629. *
  26630. * @private
  26631. * @return {NodeMaterial} The outline material.
  26632. */
  26633. _createMaterial() {
  26634. const material = new NodeMaterial();
  26635. material.isMeshToonOutlineMaterial = true;
  26636. material.name = 'Toon_Outline';
  26637. material.side = BackSide;
  26638. // vertex node
  26639. const outlineNormal = normalLocal.negate();
  26640. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26641. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26642. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26643. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26644. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26645. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26646. // color node
  26647. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26648. return material;
  26649. }
  26650. /**
  26651. * For the given toon material, this method returns a corresponding
  26652. * outline material.
  26653. *
  26654. * @private
  26655. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26656. * @return {NodeMaterial} The outline material.
  26657. */
  26658. _getOutlineMaterial( originalMaterial ) {
  26659. let outlineMaterial = this._materialCache.get( originalMaterial );
  26660. if ( outlineMaterial === undefined ) {
  26661. outlineMaterial = this._createMaterial();
  26662. this._materialCache.set( originalMaterial, outlineMaterial );
  26663. }
  26664. return outlineMaterial;
  26665. }
  26666. }
  26667. /**
  26668. * TSL function for creating a toon outline pass node.
  26669. *
  26670. * @tsl
  26671. * @function
  26672. * @param {Scene} scene - A reference to the scene.
  26673. * @param {Camera} camera - A reference to the camera.
  26674. * @param {Color} color - Defines the outline's color.
  26675. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26676. * @param {number} [alpha=1] - Defines the outline's alpha.
  26677. * @returns {ToonOutlinePassNode}
  26678. */
  26679. 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 ) ) );
  26680. /**
  26681. * Linear tone mapping, exposure only.
  26682. *
  26683. * @tsl
  26684. * @function
  26685. * @param {Node<vec3>} color - The color that should be tone mapped.
  26686. * @param {Node<float>} exposure - The exposure.
  26687. * @return {Node<vec3>} The tone mapped color.
  26688. */
  26689. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26690. return color.mul( exposure ).clamp();
  26691. } ).setLayout( {
  26692. name: 'linearToneMapping',
  26693. type: 'vec3',
  26694. inputs: [
  26695. { name: 'color', type: 'vec3' },
  26696. { name: 'exposure', type: 'float' }
  26697. ]
  26698. } );
  26699. /**
  26700. * Reinhard tone mapping.
  26701. *
  26702. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26703. *
  26704. * @tsl
  26705. * @function
  26706. * @param {Node<vec3>} color - The color that should be tone mapped.
  26707. * @param {Node<float>} exposure - The exposure.
  26708. * @return {Node<vec3>} The tone mapped color.
  26709. */
  26710. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26711. color = color.mul( exposure );
  26712. return color.div( color.add( 1.0 ) ).clamp();
  26713. } ).setLayout( {
  26714. name: 'reinhardToneMapping',
  26715. type: 'vec3',
  26716. inputs: [
  26717. { name: 'color', type: 'vec3' },
  26718. { name: 'exposure', type: 'float' }
  26719. ]
  26720. } );
  26721. /**
  26722. * Cineon tone mapping.
  26723. *
  26724. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26725. *
  26726. * @tsl
  26727. * @function
  26728. * @param {Node<vec3>} color - The color that should be tone mapped.
  26729. * @param {Node<float>} exposure - The exposure.
  26730. * @return {Node<vec3>} The tone mapped color.
  26731. */
  26732. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26733. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26734. color = color.mul( exposure );
  26735. color = color.sub( 0.004 ).max( 0.0 );
  26736. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26737. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26738. return a.div( b ).pow( 2.2 );
  26739. } ).setLayout( {
  26740. name: 'cineonToneMapping',
  26741. type: 'vec3',
  26742. inputs: [
  26743. { name: 'color', type: 'vec3' },
  26744. { name: 'exposure', type: 'float' }
  26745. ]
  26746. } );
  26747. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26748. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26749. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26750. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26751. return a.div( b );
  26752. } );
  26753. /**
  26754. * ACESFilmic tone mapping.
  26755. *
  26756. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26757. *
  26758. * @tsl
  26759. * @function
  26760. * @param {Node<vec3>} color - The color that should be tone mapped.
  26761. * @param {Node<float>} exposure - The exposure.
  26762. * @return {Node<vec3>} The tone mapped color.
  26763. */
  26764. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26765. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26766. const ACESInputMat = mat3(
  26767. 0.59719, 0.35458, 0.04823,
  26768. 0.07600, 0.90834, 0.01566,
  26769. 0.02840, 0.13383, 0.83777
  26770. );
  26771. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26772. const ACESOutputMat = mat3(
  26773. 1.60475, -0.53108, -0.07367,
  26774. -0.10208, 1.10813, -605e-5,
  26775. -327e-5, -0.07276, 1.07602
  26776. );
  26777. color = color.mul( exposure ).div( 0.6 );
  26778. color = ACESInputMat.mul( color );
  26779. // Apply RRT and ODT
  26780. color = RRTAndODTFit( color );
  26781. color = ACESOutputMat.mul( color );
  26782. // Clamp to [0, 1]
  26783. return color.clamp();
  26784. } ).setLayout( {
  26785. name: 'acesFilmicToneMapping',
  26786. type: 'vec3',
  26787. inputs: [
  26788. { name: 'color', type: 'vec3' },
  26789. { name: 'exposure', type: 'float' }
  26790. ]
  26791. } );
  26792. 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 ) );
  26793. 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 ) );
  26794. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26795. const x = vec3( x_immutable ).toVar();
  26796. const x2 = vec3( x.mul( x ) ).toVar();
  26797. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26798. 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 ) ) ) );
  26799. } );
  26800. /**
  26801. * AgX tone mapping.
  26802. *
  26803. * @tsl
  26804. * @function
  26805. * @param {Node<vec3>} color - The color that should be tone mapped.
  26806. * @param {Node<float>} exposure - The exposure.
  26807. * @return {Node<vec3>} The tone mapped color.
  26808. */
  26809. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26810. const colortone = vec3( color ).toVar();
  26811. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26812. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26813. const AgxMinEv = float( -12.47393 );
  26814. const AgxMaxEv = float( 4.026069 );
  26815. colortone.mulAssign( exposure );
  26816. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26817. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26818. colortone.assign( max$1( colortone, 1e-10 ) );
  26819. colortone.assign( log2( colortone ) );
  26820. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26821. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26822. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26823. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26824. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26825. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26826. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26827. return colortone;
  26828. } ).setLayout( {
  26829. name: 'agxToneMapping',
  26830. type: 'vec3',
  26831. inputs: [
  26832. { name: 'color', type: 'vec3' },
  26833. { name: 'exposure', type: 'float' }
  26834. ]
  26835. } );
  26836. /**
  26837. * Neutral tone mapping.
  26838. *
  26839. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26840. *
  26841. * @tsl
  26842. * @function
  26843. * @param {Node<vec3>} color - The color that should be tone mapped.
  26844. * @param {Node<float>} exposure - The exposure.
  26845. * @return {Node<vec3>} The tone mapped color.
  26846. */
  26847. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26848. const StartCompression = float( 0.8 - 0.04 );
  26849. const Desaturation = float( 0.15 );
  26850. color = color.mul( exposure );
  26851. const x = min$1( color.r, min$1( color.g, color.b ) );
  26852. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26853. color.subAssign( offset );
  26854. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26855. If( peak.lessThan( StartCompression ), () => {
  26856. return color;
  26857. } );
  26858. const d = sub( 1, StartCompression );
  26859. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26860. color.mulAssign( newPeak.div( peak ) );
  26861. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26862. return mix( color, vec3( newPeak ), g );
  26863. } ).setLayout( {
  26864. name: 'neutralToneMapping',
  26865. type: 'vec3',
  26866. inputs: [
  26867. { name: 'color', type: 'vec3' },
  26868. { name: 'exposure', type: 'float' }
  26869. ]
  26870. } );
  26871. /**
  26872. * This class represents native code sections. It is the base
  26873. * class for modules like {@link FunctionNode} which allows to implement
  26874. * functions with native shader languages.
  26875. *
  26876. * @augments Node
  26877. */
  26878. class CodeNode extends Node {
  26879. static get type() {
  26880. return 'CodeNode';
  26881. }
  26882. /**
  26883. * Constructs a new code node.
  26884. *
  26885. * @param {string} [code=''] - The native code.
  26886. * @param {Array<Node>} [includes=[]] - An array of includes.
  26887. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26888. */
  26889. constructor( code = '', includes = [], language = '' ) {
  26890. super( 'code' );
  26891. /**
  26892. * This flag can be used for type testing.
  26893. *
  26894. * @type {boolean}
  26895. * @readonly
  26896. * @default true
  26897. */
  26898. this.isCodeNode = true;
  26899. /**
  26900. * This flag is used for global cache.
  26901. *
  26902. * @type {boolean}
  26903. * @default true
  26904. */
  26905. this.global = true;
  26906. /**
  26907. * The native code.
  26908. *
  26909. * @type {string}
  26910. * @default ''
  26911. */
  26912. this.code = code;
  26913. /**
  26914. * An array of includes
  26915. *
  26916. * @type {Array<Node>}
  26917. * @default []
  26918. */
  26919. this.includes = includes;
  26920. /**
  26921. * The used language.
  26922. *
  26923. * @type {('js'|'wgsl'|'glsl')}
  26924. * @default ''
  26925. */
  26926. this.language = language;
  26927. }
  26928. /**
  26929. * Sets the includes of this code node.
  26930. *
  26931. * @param {Array<Node>} includes - The includes to set.
  26932. * @return {CodeNode} A reference to this node.
  26933. */
  26934. setIncludes( includes ) {
  26935. this.includes = includes;
  26936. return this;
  26937. }
  26938. /**
  26939. * Returns the includes of this code node.
  26940. *
  26941. * @param {NodeBuilder} builder - The current node builder.
  26942. * @return {Array<Node>} The includes.
  26943. */
  26944. getIncludes( /*builder*/ ) {
  26945. return this.includes;
  26946. }
  26947. generate( builder ) {
  26948. const includes = this.getIncludes( builder );
  26949. for ( const include of includes ) {
  26950. include.build( builder );
  26951. }
  26952. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26953. nodeCode.code = this.code;
  26954. return nodeCode.code;
  26955. }
  26956. serialize( data ) {
  26957. super.serialize( data );
  26958. data.code = this.code;
  26959. data.language = this.language;
  26960. }
  26961. deserialize( data ) {
  26962. super.deserialize( data );
  26963. this.code = data.code;
  26964. this.language = data.language;
  26965. }
  26966. }
  26967. /**
  26968. * TSL function for creating a code node.
  26969. *
  26970. * @tsl
  26971. * @function
  26972. * @param {string} [code] - The native code.
  26973. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26974. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26975. * @returns {CodeNode}
  26976. */
  26977. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26978. /**
  26979. * TSL function for creating a JS code node.
  26980. *
  26981. * @tsl
  26982. * @function
  26983. * @param {string} src - The native code.
  26984. * @param {Array<Node>} includes - An array of includes.
  26985. * @returns {CodeNode}
  26986. */
  26987. const js = ( src, includes ) => code( src, includes, 'js' );
  26988. /**
  26989. * TSL function for creating a WGSL code node.
  26990. *
  26991. * @tsl
  26992. * @function
  26993. * @param {string} src - The native code.
  26994. * @param {Array<Node>} includes - An array of includes.
  26995. * @returns {CodeNode}
  26996. */
  26997. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26998. /**
  26999. * TSL function for creating a GLSL code node.
  27000. *
  27001. * @tsl
  27002. * @function
  27003. * @param {string} src - The native code.
  27004. * @param {Array<Node>} includes - An array of includes.
  27005. * @returns {CodeNode}
  27006. */
  27007. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  27008. /**
  27009. * This class represents a native shader function. It can be used to implement
  27010. * certain aspects of a node material with native shader code. There are two predefined
  27011. * TSL functions for easier usage.
  27012. *
  27013. * - `wgslFn`: Creates a WGSL function node.
  27014. * - `glslFn`: Creates a GLSL function node.
  27015. *
  27016. * A basic example with one include looks like so:
  27017. *
  27018. * ```js
  27019. * const desaturateWGSLFn = wgslFn( `
  27020. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  27021. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  27022. * return vec3<f32>( dot( lum, color ) );
  27023. * }`
  27024. *);
  27025. * const someWGSLFn = wgslFn( `
  27026. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  27027. * return desaturate( color );
  27028. * }
  27029. * `, [ desaturateWGSLFn ] );
  27030. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  27031. *```
  27032. * @augments CodeNode
  27033. */
  27034. class FunctionNode extends CodeNode {
  27035. static get type() {
  27036. return 'FunctionNode';
  27037. }
  27038. /**
  27039. * Constructs a new function node.
  27040. *
  27041. * @param {string} [code=''] - The native code.
  27042. * @param {Array<Node>} [includes=[]] - An array of includes.
  27043. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27044. */
  27045. constructor( code = '', includes = [], language = '' ) {
  27046. super( code, includes, language );
  27047. }
  27048. /**
  27049. * Returns the type of this function node.
  27050. *
  27051. * @param {NodeBuilder} builder - The current node builder.
  27052. * @return {string} The type.
  27053. */
  27054. getNodeType( builder ) {
  27055. return this.getNodeFunction( builder ).type;
  27056. }
  27057. /**
  27058. * Returns the type of a member of this function node.
  27059. *
  27060. * @param {NodeBuilder} builder - The current node builder.
  27061. * @param {string} name - The name of the member.
  27062. * @return {string} The type of the member.
  27063. */
  27064. getMemberType( builder, name ) {
  27065. const type = this.getNodeType( builder );
  27066. const structType = builder.getStructTypeNode( type );
  27067. return structType.getMemberType( builder, name );
  27068. }
  27069. /**
  27070. * Returns the inputs of this function node.
  27071. *
  27072. * @param {NodeBuilder} builder - The current node builder.
  27073. * @return {Array<NodeFunctionInput>} The inputs.
  27074. */
  27075. getInputs( builder ) {
  27076. return this.getNodeFunction( builder ).inputs;
  27077. }
  27078. /**
  27079. * Returns the node function for this function node.
  27080. *
  27081. * @param {NodeBuilder} builder - The current node builder.
  27082. * @return {NodeFunction} The node function.
  27083. */
  27084. getNodeFunction( builder ) {
  27085. const nodeData = builder.getDataFromNode( this );
  27086. let nodeFunction = nodeData.nodeFunction;
  27087. if ( nodeFunction === undefined ) {
  27088. nodeFunction = builder.parser.parseFunction( this.code );
  27089. nodeData.nodeFunction = nodeFunction;
  27090. }
  27091. return nodeFunction;
  27092. }
  27093. generate( builder, output ) {
  27094. super.generate( builder );
  27095. const nodeFunction = this.getNodeFunction( builder );
  27096. const name = nodeFunction.name;
  27097. const type = nodeFunction.type;
  27098. const nodeCode = builder.getCodeFromNode( this, type );
  27099. if ( name !== '' ) {
  27100. // use a custom property name
  27101. nodeCode.name = name;
  27102. }
  27103. const propertyName = builder.getPropertyName( nodeCode );
  27104. const code = this.getNodeFunction( builder ).getCode( propertyName );
  27105. nodeCode.code = code + '\n';
  27106. if ( output === 'property' ) {
  27107. return propertyName;
  27108. } else {
  27109. return builder.format( `${ propertyName }()`, type, output );
  27110. }
  27111. }
  27112. }
  27113. const nativeFn = ( code, includes = [], language = '' ) => {
  27114. for ( let i = 0; i < includes.length; i ++ ) {
  27115. const include = includes[ i ];
  27116. // TSL Function: glslFn, wgslFn
  27117. if ( typeof include === 'function' ) {
  27118. includes[ i ] = include.functionNode;
  27119. }
  27120. }
  27121. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  27122. const fn = ( ...params ) => functionNode.call( ...params );
  27123. fn.functionNode = functionNode;
  27124. return fn;
  27125. };
  27126. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  27127. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  27128. /**
  27129. * `ScriptableNode` uses this class to manage script inputs and outputs.
  27130. *
  27131. * @augments Node
  27132. */
  27133. class ScriptableValueNode extends Node {
  27134. static get type() {
  27135. return 'ScriptableValueNode';
  27136. }
  27137. /**
  27138. * Constructs a new scriptable node.
  27139. *
  27140. * @param {any} [value=null] - The value.
  27141. */
  27142. constructor( value = null ) {
  27143. super();
  27144. /**
  27145. * A reference to the value.
  27146. *
  27147. * @private
  27148. * @default null
  27149. */
  27150. this._value = value;
  27151. /**
  27152. * Depending on the type of `_value`, this property might cache parsed data.
  27153. *
  27154. * @private
  27155. * @default null
  27156. */
  27157. this._cache = null;
  27158. /**
  27159. * If this node represents an input, this property represents the input type.
  27160. *
  27161. * @type {?string}
  27162. * @default null
  27163. */
  27164. this.inputType = null;
  27165. /**
  27166. * If this node represents an output, this property represents the output type.
  27167. *
  27168. * @type {?string}
  27169. * @default null
  27170. */
  27171. this.outputType = null;
  27172. /**
  27173. * An event dispatcher for managing events.
  27174. *
  27175. * @type {EventDispatcher}
  27176. */
  27177. this.events = new EventDispatcher();
  27178. /**
  27179. * This flag can be used for type testing.
  27180. *
  27181. * @type {boolean}
  27182. * @readonly
  27183. * @default true
  27184. */
  27185. this.isScriptableValueNode = true;
  27186. }
  27187. /**
  27188. * Whether this node represents an output or not.
  27189. *
  27190. * @type {boolean}
  27191. * @readonly
  27192. * @default true
  27193. */
  27194. get isScriptableOutputNode() {
  27195. return this.outputType !== null;
  27196. }
  27197. set value( val ) {
  27198. if ( this._value === val ) return;
  27199. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  27200. URL.revokeObjectURL( this._cache );
  27201. this._cache = null;
  27202. }
  27203. this._value = val;
  27204. this.events.dispatchEvent( { type: 'change' } );
  27205. this.refresh();
  27206. }
  27207. /**
  27208. * The node's value.
  27209. *
  27210. * @type {any}
  27211. */
  27212. get value() {
  27213. return this._value;
  27214. }
  27215. /**
  27216. * Dispatches the `refresh` event.
  27217. */
  27218. refresh() {
  27219. this.events.dispatchEvent( { type: 'refresh' } );
  27220. }
  27221. /**
  27222. * The `value` property usually represents a node or even binary data in form of array buffers.
  27223. * In this case, this method tries to return the actual value behind the complex type.
  27224. *
  27225. * @return {any} The value.
  27226. */
  27227. getValue() {
  27228. const value = this.value;
  27229. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  27230. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  27231. } else if ( value && value.value !== null && value.value !== undefined && (
  27232. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  27233. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  27234. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  27235. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  27236. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  27237. ( this.inputType === 'Color' && value.value.isColor ) ||
  27238. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  27239. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  27240. ) ) {
  27241. return value.value;
  27242. }
  27243. return this._cache || value;
  27244. }
  27245. /**
  27246. * Overwritten since the node type is inferred from the value.
  27247. *
  27248. * @param {NodeBuilder} builder - The current node builder.
  27249. * @return {string} The node type.
  27250. */
  27251. getNodeType( builder ) {
  27252. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  27253. }
  27254. setup() {
  27255. return this.value && this.value.isNode ? this.value : float();
  27256. }
  27257. serialize( data ) {
  27258. super.serialize( data );
  27259. if ( this.value !== null ) {
  27260. if ( this.inputType === 'ArrayBuffer' ) {
  27261. data.value = arrayBufferToBase64( this.value );
  27262. } else {
  27263. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  27264. }
  27265. } else {
  27266. data.value = null;
  27267. }
  27268. data.inputType = this.inputType;
  27269. data.outputType = this.outputType;
  27270. }
  27271. deserialize( data ) {
  27272. super.deserialize( data );
  27273. let value = null;
  27274. if ( data.value !== null ) {
  27275. if ( data.inputType === 'ArrayBuffer' ) {
  27276. value = base64ToArrayBuffer( data.value );
  27277. } else if ( data.inputType === 'Texture' ) {
  27278. value = data.meta.textures[ data.value ];
  27279. } else {
  27280. value = data.meta.nodes[ data.value ] || null;
  27281. }
  27282. }
  27283. this.value = value;
  27284. this.inputType = data.inputType;
  27285. this.outputType = data.outputType;
  27286. }
  27287. }
  27288. /**
  27289. * TSL function for creating a scriptable value node.
  27290. *
  27291. * @tsl
  27292. * @function
  27293. * @param {any} [value] - The value.
  27294. * @returns {ScriptableValueNode}
  27295. */
  27296. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  27297. /**
  27298. * A Map-like data structure for managing resources of scriptable nodes.
  27299. *
  27300. * @augments Map
  27301. */
  27302. class Resources extends Map {
  27303. get( key, callback = null, ...params ) {
  27304. if ( this.has( key ) ) return super.get( key );
  27305. if ( callback !== null ) {
  27306. const value = callback( ...params );
  27307. this.set( key, value );
  27308. return value;
  27309. }
  27310. }
  27311. }
  27312. class Parameters {
  27313. constructor( scriptableNode ) {
  27314. this.scriptableNode = scriptableNode;
  27315. }
  27316. get parameters() {
  27317. return this.scriptableNode.parameters;
  27318. }
  27319. get layout() {
  27320. return this.scriptableNode.getLayout();
  27321. }
  27322. getInputLayout( id ) {
  27323. return this.scriptableNode.getInputLayout( id );
  27324. }
  27325. get( name ) {
  27326. const param = this.parameters[ name ];
  27327. const value = param ? param.getValue() : null;
  27328. return value;
  27329. }
  27330. }
  27331. /**
  27332. * Defines the resources (e.g. namespaces) of scriptable nodes.
  27333. *
  27334. * @type {Resources}
  27335. */
  27336. const ScriptableNodeResources = new Resources();
  27337. /**
  27338. * This type of node allows to implement nodes with custom scripts. The script
  27339. * section is represented as an instance of `CodeNode` written with JavaScript.
  27340. * The script itself must adhere to a specific structure.
  27341. *
  27342. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  27343. * - layout: The layout object defines the script's interface (inputs and outputs).
  27344. *
  27345. * ```js
  27346. * ScriptableNodeResources.set( 'TSL', TSL );
  27347. *
  27348. * const scriptableNode = scriptable( js( `
  27349. * layout = {
  27350. * outputType: 'node',
  27351. * elements: [
  27352. * { name: 'source', inputType: 'node' },
  27353. * ]
  27354. * };
  27355. *
  27356. * const { mul, oscSine } = TSL;
  27357. *
  27358. * function main() {
  27359. * const source = parameters.get( 'source' ) || float();
  27360. * return mul( source, oscSine() ) );
  27361. * }
  27362. *
  27363. * ` ) );
  27364. *
  27365. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  27366. *
  27367. * const material = new THREE.MeshBasicNodeMaterial();
  27368. * material.colorNode = scriptableNode;
  27369. * ```
  27370. *
  27371. * @augments Node
  27372. */
  27373. class ScriptableNode extends Node {
  27374. static get type() {
  27375. return 'ScriptableNode';
  27376. }
  27377. /**
  27378. * Constructs a new scriptable node.
  27379. *
  27380. * @param {?CodeNode} [codeNode=null] - The code node.
  27381. * @param {Object} [parameters={}] - The parameters definition.
  27382. */
  27383. constructor( codeNode = null, parameters = {} ) {
  27384. super();
  27385. /**
  27386. * The code node.
  27387. *
  27388. * @type {?CodeNode}
  27389. * @default null
  27390. */
  27391. this.codeNode = codeNode;
  27392. /**
  27393. * The parameters definition.
  27394. *
  27395. * @type {Object}
  27396. * @default {}
  27397. */
  27398. this.parameters = parameters;
  27399. this._local = new Resources();
  27400. this._output = scriptableValue( null );
  27401. this._outputs = {};
  27402. this._source = this.source;
  27403. this._method = null;
  27404. this._object = null;
  27405. this._value = null;
  27406. this._needsOutputUpdate = true;
  27407. this.onRefresh = this.onRefresh.bind( this );
  27408. /**
  27409. * This flag can be used for type testing.
  27410. *
  27411. * @type {boolean}
  27412. * @readonly
  27413. * @default true
  27414. */
  27415. this.isScriptableNode = true;
  27416. }
  27417. /**
  27418. * The source code of the scriptable node.
  27419. *
  27420. * @type {string}
  27421. */
  27422. get source() {
  27423. return this.codeNode ? this.codeNode.code : '';
  27424. }
  27425. /**
  27426. * Sets the reference of a local script variable.
  27427. *
  27428. * @param {string} name - The variable name.
  27429. * @param {Object} value - The reference to set.
  27430. * @return {Resources} The resource map
  27431. */
  27432. setLocal( name, value ) {
  27433. return this._local.set( name, value );
  27434. }
  27435. /**
  27436. * Gets the value of a local script variable.
  27437. *
  27438. * @param {string} name - The variable name.
  27439. * @return {Object} The value.
  27440. */
  27441. getLocal( name ) {
  27442. return this._local.get( name );
  27443. }
  27444. /**
  27445. * Event listener for the `refresh` event.
  27446. */
  27447. onRefresh() {
  27448. this._refresh();
  27449. }
  27450. /**
  27451. * Returns an input from the layout with the given id/name.
  27452. *
  27453. * @param {string} id - The id/name of the input.
  27454. * @return {Object} The element entry.
  27455. */
  27456. getInputLayout( id ) {
  27457. for ( const element of this.getLayout() ) {
  27458. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  27459. return element;
  27460. }
  27461. }
  27462. }
  27463. /**
  27464. * Returns an output from the layout with the given id/name.
  27465. *
  27466. * @param {string} id - The id/name of the output.
  27467. * @return {Object} The element entry.
  27468. */
  27469. getOutputLayout( id ) {
  27470. for ( const element of this.getLayout() ) {
  27471. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  27472. return element;
  27473. }
  27474. }
  27475. }
  27476. /**
  27477. * Defines a script output for the given name and value.
  27478. *
  27479. * @param {string} name - The name of the output.
  27480. * @param {Node} value - The node value.
  27481. * @return {ScriptableNode} A reference to this node.
  27482. */
  27483. setOutput( name, value ) {
  27484. const outputs = this._outputs;
  27485. if ( outputs[ name ] === undefined ) {
  27486. outputs[ name ] = scriptableValue( value );
  27487. } else {
  27488. outputs[ name ].value = value;
  27489. }
  27490. return this;
  27491. }
  27492. /**
  27493. * Returns a script output for the given name.
  27494. *
  27495. * @param {string} name - The name of the output.
  27496. * @return {ScriptableValueNode} The node value.
  27497. */
  27498. getOutput( name ) {
  27499. return this._outputs[ name ];
  27500. }
  27501. /**
  27502. * Returns a parameter for the given name
  27503. *
  27504. * @param {string} name - The name of the parameter.
  27505. * @return {ScriptableValueNode} The node value.
  27506. */
  27507. getParameter( name ) {
  27508. return this.parameters[ name ];
  27509. }
  27510. /**
  27511. * Sets a value for the given parameter name.
  27512. *
  27513. * @param {string} name - The parameter name.
  27514. * @param {any} value - The parameter value.
  27515. * @return {ScriptableNode} A reference to this node.
  27516. */
  27517. setParameter( name, value ) {
  27518. const parameters = this.parameters;
  27519. if ( value && value.isScriptableNode ) {
  27520. this.deleteParameter( name );
  27521. parameters[ name ] = value;
  27522. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27523. } else if ( value && value.isScriptableValueNode ) {
  27524. this.deleteParameter( name );
  27525. parameters[ name ] = value;
  27526. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27527. } else if ( parameters[ name ] === undefined ) {
  27528. parameters[ name ] = scriptableValue( value );
  27529. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27530. } else {
  27531. parameters[ name ].value = value;
  27532. }
  27533. return this;
  27534. }
  27535. /**
  27536. * Returns the value of this node which is the value of
  27537. * the default output.
  27538. *
  27539. * @return {Node} The value.
  27540. */
  27541. getValue() {
  27542. return this.getDefaultOutput().getValue();
  27543. }
  27544. /**
  27545. * Deletes a parameter from the script.
  27546. *
  27547. * @param {string} name - The parameter to remove.
  27548. * @return {ScriptableNode} A reference to this node.
  27549. */
  27550. deleteParameter( name ) {
  27551. let valueNode = this.parameters[ name ];
  27552. if ( valueNode ) {
  27553. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27554. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27555. }
  27556. return this;
  27557. }
  27558. /**
  27559. * Deletes all parameters from the script.
  27560. *
  27561. * @return {ScriptableNode} A reference to this node.
  27562. */
  27563. clearParameters() {
  27564. for ( const name of Object.keys( this.parameters ) ) {
  27565. this.deleteParameter( name );
  27566. }
  27567. this.needsUpdate = true;
  27568. return this;
  27569. }
  27570. /**
  27571. * Calls a function from the script.
  27572. *
  27573. * @param {string} name - The function name.
  27574. * @param {...any} params - A list of parameters.
  27575. * @return {any} The result of the function call.
  27576. */
  27577. call( name, ...params ) {
  27578. const object = this.getObject();
  27579. const method = object[ name ];
  27580. if ( typeof method === 'function' ) {
  27581. return method( ...params );
  27582. }
  27583. }
  27584. /**
  27585. * Asynchronously calls a function from the script.
  27586. *
  27587. * @param {string} name - The function name.
  27588. * @param {...any} params - A list of parameters.
  27589. * @return {Promise<any>} The result of the function call.
  27590. */
  27591. async callAsync( name, ...params ) {
  27592. const object = this.getObject();
  27593. const method = object[ name ];
  27594. if ( typeof method === 'function' ) {
  27595. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27596. }
  27597. }
  27598. /**
  27599. * Overwritten since the node types is inferred from the script's output.
  27600. *
  27601. * @param {NodeBuilder} builder - The current node builder
  27602. * @return {string} The node type.
  27603. */
  27604. getNodeType( builder ) {
  27605. return this.getDefaultOutputNode().getNodeType( builder );
  27606. }
  27607. /**
  27608. * Refreshes the script node.
  27609. *
  27610. * @param {?string} [output=null] - An optional output.
  27611. */
  27612. refresh( output = null ) {
  27613. if ( output !== null ) {
  27614. this.getOutput( output ).refresh();
  27615. } else {
  27616. this._refresh();
  27617. }
  27618. }
  27619. /**
  27620. * Returns an object representation of the script.
  27621. *
  27622. * @return {Object} The result object.
  27623. */
  27624. getObject() {
  27625. if ( this.needsUpdate ) this.dispose();
  27626. if ( this._object !== null ) return this._object;
  27627. //
  27628. const refresh = () => this.refresh();
  27629. const setOutput = ( id, value ) => this.setOutput( id, value );
  27630. const parameters = new Parameters( this );
  27631. const THREE = ScriptableNodeResources.get( 'THREE' );
  27632. const TSL = ScriptableNodeResources.get( 'TSL' );
  27633. const method = this.getMethod();
  27634. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27635. this._object = method( ...params );
  27636. const layout = this._object.layout;
  27637. if ( layout ) {
  27638. if ( layout.cache === false ) {
  27639. this._local.clear();
  27640. }
  27641. // default output
  27642. this._output.outputType = layout.outputType || null;
  27643. if ( Array.isArray( layout.elements ) ) {
  27644. for ( const element of layout.elements ) {
  27645. const id = element.id || element.name;
  27646. if ( element.inputType ) {
  27647. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27648. this.getParameter( id ).inputType = element.inputType;
  27649. }
  27650. if ( element.outputType ) {
  27651. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27652. this.getOutput( id ).outputType = element.outputType;
  27653. }
  27654. }
  27655. }
  27656. }
  27657. return this._object;
  27658. }
  27659. deserialize( data ) {
  27660. super.deserialize( data );
  27661. for ( const name in this.parameters ) {
  27662. let valueNode = this.parameters[ name ];
  27663. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27664. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27665. }
  27666. }
  27667. /**
  27668. * Returns the layout of the script.
  27669. *
  27670. * @return {Object} The script's layout.
  27671. */
  27672. getLayout() {
  27673. return this.getObject().layout;
  27674. }
  27675. /**
  27676. * Returns default node output of the script.
  27677. *
  27678. * @return {Node} The default node output.
  27679. */
  27680. getDefaultOutputNode() {
  27681. const output = this.getDefaultOutput().value;
  27682. if ( output && output.isNode ) {
  27683. return output;
  27684. }
  27685. return float();
  27686. }
  27687. /**
  27688. * Returns default output of the script.
  27689. *
  27690. * @return {ScriptableValueNode} The default output.
  27691. */
  27692. getDefaultOutput() {
  27693. return this._exec()._output;
  27694. }
  27695. /**
  27696. * Returns a function created from the node's script.
  27697. *
  27698. * @return {Function} The function representing the node's code.
  27699. */
  27700. getMethod() {
  27701. if ( this.needsUpdate ) this.dispose();
  27702. if ( this._method !== null ) return this._method;
  27703. //
  27704. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27705. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27706. const properties = interfaceProps.join( ', ' );
  27707. const declarations = 'var ' + properties + '; var output = {};\n';
  27708. const returns = '\nreturn { ...output, ' + properties + ' };';
  27709. const code = declarations + this.codeNode.code + returns;
  27710. //
  27711. this._method = new Function( ...parametersProps, code );
  27712. return this._method;
  27713. }
  27714. /**
  27715. * Frees all internal resources.
  27716. */
  27717. dispose() {
  27718. if ( this._method === null ) return;
  27719. if ( this._object && typeof this._object.dispose === 'function' ) {
  27720. this._object.dispose();
  27721. }
  27722. this._method = null;
  27723. this._object = null;
  27724. this._source = null;
  27725. this._value = null;
  27726. this._needsOutputUpdate = true;
  27727. this._output.value = null;
  27728. this._outputs = {};
  27729. }
  27730. setup() {
  27731. return this.getDefaultOutputNode();
  27732. }
  27733. getCacheKey( force ) {
  27734. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27735. for ( const param in this.parameters ) {
  27736. values.push( this.parameters[ param ].getCacheKey( force ) );
  27737. }
  27738. return hashArray( values );
  27739. }
  27740. set needsUpdate( value ) {
  27741. if ( value === true ) this.dispose();
  27742. }
  27743. get needsUpdate() {
  27744. return this.source !== this._source;
  27745. }
  27746. /**
  27747. * Executes the `main` function of the script.
  27748. *
  27749. * @private
  27750. * @return {ScriptableNode} A reference to this node.
  27751. */
  27752. _exec() {
  27753. if ( this.codeNode === null ) return this;
  27754. if ( this._needsOutputUpdate === true ) {
  27755. this._value = this.call( 'main' );
  27756. this._needsOutputUpdate = false;
  27757. }
  27758. this._output.value = this._value;
  27759. return this;
  27760. }
  27761. /**
  27762. * Executes the refresh.
  27763. *
  27764. * @private
  27765. */
  27766. _refresh() {
  27767. this.needsUpdate = true;
  27768. this._exec();
  27769. this._output.refresh();
  27770. }
  27771. }
  27772. /**
  27773. * TSL function for creating a scriptable node.
  27774. *
  27775. * @tsl
  27776. * @function
  27777. * @param {CodeNode} [codeNode] - The code node.
  27778. * @param {?Object} [parameters={}] - The parameters definition.
  27779. * @returns {ScriptableNode}
  27780. */
  27781. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27782. /**
  27783. * Returns a node that represents the `z` coordinate in view space
  27784. * for the current fragment. It's a different representation of the
  27785. * default depth value.
  27786. *
  27787. * This value can be part of a computation that defines how the fog
  27788. * density increases when moving away from the camera.
  27789. *
  27790. * @param {NodeBuilder} builder - The current node builder.
  27791. * @return {Node} The viewZ node.
  27792. */
  27793. function getViewZNode( builder ) {
  27794. let viewZ;
  27795. const getViewZ = builder.context.getViewZ;
  27796. if ( getViewZ !== undefined ) {
  27797. viewZ = getViewZ( this );
  27798. }
  27799. return ( viewZ || positionView.z ).negate();
  27800. }
  27801. /**
  27802. * Constructs a new range factor node.
  27803. *
  27804. * @tsl
  27805. * @function
  27806. * @param {Node} near - Defines the near value.
  27807. * @param {Node} far - Defines the far value.
  27808. */
  27809. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27810. const viewZ = getViewZNode( builder );
  27811. return smoothstep( near, far, viewZ );
  27812. } );
  27813. /**
  27814. * Represents an exponential squared fog. This type of fog gives
  27815. * a clear view near the camera and a faster than exponentially
  27816. * densening fog farther from the camera.
  27817. *
  27818. * @tsl
  27819. * @function
  27820. * @param {Node} density - Defines the fog density.
  27821. */
  27822. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27823. const viewZ = getViewZNode( builder );
  27824. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27825. } );
  27826. /**
  27827. * This class can be used to configure a fog for the scene.
  27828. * Nodes of this type are assigned to `Scene.fogNode`.
  27829. *
  27830. * @tsl
  27831. * @function
  27832. * @param {Node} color - Defines the color of the fog.
  27833. * @param {Node} factor - Defines how the fog is factored in the scene.
  27834. */
  27835. const fog = Fn( ( [ color, factor ] ) => {
  27836. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27837. } );
  27838. // Deprecated
  27839. /**
  27840. * @tsl
  27841. * @function
  27842. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27843. *
  27844. * @param {Node} color
  27845. * @param {Node} near
  27846. * @param {Node} far
  27847. * @returns {Function}
  27848. */
  27849. function rangeFog( color, near, far ) { // @deprecated, r171
  27850. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27851. return fog( color, rangeFogFactor( near, far ) );
  27852. }
  27853. /**
  27854. * @tsl
  27855. * @function
  27856. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27857. *
  27858. * @param {Node} color
  27859. * @param {Node} density
  27860. * @returns {Function}
  27861. */
  27862. function densityFog( color, density ) { // @deprecated, r171
  27863. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27864. return fog( color, densityFogFactor( density ) );
  27865. }
  27866. let min = null;
  27867. let max = null;
  27868. /**
  27869. * `RangeNode` generates random instanced attribute data in a defined range.
  27870. * An exemplary use case for this utility node is to generate random per-instance
  27871. * colors:
  27872. * ```js
  27873. * const material = new MeshBasicNodeMaterial();
  27874. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27875. * const mesh = new InstancedMesh( geometry, material, count );
  27876. * ```
  27877. * @augments Node
  27878. */
  27879. class RangeNode extends Node {
  27880. static get type() {
  27881. return 'RangeNode';
  27882. }
  27883. /**
  27884. * Constructs a new range node.
  27885. *
  27886. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27887. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27888. */
  27889. constructor( minNode = float(), maxNode = float() ) {
  27890. super();
  27891. /**
  27892. * A node defining the lower bound of the range.
  27893. *
  27894. * @type {Node<any>}
  27895. * @default float()
  27896. */
  27897. this.minNode = minNode;
  27898. /**
  27899. * A node defining the upper bound of the range.
  27900. *
  27901. * @type {Node<any>}
  27902. * @default float()
  27903. */
  27904. this.maxNode = maxNode;
  27905. }
  27906. /**
  27907. * Returns the vector length which is computed based on the range definition.
  27908. *
  27909. * @param {NodeBuilder} builder - The current node builder.
  27910. * @return {number} The vector length.
  27911. */
  27912. getVectorLength( builder ) {
  27913. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27914. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27915. return minLength > maxLength ? minLength : maxLength;
  27916. }
  27917. /**
  27918. * This method is overwritten since the node type is inferred from range definition.
  27919. *
  27920. * @param {NodeBuilder} builder - The current node builder.
  27921. * @return {string} The node type.
  27922. */
  27923. getNodeType( builder ) {
  27924. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27925. }
  27926. setup( builder ) {
  27927. const object = builder.object;
  27928. let output = null;
  27929. if ( object.count > 1 ) {
  27930. const minValue = this.minNode.value;
  27931. const maxValue = this.maxNode.value;
  27932. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27933. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27934. min = min || new Vector4();
  27935. max = max || new Vector4();
  27936. min.setScalar( 0 );
  27937. max.setScalar( 0 );
  27938. if ( minLength === 1 ) min.setScalar( minValue );
  27939. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27940. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27941. if ( maxLength === 1 ) max.setScalar( maxValue );
  27942. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27943. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27944. const stride = 4;
  27945. const length = stride * object.count;
  27946. const array = new Float32Array( length );
  27947. for ( let i = 0; i < length; i ++ ) {
  27948. const index = i % stride;
  27949. const minElementValue = min.getComponent( index );
  27950. const maxElementValue = max.getComponent( index );
  27951. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27952. }
  27953. const nodeType = this.getNodeType( builder );
  27954. if ( object.count <= 4096 ) {
  27955. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27956. } else {
  27957. // TODO: Improve anonymous buffer attribute creation removing this part
  27958. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27959. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27960. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27961. }
  27962. } else {
  27963. output = float( 0 );
  27964. }
  27965. return output;
  27966. }
  27967. }
  27968. /**
  27969. * TSL function for creating a range node.
  27970. *
  27971. * @tsl
  27972. * @function
  27973. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27974. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27975. * @returns {RangeNode}
  27976. */
  27977. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27978. /**
  27979. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27980. * about the currently running dispatch and/or the device it is running on.
  27981. *
  27982. * This node can only be used with a WebGPU backend.
  27983. *
  27984. * @augments Node
  27985. */
  27986. class ComputeBuiltinNode extends Node {
  27987. static get type() {
  27988. return 'ComputeBuiltinNode';
  27989. }
  27990. /**
  27991. * Constructs a new compute builtin node.
  27992. *
  27993. * @param {string} builtinName - The built-in name.
  27994. * @param {string} nodeType - The node type.
  27995. */
  27996. constructor( builtinName, nodeType ) {
  27997. super( nodeType );
  27998. /**
  27999. * The built-in name.
  28000. *
  28001. * @private
  28002. * @type {string}
  28003. */
  28004. this._builtinName = builtinName;
  28005. }
  28006. /**
  28007. * This method is overwritten since hash is derived from the built-in name.
  28008. *
  28009. * @param {NodeBuilder} builder - The current node builder.
  28010. * @return {string} The hash.
  28011. */
  28012. getHash( builder ) {
  28013. return this.getBuiltinName( builder );
  28014. }
  28015. /**
  28016. * This method is overwritten since the node type is simply derived from `nodeType`..
  28017. *
  28018. * @param {NodeBuilder} builder - The current node builder.
  28019. * @return {string} The node type.
  28020. */
  28021. getNodeType( /*builder*/ ) {
  28022. return this.nodeType;
  28023. }
  28024. /**
  28025. * Sets the builtin name.
  28026. *
  28027. * @param {string} builtinName - The built-in name.
  28028. * @return {ComputeBuiltinNode} A reference to this node.
  28029. */
  28030. setBuiltinName( builtinName ) {
  28031. this._builtinName = builtinName;
  28032. return this;
  28033. }
  28034. /**
  28035. * Returns the builtin name.
  28036. *
  28037. * @param {NodeBuilder} builder - The current node builder.
  28038. * @return {string} The builtin name.
  28039. */
  28040. getBuiltinName( /*builder*/ ) {
  28041. return this._builtinName;
  28042. }
  28043. /**
  28044. * Whether the current node builder has the builtin or not.
  28045. *
  28046. * @param {NodeBuilder} builder - The current node builder.
  28047. * @return {boolean} Whether the builder has the builtin or not.
  28048. */
  28049. hasBuiltin( builder ) {
  28050. return builder.hasBuiltin( this._builtinName );
  28051. }
  28052. generate( builder, output ) {
  28053. const builtinName = this.getBuiltinName( builder );
  28054. const nodeType = this.getNodeType( builder );
  28055. if ( builder.shaderStage === 'compute' ) {
  28056. return builder.format( builtinName, nodeType, output );
  28057. } else {
  28058. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  28059. return builder.generateConst( nodeType );
  28060. }
  28061. }
  28062. serialize( data ) {
  28063. super.serialize( data );
  28064. data.global = this.global;
  28065. data._builtinName = this._builtinName;
  28066. }
  28067. deserialize( data ) {
  28068. super.deserialize( data );
  28069. this.global = data.global;
  28070. this._builtinName = data._builtinName;
  28071. }
  28072. }
  28073. /**
  28074. * TSL function for creating a compute builtin node.
  28075. *
  28076. * @tsl
  28077. * @function
  28078. * @param {string} name - The built-in name.
  28079. * @param {string} nodeType - The node type.
  28080. * @returns {ComputeBuiltinNode}
  28081. */
  28082. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  28083. /**
  28084. * Represents the number of workgroups dispatched by the compute shader.
  28085. * ```js
  28086. * // Run 512 invocations/threads with a workgroup size of 128.
  28087. * const computeFn = Fn(() => {
  28088. *
  28089. * // numWorkgroups.x = 4
  28090. * storageBuffer.element(0).assign(numWorkgroups.x)
  28091. *
  28092. * })().compute(512, [128]);
  28093. *
  28094. * // Run 512 invocations/threads with the default workgroup size of 64.
  28095. * const computeFn = Fn(() => {
  28096. *
  28097. * // numWorkgroups.x = 8
  28098. * storageBuffer.element(0).assign(numWorkgroups.x)
  28099. *
  28100. * })().compute(512);
  28101. * ```
  28102. *
  28103. * @tsl
  28104. * @type {ComputeBuiltinNode<uvec3>}
  28105. */
  28106. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  28107. /**
  28108. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  28109. * ```js
  28110. * // Execute 12 compute threads with a workgroup size of 3.
  28111. * const computeFn = Fn( () => {
  28112. *
  28113. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  28114. *
  28115. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  28116. *
  28117. * } ).Else( () => {
  28118. *
  28119. * storageBuffer.element( instanceIndex ).assign( 0 );
  28120. *
  28121. * } );
  28122. *
  28123. * } )().compute( 12, [ 3 ] );
  28124. *
  28125. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  28126. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  28127. * ```
  28128. *
  28129. * @tsl
  28130. * @type {ComputeBuiltinNode<uvec3>}
  28131. */
  28132. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  28133. /**
  28134. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  28135. *
  28136. * @tsl
  28137. * @type {ComputeBuiltinNode<uvec3>}
  28138. */
  28139. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  28140. /**
  28141. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  28142. *
  28143. * @tsl
  28144. * @type {ComputeBuiltinNode<uvec3>}
  28145. */
  28146. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  28147. /**
  28148. * A device dependent variable that exposes the size of the current invocation's subgroup.
  28149. *
  28150. * @tsl
  28151. * @type {ComputeBuiltinNode<uint>}
  28152. */
  28153. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  28154. /**
  28155. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  28156. *
  28157. * This node can only be used with a WebGPU backend.
  28158. *
  28159. * @augments Node
  28160. */
  28161. class BarrierNode extends Node {
  28162. /**
  28163. * Constructs a new barrier node.
  28164. *
  28165. * @param {string} scope - The scope defines the behavior of the node.
  28166. */
  28167. constructor( scope ) {
  28168. super();
  28169. this.scope = scope;
  28170. }
  28171. generate( builder ) {
  28172. const { scope } = this;
  28173. const { renderer } = builder;
  28174. if ( renderer.backend.isWebGLBackend === true ) {
  28175. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  28176. } else {
  28177. builder.addLineFlowCode( `${scope}Barrier()`, this );
  28178. }
  28179. }
  28180. }
  28181. /**
  28182. * TSL function for creating a barrier node.
  28183. *
  28184. * @tsl
  28185. * @function
  28186. * @param {string} scope - The scope defines the behavior of the node..
  28187. * @returns {BarrierNode}
  28188. */
  28189. const barrier = nodeProxy( BarrierNode );
  28190. /**
  28191. * TSL function for creating a workgroup barrier. All compute shader
  28192. * invocations must wait for each invocation within a workgroup to
  28193. * complete before the barrier can be surpassed.
  28194. *
  28195. * @tsl
  28196. * @function
  28197. * @returns {BarrierNode}
  28198. */
  28199. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  28200. /**
  28201. * TSL function for creating a storage barrier. All invocations must
  28202. * wait for each access to variables within the 'storage' address space
  28203. * to complete before the barrier can be passed.
  28204. *
  28205. * @tsl
  28206. * @function
  28207. * @returns {BarrierNode}
  28208. */
  28209. const storageBarrier = () => barrier( 'storage' ).toStack();
  28210. /**
  28211. * TSL function for creating a texture barrier. All invocations must
  28212. * wait for each access to variables within the 'texture' address space
  28213. * to complete before the barrier can be passed.
  28214. *
  28215. * @tsl
  28216. * @function
  28217. * @returns {BarrierNode}
  28218. */
  28219. const textureBarrier = () => barrier( 'texture' ).toStack();
  28220. /**
  28221. * Represents an element of a 'workgroup' scoped buffer.
  28222. *
  28223. * @augments ArrayElementNode
  28224. */
  28225. class WorkgroupInfoElementNode extends ArrayElementNode {
  28226. /**
  28227. * Constructs a new workgroup info element node.
  28228. *
  28229. * @param {Node} workgroupInfoNode - The workgroup info node.
  28230. * @param {Node} indexNode - The index node that defines the element access.
  28231. */
  28232. constructor( workgroupInfoNode, indexNode ) {
  28233. super( workgroupInfoNode, indexNode );
  28234. /**
  28235. * This flag can be used for type testing.
  28236. *
  28237. * @type {boolean}
  28238. * @readonly
  28239. * @default true
  28240. */
  28241. this.isWorkgroupInfoElementNode = true;
  28242. }
  28243. generate( builder, output ) {
  28244. let snippet;
  28245. const isAssignContext = builder.context.assign;
  28246. snippet = super.generate( builder );
  28247. if ( isAssignContext !== true ) {
  28248. const type = this.getNodeType( builder );
  28249. snippet = builder.format( snippet, type, output );
  28250. }
  28251. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  28252. return snippet;
  28253. }
  28254. }
  28255. /**
  28256. * A node allowing the user to create a 'workgroup' scoped buffer within the
  28257. * context of a compute shader. Typically, workgroup scoped buffers are
  28258. * created to hold data that is transferred from a global storage scope into
  28259. * a local workgroup scope. For invocations within a workgroup, data
  28260. * access speeds on 'workgroup' scoped buffers can be significantly faster
  28261. * than similar access operations on globally accessible storage buffers.
  28262. *
  28263. * This node can only be used with a WebGPU backend.
  28264. *
  28265. * @augments Node
  28266. */
  28267. class WorkgroupInfoNode extends Node {
  28268. /**
  28269. * Constructs a new buffer scoped to type scope.
  28270. *
  28271. * @param {string} scope - TODO.
  28272. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  28273. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  28274. */
  28275. constructor( scope, bufferType, bufferCount = 0 ) {
  28276. super( bufferType );
  28277. /**
  28278. * The buffer type.
  28279. *
  28280. * @type {string}
  28281. */
  28282. this.bufferType = bufferType;
  28283. /**
  28284. * The buffer count.
  28285. *
  28286. * @type {number}
  28287. * @default 0
  28288. */
  28289. this.bufferCount = bufferCount;
  28290. /**
  28291. * This flag can be used for type testing.
  28292. *
  28293. * @type {boolean}
  28294. * @readonly
  28295. * @default true
  28296. */
  28297. this.isWorkgroupInfoNode = true;
  28298. /**
  28299. * The data type of the array buffer.
  28300. *
  28301. * @type {string}
  28302. */
  28303. this.elementType = bufferType;
  28304. /**
  28305. * TODO.
  28306. *
  28307. * @type {string}
  28308. */
  28309. this.scope = scope;
  28310. /**
  28311. * The name of the workgroup scoped buffer.
  28312. *
  28313. * @type {string}
  28314. * @default ''
  28315. */
  28316. this.name = '';
  28317. }
  28318. /**
  28319. * Sets the name of this node.
  28320. *
  28321. * @param {string} name - The name to set.
  28322. * @return {WorkgroupInfoNode} A reference to this node.
  28323. */
  28324. setName( name ) {
  28325. this.name = name;
  28326. return this;
  28327. }
  28328. /**
  28329. * Sets the name/label of this node.
  28330. *
  28331. * @deprecated
  28332. * @param {string} name - The name to set.
  28333. * @return {WorkgroupInfoNode} A reference to this node.
  28334. */
  28335. label( name ) {
  28336. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  28337. return this.setName( name );
  28338. }
  28339. /**
  28340. * Sets the scope of this node.
  28341. *
  28342. * @param {string} scope - The scope to set.
  28343. * @return {WorkgroupInfoNode} A reference to this node.
  28344. */
  28345. setScope( scope ) {
  28346. this.scope = scope;
  28347. return this;
  28348. }
  28349. /**
  28350. * The data type of the array buffer.
  28351. *
  28352. * @return {string} The element type.
  28353. */
  28354. getElementType() {
  28355. return this.elementType;
  28356. }
  28357. /**
  28358. * Overwrites the default implementation since the input type
  28359. * is inferred from the scope.
  28360. *
  28361. * @param {NodeBuilder} builder - The current node builder.
  28362. * @return {string} The input type.
  28363. */
  28364. getInputType( /*builder*/ ) {
  28365. return `${this.scope}Array`;
  28366. }
  28367. /**
  28368. * This method can be used to access elements via an index node.
  28369. *
  28370. * @param {IndexNode} indexNode - indexNode.
  28371. * @return {WorkgroupInfoElementNode} A reference to an element.
  28372. */
  28373. element( indexNode ) {
  28374. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  28375. }
  28376. generate( builder ) {
  28377. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  28378. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  28379. }
  28380. }
  28381. /**
  28382. * TSL function for creating a workgroup info node.
  28383. * Creates a new 'workgroup' scoped array buffer.
  28384. *
  28385. * @tsl
  28386. * @function
  28387. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  28388. * @param {number} [count=0] - The number of elements in the buffer.
  28389. * @returns {WorkgroupInfoNode}
  28390. */
  28391. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  28392. /**
  28393. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  28394. * within a shader. In an atomic function, any modification to an atomic variable will
  28395. * occur as an indivisible step with a defined order relative to other modifications.
  28396. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  28397. * atomic operations will not interfere with each other.
  28398. *
  28399. * This node can only be used with a WebGPU backend.
  28400. *
  28401. * @augments Node
  28402. */
  28403. class AtomicFunctionNode extends Node {
  28404. static get type() {
  28405. return 'AtomicFunctionNode';
  28406. }
  28407. /**
  28408. * Constructs a new atomic function node.
  28409. *
  28410. * @param {string} method - The signature of the atomic function to construct.
  28411. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28412. * @param {Node} valueNode - The value that mutates the atomic variable.
  28413. */
  28414. constructor( method, pointerNode, valueNode ) {
  28415. super( 'uint' );
  28416. /**
  28417. * The signature of the atomic function to construct.
  28418. *
  28419. * @type {string}
  28420. */
  28421. this.method = method;
  28422. /**
  28423. * An atomic variable or element of an atomic buffer.
  28424. *
  28425. * @type {Node}
  28426. */
  28427. this.pointerNode = pointerNode;
  28428. /**
  28429. * A value that modifies the atomic variable.
  28430. *
  28431. * @type {Node}
  28432. */
  28433. this.valueNode = valueNode;
  28434. /**
  28435. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  28436. *
  28437. * @type {boolean}
  28438. * @default true
  28439. */
  28440. this.parents = true;
  28441. }
  28442. /**
  28443. * Overwrites the default implementation to return the type of
  28444. * the pointer node.
  28445. *
  28446. * @param {NodeBuilder} builder - The current node builder.
  28447. * @return {string} The input type.
  28448. */
  28449. getInputType( builder ) {
  28450. return this.pointerNode.getNodeType( builder );
  28451. }
  28452. /**
  28453. * Overwritten since the node type is inferred from the input type.
  28454. *
  28455. * @param {NodeBuilder} builder - The current node builder.
  28456. * @return {string} The node type.
  28457. */
  28458. getNodeType( builder ) {
  28459. return this.getInputType( builder );
  28460. }
  28461. generate( builder ) {
  28462. const properties = builder.getNodeProperties( this );
  28463. const parents = properties.parents;
  28464. const method = this.method;
  28465. const type = this.getNodeType( builder );
  28466. const inputType = this.getInputType( builder );
  28467. const a = this.pointerNode;
  28468. const b = this.valueNode;
  28469. const params = [];
  28470. params.push( `&${ a.build( builder, inputType ) }` );
  28471. if ( b !== null ) {
  28472. params.push( b.build( builder, inputType ) );
  28473. }
  28474. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  28475. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  28476. if ( isVoid ) {
  28477. builder.addLineFlowCode( methodSnippet, this );
  28478. } else {
  28479. if ( properties.constNode === undefined ) {
  28480. properties.constNode = expression( methodSnippet, type ).toConst();
  28481. }
  28482. return properties.constNode.build( builder );
  28483. }
  28484. }
  28485. }
  28486. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28487. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28488. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28489. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28490. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28491. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28492. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28493. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28494. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28495. /**
  28496. * TSL function for creating an atomic function node.
  28497. *
  28498. * @tsl
  28499. * @function
  28500. * @param {string} method - The signature of the atomic function to construct.
  28501. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28502. * @param {Node} valueNode - The value that mutates the atomic variable.
  28503. * @returns {AtomicFunctionNode}
  28504. */
  28505. const atomicNode = nodeProxy( AtomicFunctionNode );
  28506. /**
  28507. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28508. *
  28509. * @tsl
  28510. * @function
  28511. * @param {string} method - The signature of the atomic function to construct.
  28512. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28513. * @param {Node} valueNode - The value that mutates the atomic variable.
  28514. * @returns {AtomicFunctionNode}
  28515. */
  28516. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28517. return atomicNode( method, pointerNode, valueNode ).toStack();
  28518. };
  28519. /**
  28520. * Loads the value stored in the atomic variable.
  28521. *
  28522. * @tsl
  28523. * @function
  28524. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28525. * @returns {AtomicFunctionNode}
  28526. */
  28527. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28528. /**
  28529. * Stores a value in the atomic variable.
  28530. *
  28531. * @tsl
  28532. * @function
  28533. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28534. * @param {Node} valueNode - The value that mutates the atomic variable.
  28535. * @returns {AtomicFunctionNode}
  28536. */
  28537. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  28538. /**
  28539. * Increments the value stored in the atomic variable.
  28540. *
  28541. * @tsl
  28542. * @function
  28543. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28544. * @param {Node} valueNode - The value that mutates the atomic variable.
  28545. * @returns {AtomicFunctionNode}
  28546. */
  28547. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28548. /**
  28549. * Decrements the value stored in the atomic variable.
  28550. *
  28551. * @tsl
  28552. * @function
  28553. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28554. * @param {Node} valueNode - The value that mutates the atomic variable.
  28555. * @returns {AtomicFunctionNode}
  28556. */
  28557. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28558. /**
  28559. * Stores in an atomic variable the maximum between its current value and a parameter.
  28560. *
  28561. * @tsl
  28562. * @function
  28563. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28564. * @param {Node} valueNode - The value that mutates the atomic variable.
  28565. * @returns {AtomicFunctionNode}
  28566. */
  28567. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28568. /**
  28569. * Stores in an atomic variable the minimum between its current value and a parameter.
  28570. *
  28571. * @tsl
  28572. * @function
  28573. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28574. * @param {Node} valueNode - The value that mutates the atomic variable.
  28575. * @returns {AtomicFunctionNode}
  28576. */
  28577. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28578. /**
  28579. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28580. *
  28581. * @tsl
  28582. * @function
  28583. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28584. * @param {Node} valueNode - The value that mutates the atomic variable.
  28585. * @returns {AtomicFunctionNode}
  28586. */
  28587. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28588. /**
  28589. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28590. *
  28591. * @tsl
  28592. * @function
  28593. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28594. * @param {Node} valueNode - The value that mutates the atomic variable.
  28595. * @returns {AtomicFunctionNode}
  28596. */
  28597. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28598. /**
  28599. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28600. *
  28601. * @tsl
  28602. * @function
  28603. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28604. * @param {Node} valueNode - The value that mutates the atomic variable.
  28605. * @returns {AtomicFunctionNode}
  28606. */
  28607. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28608. /**
  28609. * This class represents a set of built in WGSL shader functions that sync
  28610. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28611. * or fragment shader invocations within a workgroup. Typically, these functions
  28612. * will synchronously execute an operation using data from all active invocations
  28613. * within the subgroup, then broadcast that result to all active invocations. In
  28614. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28615. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28616. *
  28617. * @augments TempNode
  28618. */
  28619. class SubgroupFunctionNode extends TempNode {
  28620. static get type() {
  28621. return 'SubgroupFunctionNode';
  28622. }
  28623. /**
  28624. * Constructs a new function node.
  28625. *
  28626. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28627. * @param {Node} [aNode=null] - The method's first argument.
  28628. * @param {Node} [bNode=null] - The method's second argument.
  28629. */
  28630. constructor( method, aNode = null, bNode = null ) {
  28631. super();
  28632. /**
  28633. * The subgroup/wave intrinsic method to construct.
  28634. *
  28635. * @type {String}
  28636. */
  28637. this.method = method;
  28638. /**
  28639. * The method's first argument.
  28640. *
  28641. * @type {Node}
  28642. */
  28643. this.aNode = aNode;
  28644. /**
  28645. * The method's second argument.
  28646. *
  28647. * @type {Node}
  28648. */
  28649. this.bNode = bNode;
  28650. }
  28651. getInputType( builder ) {
  28652. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28653. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28654. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28655. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28656. if ( aLen > bLen ) {
  28657. return aType;
  28658. } else {
  28659. return bType;
  28660. }
  28661. }
  28662. getNodeType( builder ) {
  28663. const method = this.method;
  28664. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28665. return 'bool';
  28666. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28667. return 'uvec4';
  28668. } else {
  28669. return this.getInputType( builder );
  28670. }
  28671. }
  28672. generate( builder, output ) {
  28673. const method = this.method;
  28674. const type = this.getNodeType( builder );
  28675. const inputType = this.getInputType( builder );
  28676. const a = this.aNode;
  28677. const b = this.bNode;
  28678. const params = [];
  28679. if (
  28680. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28681. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28682. method === SubgroupFunctionNode.QUAD_BROADCAST
  28683. ) {
  28684. const bType = b.getNodeType( builder );
  28685. params.push(
  28686. a.build( builder, type ),
  28687. b.build( builder, bType === 'float' ? 'int' : type )
  28688. );
  28689. } else if (
  28690. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28691. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28692. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28693. ) {
  28694. params.push(
  28695. a.build( builder, type ),
  28696. b.build( builder, 'uint' )
  28697. );
  28698. } else {
  28699. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28700. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28701. }
  28702. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28703. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28704. }
  28705. serialize( data ) {
  28706. super.serialize( data );
  28707. data.method = this.method;
  28708. }
  28709. deserialize( data ) {
  28710. super.deserialize( data );
  28711. this.method = data.method;
  28712. }
  28713. }
  28714. // 0 inputs
  28715. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28716. // 1 input
  28717. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28718. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28719. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28720. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28721. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28722. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28723. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28724. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28725. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28726. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28727. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28728. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28729. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28730. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28731. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28732. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28733. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28734. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28735. // 2 inputs
  28736. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28737. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28738. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28739. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28740. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28741. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28742. /**
  28743. * Returns true if this invocation has the lowest subgroup_invocation_id
  28744. * among active invocations in the subgroup.
  28745. *
  28746. * @tsl
  28747. * @method
  28748. * @return {bool} The result of the computation.
  28749. */
  28750. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28751. /**
  28752. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28753. * is 1 if pred is true for that active invocation and 0 otherwise.
  28754. *
  28755. * @tsl
  28756. * @method
  28757. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28758. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28759. */
  28760. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28761. /**
  28762. * A reduction that adds e among all active invocations and returns that result.
  28763. *
  28764. * @tsl
  28765. * @method
  28766. * @param {number} e - The value provided to the reduction by the current invocation.
  28767. * @return {number} The accumulated result of the reduction operation.
  28768. */
  28769. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28770. /**
  28771. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28772. *
  28773. * @tsl
  28774. * @method
  28775. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28776. * @return {number} The accumulated result of the inclusive scan operation.
  28777. */
  28778. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28779. /**
  28780. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28781. *
  28782. * @tsl
  28783. * @method
  28784. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28785. * @return {number} The accumulated result of the exclusive scan operation.
  28786. */
  28787. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28788. /**
  28789. * A reduction that multiplies e among all active invocations and returns that result.
  28790. *
  28791. * @tsl
  28792. * @method
  28793. * @param {number} e - The value provided to the reduction by the current invocation.
  28794. * @return {number} The accumulated result of the reduction operation.
  28795. */
  28796. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28797. /**
  28798. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28799. *
  28800. * @tsl
  28801. * @method
  28802. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28803. * @return {number} The accumulated result of the inclusive scan operation.
  28804. */
  28805. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28806. /**
  28807. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28808. *
  28809. * @tsl
  28810. * @method
  28811. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28812. * @return {number} The accumulated result of the exclusive scan operation.
  28813. */
  28814. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28815. /**
  28816. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  28817. *
  28818. * @tsl
  28819. * @method
  28820. * @param {number} e - The value provided to the reduction by the current invocation.
  28821. * @return {number} The result of the reduction operation.
  28822. */
  28823. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  28824. /**
  28825. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  28826. *
  28827. * @tsl
  28828. * @method
  28829. * @param {number} e - The value provided to the reduction by the current invocation.
  28830. * @return {number} The result of the reduction operation.
  28831. */
  28832. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  28833. /**
  28834. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  28835. *
  28836. * @tsl
  28837. * @method
  28838. * @param {number} e - The value provided to the reduction by the current invocation.
  28839. * @return {number} The result of the reduction operation.
  28840. */
  28841. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  28842. /**
  28843. * A reduction that performs a min of e among all active invocations and returns that result.
  28844. *
  28845. * @tsl
  28846. * @method
  28847. * @param {number} e - The value provided to the reduction by the current invocation.
  28848. * @return {number} The result of the reduction operation.
  28849. */
  28850. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28851. /**
  28852. * A reduction that performs a max of e among all active invocations and returns that result.
  28853. *
  28854. * @tsl
  28855. * @method
  28856. * @param {number} e - The value provided to the reduction by the current invocation.
  28857. * @return {number} The result of the reduction operation.
  28858. */
  28859. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28860. /**
  28861. * Returns true if e is true for all active invocations in the subgroup.
  28862. *
  28863. * @tsl
  28864. * @method
  28865. * @return {bool} The result of the computation.
  28866. */
  28867. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28868. /**
  28869. * Returns true if e is true for any active invocation in the subgroup
  28870. *
  28871. * @tsl
  28872. * @method
  28873. * @return {bool} The result of the computation.
  28874. */
  28875. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28876. /**
  28877. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28878. *
  28879. * @tsl
  28880. * @method
  28881. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28882. * @param {number} id - The subgroup invocation to broadcast from.
  28883. * @return {number} The broadcast value.
  28884. */
  28885. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28886. /**
  28887. * Swaps e between invocations in the quad in the X direction.
  28888. *
  28889. * @tsl
  28890. * @method
  28891. * @param {number} e - The value to swap from the current invocation.
  28892. * @return {number} The value received from the swap operation.
  28893. */
  28894. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28895. /**
  28896. * Swaps e between invocations in the quad in the Y direction.
  28897. *
  28898. * @tsl
  28899. * @method
  28900. * @param {number} e - The value to swap from the current invocation.
  28901. * @return {number} The value received from the swap operation.
  28902. */
  28903. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28904. /**
  28905. * Swaps e between invocations in the quad diagonally.
  28906. *
  28907. * @tsl
  28908. * @method
  28909. * @param {number} e - The value to swap from the current invocation.
  28910. * @return {number} The value received from the swap operation.
  28911. */
  28912. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28913. /**
  28914. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28915. *
  28916. * @tsl
  28917. * @method
  28918. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28919. * @param {number} id - The subgroup invocation to broadcast from.
  28920. * @return {number} The broadcast value.
  28921. */
  28922. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28923. /**
  28924. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28925. *
  28926. * @tsl
  28927. * @method
  28928. * @param {number} v - The value to return from subgroup invocation id^mask.
  28929. * @param {number} id - The subgroup invocation which returns the value v.
  28930. * @return {number} The broadcast value.
  28931. */
  28932. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28933. /**
  28934. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28935. *
  28936. * @tsl
  28937. * @method
  28938. * @param {number} v - The value to return from subgroup invocation id^mask.
  28939. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28940. * @return {number} The broadcast value.
  28941. */
  28942. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28943. /**
  28944. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28945. *
  28946. * @tsl
  28947. * @method
  28948. * @param {number} v - The value to return from subgroup invocation id^mask.
  28949. * @param {number} delta - A value that offsets the current in.
  28950. * @return {number} The broadcast value.
  28951. */
  28952. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28953. /**
  28954. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28955. *
  28956. * @tsl
  28957. * @method
  28958. * @param {number} v - The value to return from subgroup invocation id^mask.
  28959. * @param {number} delta - A value that offsets the current subgroup invocation.
  28960. * @return {number} The broadcast value.
  28961. */
  28962. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28963. /**
  28964. * Broadcasts e from the quad invocation with id equal to id.
  28965. *
  28966. * @tsl
  28967. * @method
  28968. * @param {number} e - The value to broadcast.
  28969. * @return {number} The broadcast value.
  28970. */
  28971. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28972. let uniformsLib;
  28973. function getLightData( light ) {
  28974. uniformsLib = uniformsLib || new WeakMap();
  28975. let uniforms = uniformsLib.get( light );
  28976. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28977. return uniforms;
  28978. }
  28979. /**
  28980. * TSL function for getting a shadow matrix uniform node for the given light.
  28981. *
  28982. * @tsl
  28983. * @function
  28984. * @param {Light} light -The light source.
  28985. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28986. */
  28987. function lightShadowMatrix( light ) {
  28988. const data = getLightData( light );
  28989. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28990. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  28991. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  28992. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28993. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  28994. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  28995. light.shadow.camera.updateProjectionMatrix();
  28996. }
  28997. light.shadow.updateMatrices( light );
  28998. }
  28999. return light.shadow.matrix;
  29000. } ) );
  29001. }
  29002. /**
  29003. * TSL function for getting projected uv coordinates for the given light.
  29004. * Relevant when using maps with spot lights.
  29005. *
  29006. * @tsl
  29007. * @function
  29008. * @param {Light} light -The light source.
  29009. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  29010. * @returns {Node<vec3>} The projected uvs.
  29011. */
  29012. function lightProjectionUV( light, position = positionWorld ) {
  29013. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  29014. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  29015. return projectionUV;
  29016. }
  29017. /**
  29018. * TSL function for getting the position in world space for the given light.
  29019. *
  29020. * @tsl
  29021. * @function
  29022. * @param {Light} light -The light source.
  29023. * @returns {UniformNode<vec3>} The light's position in world space.
  29024. */
  29025. function lightPosition( light ) {
  29026. const data = getLightData( light );
  29027. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  29028. }
  29029. /**
  29030. * TSL function for getting the light target position in world space for the given light.
  29031. *
  29032. * @tsl
  29033. * @function
  29034. * @param {Light} light -The light source.
  29035. * @returns {UniformNode<vec3>} The light target position in world space.
  29036. */
  29037. function lightTargetPosition( light ) {
  29038. const data = getLightData( light );
  29039. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  29040. }
  29041. /**
  29042. * TSL function for getting the position in view space for the given light.
  29043. *
  29044. * @tsl
  29045. * @function
  29046. * @param {Light} light - The light source.
  29047. * @returns {UniformNode<vec3>} The light's position in view space.
  29048. */
  29049. function lightViewPosition( light ) {
  29050. const data = getLightData( light );
  29051. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  29052. self.value = self.value || new Vector3();
  29053. self.value.setFromMatrixPosition( light.matrixWorld );
  29054. self.value.applyMatrix4( camera.matrixWorldInverse );
  29055. } ) );
  29056. }
  29057. /**
  29058. * TSL function for getting the light target direction for the given light.
  29059. *
  29060. * @tsl
  29061. * @function
  29062. * @param {Light} light -The light source.
  29063. * @returns {Node<vec3>} The light's target direction.
  29064. */
  29065. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  29066. const sortLights = ( lights ) => {
  29067. return lights.sort( ( a, b ) => a.id - b.id );
  29068. };
  29069. const getLightNodeById = ( id, lightNodes ) => {
  29070. for ( const lightNode of lightNodes ) {
  29071. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  29072. return lightNode;
  29073. }
  29074. }
  29075. return null;
  29076. };
  29077. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  29078. const _hashData = [];
  29079. /**
  29080. * This node represents the scene's lighting and manages the lighting model's life cycle
  29081. * for the current build 3D object. It is responsible for computing the total outgoing
  29082. * light in a given lighting context.
  29083. *
  29084. * @augments Node
  29085. */
  29086. class LightsNode extends Node {
  29087. static get type() {
  29088. return 'LightsNode';
  29089. }
  29090. /**
  29091. * Constructs a new lights node.
  29092. */
  29093. constructor() {
  29094. super( 'vec3' );
  29095. /**
  29096. * A node representing the total diffuse light.
  29097. *
  29098. * @type {Node<vec3>}
  29099. */
  29100. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  29101. /**
  29102. * A node representing the total specular light.
  29103. *
  29104. * @type {Node<vec3>}
  29105. */
  29106. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  29107. /**
  29108. * A node representing the outgoing light.
  29109. *
  29110. * @type {Node<vec3>}
  29111. */
  29112. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  29113. /**
  29114. * An array representing the lights in the scene.
  29115. *
  29116. * @private
  29117. * @type {Array<Light>}
  29118. */
  29119. this._lights = [];
  29120. /**
  29121. * For each light in the scene, this node will create a
  29122. * corresponding light node.
  29123. *
  29124. * @private
  29125. * @type {?Array<LightingNode>}
  29126. * @default null
  29127. */
  29128. this._lightNodes = null;
  29129. /**
  29130. * A hash for identifying the current light nodes setup.
  29131. *
  29132. * @private
  29133. * @type {?string}
  29134. * @default null
  29135. */
  29136. this._lightNodesHash = null;
  29137. /**
  29138. * `LightsNode` sets this property to `true` by default.
  29139. *
  29140. * @type {boolean}
  29141. * @default true
  29142. */
  29143. this.global = true;
  29144. }
  29145. /**
  29146. * Overwrites the default {@link Node#customCacheKey} implementation by including
  29147. * light data into the cache key.
  29148. *
  29149. * @return {number} The custom cache key.
  29150. */
  29151. customCacheKey() {
  29152. const lights = this._lights;
  29153. for ( let i = 0; i < lights.length; i ++ ) {
  29154. const light = lights[ i ];
  29155. _hashData.push( light.id );
  29156. _hashData.push( light.castShadow ? 1 : 0 );
  29157. if ( light.isSpotLight === true ) {
  29158. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  29159. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  29160. _hashData.push( hashMap, hashColorNode );
  29161. }
  29162. }
  29163. const cacheKey = hashArray( _hashData );
  29164. _hashData.length = 0;
  29165. return cacheKey;
  29166. }
  29167. /**
  29168. * Computes a hash value for identifying the current light nodes setup.
  29169. *
  29170. * @param {NodeBuilder} builder - A reference to the current node builder.
  29171. * @return {string} The computed hash.
  29172. */
  29173. getHash( builder ) {
  29174. if ( this._lightNodesHash === null ) {
  29175. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29176. const hash = [];
  29177. for ( const lightNode of this._lightNodes ) {
  29178. hash.push( lightNode.getHash() );
  29179. }
  29180. this._lightNodesHash = 'lights-' + hash.join( ',' );
  29181. }
  29182. return this._lightNodesHash;
  29183. }
  29184. analyze( builder ) {
  29185. const properties = builder.getNodeProperties( this );
  29186. for ( const node of properties.nodes ) {
  29187. node.build( builder );
  29188. }
  29189. properties.outputNode.build( builder );
  29190. }
  29191. /**
  29192. * Creates lighting nodes for each scene light. This makes it possible to further
  29193. * process lights in the node system.
  29194. *
  29195. * @param {NodeBuilder} builder - A reference to the current node builder.
  29196. */
  29197. setupLightsNode( builder ) {
  29198. const lightNodes = [];
  29199. const previousLightNodes = this._lightNodes;
  29200. const lights = sortLights( this._lights );
  29201. const nodeLibrary = builder.renderer.library;
  29202. for ( const light of lights ) {
  29203. if ( light.isNode ) {
  29204. lightNodes.push( nodeObject( light ) );
  29205. } else {
  29206. let lightNode = null;
  29207. if ( previousLightNodes !== null ) {
  29208. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  29209. }
  29210. if ( lightNode === null ) {
  29211. // find the corresponding node type for a given light
  29212. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  29213. if ( lightNodeClass === null ) {
  29214. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  29215. continue;
  29216. }
  29217. let lightNode = null;
  29218. if ( ! _lightsNodeRef.has( light ) ) {
  29219. lightNode = nodeObject( new lightNodeClass( light ) );
  29220. _lightsNodeRef.set( light, lightNode );
  29221. } else {
  29222. lightNode = _lightsNodeRef.get( light );
  29223. }
  29224. lightNodes.push( lightNode );
  29225. }
  29226. }
  29227. }
  29228. this._lightNodes = lightNodes;
  29229. }
  29230. /**
  29231. * Sets up a direct light in the lighting model.
  29232. *
  29233. * @param {Object} builder - The builder object containing the context and stack.
  29234. * @param {Object} lightNode - The light node.
  29235. * @param {Object} lightData - The light object containing color and direction properties.
  29236. */
  29237. setupDirectLight( builder, lightNode, lightData ) {
  29238. const { lightingModel, reflectedLight } = builder.context;
  29239. lightingModel.direct( {
  29240. ...lightData,
  29241. lightNode,
  29242. reflectedLight
  29243. }, builder );
  29244. }
  29245. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  29246. const { lightingModel, reflectedLight } = builder.context;
  29247. lightingModel.directRectArea( {
  29248. ...lightData,
  29249. lightNode,
  29250. reflectedLight
  29251. }, builder );
  29252. }
  29253. /**
  29254. * Setups the internal lights by building all respective
  29255. * light nodes.
  29256. *
  29257. * @param {NodeBuilder} builder - A reference to the current node builder.
  29258. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  29259. */
  29260. setupLights( builder, lightNodes ) {
  29261. for ( const lightNode of lightNodes ) {
  29262. lightNode.build( builder );
  29263. }
  29264. }
  29265. getLightNodes( builder ) {
  29266. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29267. return this._lightNodes;
  29268. }
  29269. /**
  29270. * The implementation makes sure that for each light in the scene
  29271. * there is a corresponding light node. By building the light nodes
  29272. * and evaluating the lighting model the outgoing light is computed.
  29273. *
  29274. * @param {NodeBuilder} builder - A reference to the current node builder.
  29275. * @return {Node<vec3>} A node representing the outgoing light.
  29276. */
  29277. setup( builder ) {
  29278. const currentLightsNode = builder.lightsNode;
  29279. builder.lightsNode = this;
  29280. //
  29281. let outgoingLightNode = this.outgoingLightNode;
  29282. const context = builder.context;
  29283. const lightingModel = context.lightingModel;
  29284. const properties = builder.getNodeProperties( this );
  29285. if ( lightingModel ) {
  29286. const { totalDiffuseNode, totalSpecularNode } = this;
  29287. context.outgoingLight = outgoingLightNode;
  29288. const stack = builder.addStack();
  29289. //
  29290. properties.nodes = stack.nodes;
  29291. //
  29292. lightingModel.start( builder );
  29293. //
  29294. const { backdrop, backdropAlpha } = context;
  29295. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  29296. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  29297. if ( backdrop !== null ) {
  29298. if ( backdropAlpha !== null ) {
  29299. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  29300. } else {
  29301. totalDiffuse = vec3( backdrop );
  29302. }
  29303. context.material.transparent = true;
  29304. }
  29305. totalDiffuseNode.assign( totalDiffuse );
  29306. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  29307. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  29308. //
  29309. lightingModel.finish( builder );
  29310. //
  29311. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  29312. } else {
  29313. properties.nodes = [];
  29314. }
  29315. //
  29316. builder.lightsNode = currentLightsNode;
  29317. return outgoingLightNode;
  29318. }
  29319. /**
  29320. * Configures this node with an array of lights.
  29321. *
  29322. * @param {Array<Light>} lights - An array of lights.
  29323. * @return {LightsNode} A reference to this node.
  29324. */
  29325. setLights( lights ) {
  29326. this._lights = lights;
  29327. this._lightNodes = null;
  29328. this._lightNodesHash = null;
  29329. return this;
  29330. }
  29331. /**
  29332. * Returns an array of the scene's lights.
  29333. *
  29334. * @return {Array<Light>} The scene's lights.
  29335. */
  29336. getLights() {
  29337. return this._lights;
  29338. }
  29339. /**
  29340. * Whether the scene has lights or not.
  29341. *
  29342. * @type {boolean}
  29343. */
  29344. get hasLights() {
  29345. return this._lights.length > 0;
  29346. }
  29347. }
  29348. /**
  29349. * TSL function for creating an instance of `LightsNode` and configuring
  29350. * it with the given array of lights.
  29351. *
  29352. * @tsl
  29353. * @function
  29354. * @param {Array<Light>} lights - An array of lights.
  29355. * @return {LightsNode} The created lights node.
  29356. */
  29357. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  29358. /**
  29359. * Base class for all shadow nodes.
  29360. *
  29361. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  29362. * Lighting nodes might share the same shadow node type or use specific ones depending on
  29363. * their requirements.
  29364. *
  29365. * @augments Node
  29366. */
  29367. class ShadowBaseNode extends Node {
  29368. static get type() {
  29369. return 'ShadowBaseNode';
  29370. }
  29371. /**
  29372. * Constructs a new shadow base node.
  29373. *
  29374. * @param {Light} light - The shadow casting light.
  29375. */
  29376. constructor( light ) {
  29377. super();
  29378. /**
  29379. * The shadow casting light.
  29380. *
  29381. * @type {Light}
  29382. */
  29383. this.light = light;
  29384. /**
  29385. * Overwritten since shadows are updated by default per render.
  29386. *
  29387. * @type {string}
  29388. * @default 'render'
  29389. */
  29390. this.updateBeforeType = NodeUpdateType.RENDER;
  29391. /**
  29392. * This flag can be used for type testing.
  29393. *
  29394. * @type {boolean}
  29395. * @readonly
  29396. * @default true
  29397. */
  29398. this.isShadowBaseNode = true;
  29399. }
  29400. /**
  29401. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  29402. *
  29403. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  29404. */
  29405. setupShadowPosition( { context, material } ) {
  29406. // Use assign inside an Fn()
  29407. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  29408. }
  29409. }
  29410. /**
  29411. * TSL object that represents the vertex position in world space during the shadow pass.
  29412. *
  29413. * @tsl
  29414. * @type {Node<vec3>}
  29415. */
  29416. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  29417. /**
  29418. * Saves the state of the given renderer and stores it into the given state object.
  29419. *
  29420. * If not state object is provided, the function creates one.
  29421. *
  29422. * @private
  29423. * @function
  29424. * @param {Renderer} renderer - The renderer.
  29425. * @param {Object} [state={}] - The state.
  29426. * @return {Object} The state.
  29427. */
  29428. function saveRendererState( renderer, state = {} ) {
  29429. state.toneMapping = renderer.toneMapping;
  29430. state.toneMappingExposure = renderer.toneMappingExposure;
  29431. state.outputColorSpace = renderer.outputColorSpace;
  29432. state.renderTarget = renderer.getRenderTarget();
  29433. state.activeCubeFace = renderer.getActiveCubeFace();
  29434. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  29435. state.renderObjectFunction = renderer.getRenderObjectFunction();
  29436. state.pixelRatio = renderer.getPixelRatio();
  29437. state.mrt = renderer.getMRT();
  29438. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  29439. state.clearAlpha = renderer.getClearAlpha();
  29440. state.autoClear = renderer.autoClear;
  29441. state.scissorTest = renderer.getScissorTest();
  29442. return state;
  29443. }
  29444. /**
  29445. * Saves the state of the given renderer and stores it into the given state object.
  29446. * Besides, the function also resets the state of the renderer to its default values.
  29447. *
  29448. * If not state object is provided, the function creates one.
  29449. *
  29450. * @private
  29451. * @function
  29452. * @param {Renderer} renderer - The renderer.
  29453. * @param {Object} [state={}] - The state.
  29454. * @return {Object} The state.
  29455. */
  29456. function resetRendererState( renderer, state ) {
  29457. state = saveRendererState( renderer, state );
  29458. renderer.setMRT( null );
  29459. renderer.setRenderObjectFunction( null );
  29460. renderer.setClearColor( 0x000000, 1 );
  29461. renderer.autoClear = true;
  29462. return state;
  29463. }
  29464. /**
  29465. * Restores the state of the given renderer from the given state object.
  29466. *
  29467. * @private
  29468. * @function
  29469. * @param {Renderer} renderer - The renderer.
  29470. * @param {Object} state - The state to restore.
  29471. */
  29472. function restoreRendererState( renderer, state ) {
  29473. renderer.toneMapping = state.toneMapping;
  29474. renderer.toneMappingExposure = state.toneMappingExposure;
  29475. renderer.outputColorSpace = state.outputColorSpace;
  29476. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  29477. renderer.setRenderObjectFunction( state.renderObjectFunction );
  29478. renderer.setPixelRatio( state.pixelRatio );
  29479. renderer.setMRT( state.mrt );
  29480. renderer.setClearColor( state.clearColor, state.clearAlpha );
  29481. renderer.autoClear = state.autoClear;
  29482. renderer.setScissorTest( state.scissorTest );
  29483. }
  29484. /**
  29485. * Saves the state of the given scene and stores it into the given state object.
  29486. *
  29487. * If not state object is provided, the function creates one.
  29488. *
  29489. * @private
  29490. * @function
  29491. * @param {Scene} scene - The scene.
  29492. * @param {Object} [state={}] - The state.
  29493. * @return {Object} The state.
  29494. */
  29495. function saveSceneState( scene, state = {} ) {
  29496. state.background = scene.background;
  29497. state.backgroundNode = scene.backgroundNode;
  29498. state.overrideMaterial = scene.overrideMaterial;
  29499. return state;
  29500. }
  29501. /**
  29502. * Saves the state of the given scene and stores it into the given state object.
  29503. * Besides, the function also resets the state of the scene to its default values.
  29504. *
  29505. * If not state object is provided, the function creates one.
  29506. *
  29507. * @private
  29508. * @function
  29509. * @param {Scene} scene - The scene.
  29510. * @param {Object} [state={}] - The state.
  29511. * @return {Object} The state.
  29512. */
  29513. function resetSceneState( scene, state ) {
  29514. state = saveSceneState( scene, state );
  29515. scene.background = null;
  29516. scene.backgroundNode = null;
  29517. scene.overrideMaterial = null;
  29518. return state;
  29519. }
  29520. /**
  29521. * Restores the state of the given scene from the given state object.
  29522. *
  29523. * @private
  29524. * @function
  29525. * @param {Scene} scene - The scene.
  29526. * @param {Object} state - The state to restore.
  29527. */
  29528. function restoreSceneState( scene, state ) {
  29529. scene.background = state.background;
  29530. scene.backgroundNode = state.backgroundNode;
  29531. scene.overrideMaterial = state.overrideMaterial;
  29532. }
  29533. /**
  29534. * Saves the state of the given renderer and scene and stores it into the given state object.
  29535. *
  29536. * If not state object is provided, the function creates one.
  29537. *
  29538. * @private
  29539. * @function
  29540. * @param {Renderer} renderer - The renderer.
  29541. * @param {Scene} scene - The scene.
  29542. * @param {Object} [state={}] - The state.
  29543. * @return {Object} The state.
  29544. */
  29545. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  29546. state = saveRendererState( renderer, state );
  29547. state = saveSceneState( scene, state );
  29548. return state;
  29549. }
  29550. /**
  29551. * Saves the state of the given renderer and scene and stores it into the given state object.
  29552. * Besides, the function also resets the state of the renderer and scene to its default values.
  29553. *
  29554. * If not state object is provided, the function creates one.
  29555. *
  29556. * @private
  29557. * @function
  29558. * @param {Renderer} renderer - The renderer.
  29559. * @param {Scene} scene - The scene.
  29560. * @param {Object} [state={}] - The state.
  29561. * @return {Object} The state.
  29562. */
  29563. function resetRendererAndSceneState( renderer, scene, state ) {
  29564. state = resetRendererState( renderer, state );
  29565. state = resetSceneState( scene, state );
  29566. return state;
  29567. }
  29568. /**
  29569. * Restores the state of the given renderer and scene from the given state object.
  29570. *
  29571. * @private
  29572. * @function
  29573. * @param {Renderer} renderer - The renderer.
  29574. * @param {Scene} scene - The scene.
  29575. * @param {Object} state - The state to restore.
  29576. */
  29577. function restoreRendererAndSceneState( renderer, scene, state ) {
  29578. restoreRendererState( renderer, state );
  29579. restoreSceneState( scene, state );
  29580. }
  29581. var RendererUtils = /*#__PURE__*/Object.freeze({
  29582. __proto__: null,
  29583. resetRendererAndSceneState: resetRendererAndSceneState,
  29584. resetRendererState: resetRendererState,
  29585. resetSceneState: resetSceneState,
  29586. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29587. restoreRendererState: restoreRendererState,
  29588. restoreSceneState: restoreSceneState,
  29589. saveRendererAndSceneState: saveRendererAndSceneState,
  29590. saveRendererState: saveRendererState,
  29591. saveSceneState: saveSceneState
  29592. });
  29593. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29594. /**
  29595. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29596. * with a binary `[0,1]` result.
  29597. *
  29598. * @method
  29599. * @param {Object} inputs - The input parameter object.
  29600. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29601. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29602. * @return {Node<float>} The filtering result.
  29603. */
  29604. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29605. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29606. if ( depthTexture.isArrayTexture ) {
  29607. basic = basic.depth( depthLayer );
  29608. }
  29609. return basic.compare( shadowCoord.z );
  29610. } );
  29611. /**
  29612. * A shadow filtering function performing PCF filtering.
  29613. *
  29614. * @method
  29615. * @param {Object} inputs - The input parameter object.
  29616. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29617. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29618. * @param {LightShadow} inputs.shadow - The light shadow.
  29619. * @return {Node<float>} The filtering result.
  29620. */
  29621. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29622. const depthCompare = ( uv, compare ) => {
  29623. let depth = texture( depthTexture, uv );
  29624. if ( depthTexture.isArrayTexture ) {
  29625. depth = depth.depth( depthLayer );
  29626. }
  29627. return depth.compare( compare );
  29628. };
  29629. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29630. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29631. const texelSize = vec2( 1 ).div( mapSize );
  29632. const dx0 = texelSize.x.negate().mul( radius );
  29633. const dy0 = texelSize.y.negate().mul( radius );
  29634. const dx1 = texelSize.x.mul( radius );
  29635. const dy1 = texelSize.y.mul( radius );
  29636. const dx2 = dx0.div( 2 );
  29637. const dy2 = dy0.div( 2 );
  29638. const dx3 = dx1.div( 2 );
  29639. const dy3 = dy1.div( 2 );
  29640. return add(
  29641. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29642. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29643. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29644. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29645. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29646. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29647. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29648. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29649. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29650. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29651. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29652. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29653. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29654. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29655. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29656. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29657. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29658. ).mul( 1 / 17 );
  29659. } );
  29660. /**
  29661. * A shadow filtering function performing PCF soft filtering.
  29662. *
  29663. * @method
  29664. * @param {Object} inputs - The input parameter object.
  29665. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29666. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29667. * @param {LightShadow} inputs.shadow - The light shadow.
  29668. * @return {Node<float>} The filtering result.
  29669. */
  29670. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29671. const depthCompare = ( uv, compare ) => {
  29672. let depth = texture( depthTexture, uv );
  29673. if ( depthTexture.isArrayTexture ) {
  29674. depth = depth.depth( depthLayer );
  29675. }
  29676. return depth.compare( compare );
  29677. };
  29678. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29679. const texelSize = vec2( 1 ).div( mapSize );
  29680. const dx = texelSize.x;
  29681. const dy = texelSize.y;
  29682. const uv = shadowCoord.xy;
  29683. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29684. uv.subAssign( f.mul( texelSize ) );
  29685. return add(
  29686. depthCompare( uv, shadowCoord.z ),
  29687. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29688. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29689. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29690. mix(
  29691. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29692. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29693. f.x
  29694. ),
  29695. mix(
  29696. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29697. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29698. f.x
  29699. ),
  29700. mix(
  29701. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29702. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29703. f.y
  29704. ),
  29705. mix(
  29706. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29707. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29708. f.y
  29709. ),
  29710. mix(
  29711. mix(
  29712. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29713. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29714. f.x
  29715. ),
  29716. mix(
  29717. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29718. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29719. f.x
  29720. ),
  29721. f.y
  29722. )
  29723. ).mul( 1 / 9 );
  29724. } );
  29725. /**
  29726. * A shadow filtering function performing VSM filtering.
  29727. *
  29728. * @method
  29729. * @param {Object} inputs - The input parameter object.
  29730. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29731. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29732. * @return {Node<float>} The filtering result.
  29733. */
  29734. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29735. const occlusion = float( 1 ).toVar();
  29736. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29737. if ( depthTexture.isArrayTexture ) {
  29738. distribution = distribution.depth( depthLayer );
  29739. }
  29740. distribution = distribution.rg;
  29741. const hardShadow = step( shadowCoord.z, distribution.x );
  29742. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29743. const distance = shadowCoord.z.sub( distribution.x );
  29744. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29745. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29746. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29747. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29748. } );
  29749. return occlusion;
  29750. } );
  29751. //
  29752. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29753. let dist = positionWorld.sub( position ).length();
  29754. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29755. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29756. return dist;
  29757. } );
  29758. const linearShadowDistance = ( light ) => {
  29759. const camera = light.shadow.camera;
  29760. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29761. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29762. const referencePosition = objectPosition( light );
  29763. return linearDistance( referencePosition, nearDistance, farDistance );
  29764. };
  29765. /**
  29766. * Retrieves or creates a shadow material for the given light source.
  29767. *
  29768. * This function checks if a shadow material already exists for the provided light.
  29769. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29770. * in the `shadowMaterialLib` for future use.
  29771. *
  29772. * @tsl
  29773. * @function
  29774. * @param {Light} light - The light source for which the shadow material is needed.
  29775. * If the light is a point light, a depth node is calculated
  29776. * using the linear shadow distance.
  29777. * @returns {NodeMaterial} The shadow material associated with the given light.
  29778. */
  29779. const getShadowMaterial = ( light ) => {
  29780. let material = shadowMaterialLib.get( light );
  29781. if ( material === undefined ) {
  29782. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29783. material = new NodeMaterial();
  29784. material.colorNode = vec4( 0, 0, 0, 1 );
  29785. material.depthNode = depthNode;
  29786. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29787. material.name = 'ShadowMaterial';
  29788. material.fog = false;
  29789. shadowMaterialLib.set( light, material );
  29790. }
  29791. return material;
  29792. };
  29793. //
  29794. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29795. const _shadowRenderObjectKeys = [];
  29796. /**
  29797. * Creates a function to render shadow objects in a scene.
  29798. *
  29799. * @tsl
  29800. * @function
  29801. * @param {Renderer} renderer - The renderer.
  29802. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29803. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29804. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29805. * @return {Function} A function that renders shadow objects.
  29806. *
  29807. * The returned function has the following parameters:
  29808. * @param {Object3D} object - The 3D object to render.
  29809. * @param {Scene} scene - The scene containing the object.
  29810. * @param {Camera} _camera - The camera used for rendering.
  29811. * @param {BufferGeometry} geometry - The geometry of the object.
  29812. * @param {Material} material - The material of the object.
  29813. * @param {Group} group - The group the object belongs to.
  29814. * @param {...any} params - Additional parameters for rendering.
  29815. */
  29816. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  29817. _shadowRenderObjectKeys[ 0 ] = renderer;
  29818. _shadowRenderObjectKeys[ 1 ] = shadow;
  29819. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  29820. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  29821. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  29822. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  29823. if ( useVelocity ) {
  29824. getDataFromObject( object ).useVelocity = true;
  29825. }
  29826. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29827. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  29828. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29829. }
  29830. };
  29831. renderObjectFunction.shadowType = shadowType;
  29832. renderObjectFunction.useVelocity = useVelocity;
  29833. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  29834. }
  29835. _shadowRenderObjectKeys[ 0 ] = null;
  29836. _shadowRenderObjectKeys[ 1 ] = null;
  29837. return renderObjectFunction;
  29838. };
  29839. /**
  29840. * Represents the shader code for the first VSM render pass.
  29841. *
  29842. * @method
  29843. * @param {Object} inputs - The input parameter object.
  29844. * @param {Node<float>} inputs.samples - The number of samples
  29845. * @param {Node<float>} inputs.radius - The radius.
  29846. * @param {Node<float>} inputs.size - The size.
  29847. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  29848. * @return {Node<vec2>} The VSM output.
  29849. */
  29850. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29851. const mean = float( 0 ).toVar( 'meanVertical' );
  29852. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  29853. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29854. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29855. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29856. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29857. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  29858. if ( shadowPass.value.isArrayTexture ) {
  29859. depth = depth.depth( depthLayer );
  29860. }
  29861. depth = depth.x;
  29862. mean.addAssign( depth );
  29863. squaredMean.addAssign( depth.mul( depth ) );
  29864. } );
  29865. mean.divAssign( samples );
  29866. squaredMean.divAssign( samples );
  29867. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29868. return vec2( mean, std_dev );
  29869. } );
  29870. /**
  29871. * Represents the shader code for the second VSM render pass.
  29872. *
  29873. * @method
  29874. * @param {Object} inputs - The input parameter object.
  29875. * @param {Node<float>} inputs.samples - The number of samples
  29876. * @param {Node<float>} inputs.radius - The radius.
  29877. * @param {Node<float>} inputs.size - The size.
  29878. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  29879. * @return {Node<vec2>} The VSM output.
  29880. */
  29881. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29882. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29883. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29884. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29885. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29886. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29887. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29888. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29889. if ( shadowPass.value.isArrayTexture ) {
  29890. distribution = distribution.depth( depthLayer );
  29891. }
  29892. mean.addAssign( distribution.x );
  29893. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29894. } );
  29895. mean.divAssign( samples );
  29896. squaredMean.divAssign( samples );
  29897. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29898. return vec2( mean, std_dev );
  29899. } );
  29900. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29901. //
  29902. let _rendererState;
  29903. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29904. /**
  29905. * Represents the default shadow implementation for lighting nodes.
  29906. *
  29907. * @augments ShadowBaseNode
  29908. */
  29909. class ShadowNode extends ShadowBaseNode {
  29910. static get type() {
  29911. return 'ShadowNode';
  29912. }
  29913. /**
  29914. * Constructs a new shadow node.
  29915. *
  29916. * @param {Light} light - The shadow casting light.
  29917. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29918. */
  29919. constructor( light, shadow = null ) {
  29920. super( light );
  29921. /**
  29922. * The light shadow which defines the properties light's
  29923. * shadow.
  29924. *
  29925. * @type {?LightShadow}
  29926. * @default null
  29927. */
  29928. this.shadow = shadow || light.shadow;
  29929. /**
  29930. * A reference to the shadow map which is a render target.
  29931. *
  29932. * @type {?RenderTarget}
  29933. * @default null
  29934. */
  29935. this.shadowMap = null;
  29936. /**
  29937. * Only relevant for VSM shadows. Render target for the
  29938. * first VSM render pass.
  29939. *
  29940. * @type {?RenderTarget}
  29941. * @default null
  29942. */
  29943. this.vsmShadowMapVertical = null;
  29944. /**
  29945. * Only relevant for VSM shadows. Render target for the
  29946. * second VSM render pass.
  29947. *
  29948. * @type {?RenderTarget}
  29949. * @default null
  29950. */
  29951. this.vsmShadowMapHorizontal = null;
  29952. /**
  29953. * Only relevant for VSM shadows. Node material which
  29954. * is used to render the first VSM pass.
  29955. *
  29956. * @type {?NodeMaterial}
  29957. * @default null
  29958. */
  29959. this.vsmMaterialVertical = null;
  29960. /**
  29961. * Only relevant for VSM shadows. Node material which
  29962. * is used to render the second VSM pass.
  29963. *
  29964. * @type {?NodeMaterial}
  29965. * @default null
  29966. */
  29967. this.vsmMaterialHorizontal = null;
  29968. /**
  29969. * A reference to the output node which defines the
  29970. * final result of this shadow node.
  29971. *
  29972. * @type {?Node}
  29973. * @private
  29974. * @default null
  29975. */
  29976. this._node = null;
  29977. this._cameraFrameId = new WeakMap();
  29978. /**
  29979. * This flag can be used for type testing.
  29980. *
  29981. * @type {boolean}
  29982. * @readonly
  29983. * @default true
  29984. */
  29985. this.isShadowNode = true;
  29986. /**
  29987. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29988. *
  29989. * @type {number}
  29990. * @readonly
  29991. * @default true
  29992. */
  29993. this.depthLayer = 0;
  29994. }
  29995. /**
  29996. * Setups the shadow filtering.
  29997. *
  29998. * @param {NodeBuilder} builder - A reference to the current node builder.
  29999. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30000. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30001. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30002. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30003. * @param {LightShadow} inputs.shadow - The light shadow.
  30004. * @return {Node<float>} The result node of the shadow filtering.
  30005. */
  30006. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  30007. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  30008. .and( shadowCoord.x.lessThanEqual( 1 ) )
  30009. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  30010. .and( shadowCoord.y.lessThanEqual( 1 ) )
  30011. .and( shadowCoord.z.lessThanEqual( 1 ) );
  30012. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  30013. return frustumTest.select( shadowNode, float( 1 ) );
  30014. }
  30015. /**
  30016. * Setups the shadow coordinates.
  30017. *
  30018. * @param {NodeBuilder} builder - A reference to the current node builder.
  30019. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30020. * @return {Node<vec3>} The shadow coordinates.
  30021. */
  30022. setupShadowCoord( builder, shadowPosition ) {
  30023. const { shadow } = this;
  30024. const { renderer } = builder;
  30025. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30026. let shadowCoord = shadowPosition;
  30027. let coordZ;
  30028. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  30029. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  30030. coordZ = shadowCoord.z;
  30031. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  30032. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  30033. }
  30034. } else {
  30035. const w = shadowCoord.w;
  30036. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  30037. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  30038. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  30039. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  30040. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  30041. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  30042. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  30043. }
  30044. shadowCoord = vec3(
  30045. shadowCoord.x,
  30046. shadowCoord.y.oneMinus(), // follow webgpu standards
  30047. coordZ.add( bias )
  30048. );
  30049. return shadowCoord;
  30050. }
  30051. /**
  30052. * Returns the shadow filtering function for the given shadow type.
  30053. *
  30054. * @param {number} type - The shadow type.
  30055. * @return {Function} The filtering function.
  30056. */
  30057. getShadowFilterFn( type ) {
  30058. return _shadowFilterLib[ type ];
  30059. }
  30060. setupRenderTarget( shadow, builder ) {
  30061. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  30062. depthTexture.name = 'ShadowDepthTexture';
  30063. depthTexture.compareFunction = LessCompare;
  30064. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  30065. shadowMap.texture.name = 'ShadowMap';
  30066. shadowMap.texture.type = shadow.mapType;
  30067. shadowMap.depthTexture = depthTexture;
  30068. return { shadowMap, depthTexture };
  30069. }
  30070. /**
  30071. * Setups the shadow output node.
  30072. *
  30073. * @param {NodeBuilder} builder - A reference to the current node builder.
  30074. * @return {Node<vec3>} The shadow output node.
  30075. */
  30076. setupShadow( builder ) {
  30077. const { renderer, camera } = builder;
  30078. const { light, shadow } = this;
  30079. const shadowMapType = renderer.shadowMap.type;
  30080. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  30081. shadow.camera.coordinateSystem = camera.coordinateSystem;
  30082. shadow.camera.updateProjectionMatrix();
  30083. // VSM
  30084. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30085. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  30086. if ( shadowMap.depth > 1 ) {
  30087. if ( ! shadowMap._vsmShadowMapVertical ) {
  30088. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30089. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  30090. }
  30091. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  30092. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  30093. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30094. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  30095. }
  30096. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  30097. } else {
  30098. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30099. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30100. }
  30101. let shadowPassVertical = texture( depthTexture );
  30102. if ( depthTexture.isArrayTexture ) {
  30103. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  30104. }
  30105. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  30106. if ( depthTexture.isArrayTexture ) {
  30107. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  30108. }
  30109. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  30110. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30111. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30112. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  30113. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30114. material.name = 'VSMVertical';
  30115. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  30116. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30117. material.name = 'VSMHorizontal';
  30118. }
  30119. //
  30120. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  30121. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  30122. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  30123. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  30124. //
  30125. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  30126. if ( filterFn === null ) {
  30127. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  30128. }
  30129. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  30130. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  30131. let shadowColor = texture( shadowMap.texture, shadowCoord );
  30132. if ( depthTexture.isArrayTexture ) {
  30133. shadowColor = shadowColor.depth( this.depthLayer );
  30134. }
  30135. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  30136. this.shadowMap = shadowMap;
  30137. this.shadow.map = shadowMap;
  30138. // Shadow Output + Inspector
  30139. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  30140. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  30141. return texture( this.shadowMap.texture );
  30142. } ).toInspector( `${ inspectName } / Depth`, () => {
  30143. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  30144. } );
  30145. }
  30146. /**
  30147. * The implementation performs the setup of the output node. An output is only
  30148. * produces if shadow mapping is globally enabled in the renderer.
  30149. *
  30150. * @param {NodeBuilder} builder - A reference to the current node builder.
  30151. * @return {ShaderCallNodeInternal} The output node.
  30152. */
  30153. setup( builder ) {
  30154. if ( builder.renderer.shadowMap.enabled === false ) return;
  30155. return Fn( () => {
  30156. let node = this._node;
  30157. this.setupShadowPosition( builder );
  30158. if ( node === null ) {
  30159. this._node = node = this.setupShadow( builder );
  30160. }
  30161. if ( builder.material.shadowNode ) { // @deprecated, r171
  30162. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  30163. }
  30164. if ( builder.material.receivedShadowNode ) {
  30165. node = builder.material.receivedShadowNode( node );
  30166. }
  30167. return node;
  30168. } )();
  30169. }
  30170. /**
  30171. * Renders the shadow. The logic of this function could be included
  30172. * into {@link ShadowNode#updateShadow} however more specialized shadow
  30173. * nodes might require a custom shadow map rendering. By having a
  30174. * dedicated method, it's easier to overwrite the default behavior.
  30175. *
  30176. * @param {NodeFrame} frame - A reference to the current node frame.
  30177. */
  30178. renderShadow( frame ) {
  30179. const { shadow, shadowMap, light } = this;
  30180. const { renderer, scene } = frame;
  30181. shadow.updateMatrices( light );
  30182. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  30183. const currentSceneName = scene.name;
  30184. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  30185. renderer.render( scene, shadow.camera );
  30186. scene.name = currentSceneName;
  30187. }
  30188. /**
  30189. * Updates the shadow.
  30190. *
  30191. * @param {NodeFrame} frame - A reference to the current node frame.
  30192. */
  30193. updateShadow( frame ) {
  30194. const { shadowMap, light, shadow } = this;
  30195. const { renderer, scene, camera } = frame;
  30196. const shadowType = renderer.shadowMap.type;
  30197. const depthVersion = shadowMap.depthTexture.version;
  30198. this._depthVersionCached = depthVersion;
  30199. const _shadowCameraLayer = shadow.camera.layers.mask;
  30200. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  30201. shadow.camera.layers.mask = camera.layers.mask;
  30202. }
  30203. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  30204. const currentMRT = renderer.getMRT();
  30205. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  30206. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  30207. scene.overrideMaterial = getShadowMaterial( light );
  30208. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  30209. renderer.setClearColor( 0x000000, 0 );
  30210. renderer.setRenderTarget( shadowMap );
  30211. this.renderShadow( frame );
  30212. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  30213. // vsm blur pass
  30214. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30215. this.vsmPass( renderer );
  30216. }
  30217. shadow.camera.layers.mask = _shadowCameraLayer;
  30218. restoreRendererAndSceneState( renderer, scene, _rendererState );
  30219. }
  30220. /**
  30221. * For VSM additional render passes are required.
  30222. *
  30223. * @param {Renderer} renderer - A reference to the current renderer.
  30224. */
  30225. vsmPass( renderer ) {
  30226. const { shadow } = this;
  30227. const depth = this.shadowMap.depth;
  30228. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30229. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30230. renderer.setRenderTarget( this.vsmShadowMapVertical );
  30231. _quadMesh.material = this.vsmMaterialVertical;
  30232. _quadMesh.render( renderer );
  30233. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  30234. _quadMesh.material = this.vsmMaterialHorizontal;
  30235. _quadMesh.render( renderer );
  30236. }
  30237. /**
  30238. * Frees the internal resources of this shadow node.
  30239. */
  30240. dispose() {
  30241. this.shadowMap.dispose();
  30242. this.shadowMap = null;
  30243. if ( this.vsmShadowMapVertical !== null ) {
  30244. this.vsmShadowMapVertical.dispose();
  30245. this.vsmShadowMapVertical = null;
  30246. this.vsmMaterialVertical.dispose();
  30247. this.vsmMaterialVertical = null;
  30248. }
  30249. if ( this.vsmShadowMapHorizontal !== null ) {
  30250. this.vsmShadowMapHorizontal.dispose();
  30251. this.vsmShadowMapHorizontal = null;
  30252. this.vsmMaterialHorizontal.dispose();
  30253. this.vsmMaterialHorizontal = null;
  30254. }
  30255. super.dispose();
  30256. }
  30257. /**
  30258. * The implementation performs the update of the shadow map if necessary.
  30259. *
  30260. * @param {NodeFrame} frame - A reference to the current node frame.
  30261. */
  30262. updateBefore( frame ) {
  30263. const { shadow } = this;
  30264. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  30265. if ( needsUpdate ) {
  30266. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  30267. needsUpdate = false;
  30268. }
  30269. this._cameraFrameId[ frame.camera ] = frame.frameId;
  30270. }
  30271. if ( needsUpdate ) {
  30272. this.updateShadow( frame );
  30273. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  30274. shadow.needsUpdate = false;
  30275. }
  30276. }
  30277. }
  30278. }
  30279. /**
  30280. * TSL function for creating an instance of `ShadowNode`.
  30281. *
  30282. * @tsl
  30283. * @function
  30284. * @param {Light} light - The shadow casting light.
  30285. * @param {?LightShadow} [shadow] - The light shadow.
  30286. * @return {ShadowNode} The created shadow node.
  30287. */
  30288. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  30289. const _clearColor$1 = /*@__PURE__*/ new Color();
  30290. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  30291. // vector suitable for 2D texture mapping. This code uses the following layout for the
  30292. // 2D texture:
  30293. //
  30294. // xzXZ
  30295. // y Y
  30296. //
  30297. // Y - Positive y direction
  30298. // y - Negative y direction
  30299. // X - Positive x direction
  30300. // x - Negative x direction
  30301. // Z - Positive z direction
  30302. // z - Negative z direction
  30303. //
  30304. // Source and test bed:
  30305. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  30306. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  30307. const v = pos.toVar();
  30308. // Number of texels to avoid at the edge of each square
  30309. const absV = abs( v );
  30310. // Intersect unit cube
  30311. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  30312. absV.mulAssign( scaleToCube );
  30313. // Apply scale to avoid seams
  30314. // two texels less per square (one texel will do for NEAREST)
  30315. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  30316. // Unwrap
  30317. // space: -1 ... 1 range for each square
  30318. //
  30319. // #X## dim := ( 4 , 2 )
  30320. // # # center := ( 1 , 1 )
  30321. const planar = vec2( v.xy ).toVar();
  30322. const almostATexel = texelSizeY.mul( 1.5 );
  30323. const almostOne = almostATexel.oneMinus();
  30324. If( absV.z.greaterThanEqual( almostOne ), () => {
  30325. If( v.z.greaterThan( 0.0 ), () => {
  30326. planar.x.assign( sub( 4.0, v.x ) );
  30327. } );
  30328. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  30329. const signX = sign( v.x );
  30330. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  30331. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  30332. const signY = sign( v.y );
  30333. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  30334. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  30335. } );
  30336. // Transform to UV space
  30337. // scale := 0.5 / dim
  30338. // translate := ( center + 0.5 ) / dim
  30339. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  30340. } ).setLayout( {
  30341. name: 'cubeToUV',
  30342. type: 'vec2',
  30343. inputs: [
  30344. { name: 'pos', type: 'vec3' },
  30345. { name: 'texelSizeY', type: 'float' }
  30346. ]
  30347. } );
  30348. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  30349. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  30350. } );
  30351. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  30352. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30353. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  30354. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  30355. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  30356. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  30357. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  30358. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  30359. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  30360. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  30361. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  30362. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  30363. .mul( 1.0 / 9.0 );
  30364. } );
  30365. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  30366. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  30367. // the vector from the light to the world-space position of the fragment.
  30368. const lightToPosition = shadowCoord.xyz.toVar();
  30369. const lightToPositionLength = lightToPosition.length();
  30370. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  30371. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  30372. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30373. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  30374. const result = float( 1.0 ).toVar();
  30375. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  30376. // dp = normalized distance from light to fragment position
  30377. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  30378. dp.addAssign( bias );
  30379. // bd3D = base direction 3D
  30380. const bd3D = lightToPosition.normalize();
  30381. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  30382. // percentage-closer filtering
  30383. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  30384. } );
  30385. return result;
  30386. } );
  30387. const _viewport = /*@__PURE__*/ new Vector4();
  30388. const _viewportSize = /*@__PURE__*/ new Vector2();
  30389. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  30390. /**
  30391. * Represents the shadow implementation for point light nodes.
  30392. *
  30393. * @augments ShadowNode
  30394. */
  30395. class PointShadowNode extends ShadowNode {
  30396. static get type() {
  30397. return 'PointShadowNode';
  30398. }
  30399. /**
  30400. * Constructs a new point shadow node.
  30401. *
  30402. * @param {PointLight} light - The shadow casting point light.
  30403. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30404. */
  30405. constructor( light, shadow = null ) {
  30406. super( light, shadow );
  30407. }
  30408. /**
  30409. * Overwrites the default implementation to return point light shadow specific
  30410. * filtering functions.
  30411. *
  30412. * @param {number} type - The shadow type.
  30413. * @return {Function} The filtering function.
  30414. */
  30415. getShadowFilterFn( type ) {
  30416. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  30417. }
  30418. /**
  30419. * Overwrites the default implementation so the unaltered shadow position is used.
  30420. *
  30421. * @param {NodeBuilder} builder - A reference to the current node builder.
  30422. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30423. * @return {Node<vec3>} The shadow coordinates.
  30424. */
  30425. setupShadowCoord( builder, shadowPosition ) {
  30426. return shadowPosition;
  30427. }
  30428. /**
  30429. * Overwrites the default implementation to only use point light specific
  30430. * shadow filter functions.
  30431. *
  30432. * @param {NodeBuilder} builder - A reference to the current node builder.
  30433. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30434. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30435. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  30436. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30437. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30438. * @param {LightShadow} inputs.shadow - The light shadow.
  30439. * @return {Node<float>} The result node of the shadow filtering.
  30440. */
  30441. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  30442. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  30443. }
  30444. /**
  30445. * Overwrites the default implementation with point light specific
  30446. * rendering code.
  30447. *
  30448. * @param {NodeFrame} frame - A reference to the current node frame.
  30449. */
  30450. renderShadow( frame ) {
  30451. const { shadow, shadowMap, light } = this;
  30452. const { renderer, scene } = frame;
  30453. const shadowFrameExtents = shadow.getFrameExtents();
  30454. _shadowMapSize.copy( shadow.mapSize );
  30455. _shadowMapSize.multiply( shadowFrameExtents );
  30456. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  30457. _viewportSize.copy( shadow.mapSize );
  30458. //
  30459. const previousAutoClear = renderer.autoClear;
  30460. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  30461. const previousClearAlpha = renderer.getClearAlpha();
  30462. renderer.autoClear = false;
  30463. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  30464. renderer.clear();
  30465. const viewportCount = shadow.getViewportCount();
  30466. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  30467. const viewport = shadow.getViewport( vp );
  30468. const x = _viewportSize.x * viewport.x;
  30469. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  30470. _viewport.set(
  30471. x,
  30472. y,
  30473. _viewportSize.x * viewport.z,
  30474. _viewportSize.y * viewport.w
  30475. );
  30476. shadowMap.viewport.copy( _viewport );
  30477. shadow.updateMatrices( light, vp );
  30478. const currentSceneName = scene.name;
  30479. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  30480. renderer.render( scene, shadow.camera );
  30481. scene.name = currentSceneName;
  30482. }
  30483. //
  30484. renderer.autoClear = previousAutoClear;
  30485. renderer.setClearColor( previousClearColor, previousClearAlpha );
  30486. }
  30487. }
  30488. /**
  30489. * TSL function for creating an instance of `PointShadowNode`.
  30490. *
  30491. * @tsl
  30492. * @function
  30493. * @param {PointLight} light - The shadow casting point light.
  30494. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30495. * @return {PointShadowNode} The created point shadow node.
  30496. */
  30497. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  30498. /**
  30499. * Base class for analytic light nodes.
  30500. *
  30501. * @augments LightingNode
  30502. */
  30503. class AnalyticLightNode extends LightingNode {
  30504. static get type() {
  30505. return 'AnalyticLightNode';
  30506. }
  30507. /**
  30508. * Constructs a new analytic light node.
  30509. *
  30510. * @param {?Light} [light=null] - The light source.
  30511. */
  30512. constructor( light = null ) {
  30513. super();
  30514. /**
  30515. * The light source.
  30516. *
  30517. * @type {?Light}
  30518. * @default null
  30519. */
  30520. this.light = light;
  30521. /**
  30522. * The light's color value.
  30523. *
  30524. * @type {Color}
  30525. */
  30526. this.color = new Color();
  30527. /**
  30528. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  30529. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  30530. *
  30531. * @type {Node}
  30532. */
  30533. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  30534. /**
  30535. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  30536. * The final color node is represented by a different node when using shadows.
  30537. *
  30538. * @type {?Node}
  30539. * @default null
  30540. */
  30541. this.baseColorNode = null;
  30542. /**
  30543. * Represents the light's shadow.
  30544. *
  30545. * @type {?ShadowNode}
  30546. * @default null
  30547. */
  30548. this.shadowNode = null;
  30549. /**
  30550. * Represents the light's shadow color.
  30551. *
  30552. * @type {?Node}
  30553. * @default null
  30554. */
  30555. this.shadowColorNode = null;
  30556. /**
  30557. * This flag can be used for type testing.
  30558. *
  30559. * @type {boolean}
  30560. * @readonly
  30561. * @default true
  30562. */
  30563. this.isAnalyticLightNode = true;
  30564. /**
  30565. * Overwritten since analytic light nodes are updated
  30566. * once per frame.
  30567. *
  30568. * @type {string}
  30569. * @default 'frame'
  30570. */
  30571. this.updateType = NodeUpdateType.FRAME;
  30572. }
  30573. getHash() {
  30574. return this.light.uuid;
  30575. }
  30576. /**
  30577. * Returns a node representing a direction vector which points from the current
  30578. * position in view space to the light's position in view space.
  30579. *
  30580. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30581. * @return {Node<vec3>} The light vector node.
  30582. */
  30583. getLightVector( builder ) {
  30584. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  30585. }
  30586. /**
  30587. * Sets up the direct lighting for the analytic light node.
  30588. *
  30589. * @abstract
  30590. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30591. * @return {Object|undefined} The direct light data (color and direction).
  30592. */
  30593. setupDirect( /*builder*/ ) { }
  30594. /**
  30595. * Sets up the direct rect area lighting for the analytic light node.
  30596. *
  30597. * @abstract
  30598. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30599. * @return {Object|undefined} The direct rect area light data.
  30600. */
  30601. setupDirectRectArea( /*builder*/ ) { }
  30602. /**
  30603. * Setups the shadow node for this light. The method exists so concrete light classes
  30604. * can setup different types of shadow nodes.
  30605. *
  30606. * @return {ShadowNode} The created shadow node.
  30607. */
  30608. setupShadowNode() {
  30609. return shadow( this.light );
  30610. }
  30611. /**
  30612. * Setups the shadow for this light. This method is only executed if the light
  30613. * cast shadows and the current build object receives shadows. It incorporates
  30614. * shadows into the lighting computation.
  30615. *
  30616. * @param {NodeBuilder} builder - The current node builder.
  30617. */
  30618. setupShadow( builder ) {
  30619. const { renderer } = builder;
  30620. if ( renderer.shadowMap.enabled === false ) return;
  30621. let shadowColorNode = this.shadowColorNode;
  30622. if ( shadowColorNode === null ) {
  30623. const customShadowNode = this.light.shadow.shadowNode;
  30624. let shadowNode;
  30625. if ( customShadowNode !== undefined ) {
  30626. shadowNode = nodeObject( customShadowNode );
  30627. } else {
  30628. shadowNode = this.setupShadowNode();
  30629. }
  30630. this.shadowNode = shadowNode;
  30631. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30632. this.baseColorNode = this.colorNode;
  30633. }
  30634. //
  30635. this.colorNode = shadowColorNode;
  30636. }
  30637. /**
  30638. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30639. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30640. * invocate the respective interface methods.
  30641. *
  30642. * @param {NodeBuilder} builder - The current node builder.
  30643. */
  30644. setup( builder ) {
  30645. this.colorNode = this.baseColorNode || this.colorNode;
  30646. if ( this.light.castShadow ) {
  30647. if ( builder.object.receiveShadow ) {
  30648. this.setupShadow( builder );
  30649. }
  30650. } else if ( this.shadowNode !== null ) {
  30651. this.shadowNode.dispose();
  30652. this.shadowNode = null;
  30653. this.shadowColorNode = null;
  30654. }
  30655. const directLightData = this.setupDirect( builder );
  30656. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30657. if ( directLightData ) {
  30658. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30659. }
  30660. if ( directRectAreaLightData ) {
  30661. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30662. }
  30663. }
  30664. /**
  30665. * The update method is used to update light uniforms per frame.
  30666. * Potentially overwritten in concrete light nodes to update light
  30667. * specific uniforms.
  30668. *
  30669. * @param {NodeFrame} frame - A reference to the current node frame.
  30670. */
  30671. update( /*frame*/ ) {
  30672. const { light } = this;
  30673. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30674. }
  30675. }
  30676. /**
  30677. * Represents a `discard` shader operation in TSL.
  30678. *
  30679. * @method
  30680. * @param {Object} inputs - The input parameter object.
  30681. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30682. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30683. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30684. * @return {Node<float>} The distance falloff.
  30685. */
  30686. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30687. // based upon Frostbite 3 Moving to Physically-based Rendering
  30688. // page 32, equation 26: E[window1]
  30689. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30690. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30691. return cutoffDistance.greaterThan( 0 ).select(
  30692. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30693. distanceFalloff
  30694. );
  30695. } ); // validated
  30696. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30697. const lightDirection = lightVector.normalize();
  30698. const lightDistance = lightVector.length();
  30699. const attenuation = getDistanceAttenuation( {
  30700. lightDistance,
  30701. cutoffDistance,
  30702. decayExponent
  30703. } );
  30704. const lightColor = color.mul( attenuation );
  30705. return { lightDirection, lightColor };
  30706. };
  30707. /**
  30708. * Module for representing point lights as nodes.
  30709. *
  30710. * @augments AnalyticLightNode
  30711. */
  30712. class PointLightNode extends AnalyticLightNode {
  30713. static get type() {
  30714. return 'PointLightNode';
  30715. }
  30716. /**
  30717. * Constructs a new point light node.
  30718. *
  30719. * @param {?PointLight} [light=null] - The point light source.
  30720. */
  30721. constructor( light = null ) {
  30722. super( light );
  30723. /**
  30724. * Uniform node representing the cutoff distance.
  30725. *
  30726. * @type {UniformNode<float>}
  30727. */
  30728. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30729. /**
  30730. * Uniform node representing the decay exponent.
  30731. *
  30732. * @type {UniformNode<float>}
  30733. */
  30734. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30735. }
  30736. /**
  30737. * Overwritten to updated point light specific uniforms.
  30738. *
  30739. * @param {NodeFrame} frame - A reference to the current node frame.
  30740. */
  30741. update( frame ) {
  30742. const { light } = this;
  30743. super.update( frame );
  30744. this.cutoffDistanceNode.value = light.distance;
  30745. this.decayExponentNode.value = light.decay;
  30746. }
  30747. /**
  30748. * Overwritten to setup point light specific shadow.
  30749. *
  30750. * @return {PointShadowNode}
  30751. */
  30752. setupShadowNode() {
  30753. return pointShadow( this.light );
  30754. }
  30755. setupDirect( builder ) {
  30756. return directPointLight( {
  30757. color: this.colorNode,
  30758. lightVector: this.getLightVector( builder ),
  30759. cutoffDistance: this.cutoffDistanceNode,
  30760. decayExponent: this.decayExponentNode
  30761. } );
  30762. }
  30763. }
  30764. /**
  30765. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30766. *
  30767. * @tsl
  30768. * @function
  30769. * @param {Node<vec2>} coord - The uv coordinates.
  30770. * @return {Node<float>} The result data.
  30771. */
  30772. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30773. const uv = coord.mul( 2.0 );
  30774. const cx = uv.x.floor();
  30775. const cy = uv.y.floor();
  30776. const result = cx.add( cy ).mod( 2.0 );
  30777. return result.sign();
  30778. } );
  30779. /**
  30780. * Generates a circle based on the uv coordinates.
  30781. *
  30782. * @tsl
  30783. * @function
  30784. * @param {Node<vec2>} coord - The uv to generate the circle.
  30785. * @return {Node<float>} The circle shape.
  30786. */
  30787. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  30788. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  30789. let alpha;
  30790. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  30791. const dlen = float( len2.fwidth() ).toVar();
  30792. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  30793. } else {
  30794. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  30795. }
  30796. return alpha;
  30797. } );
  30798. // Three.js Transpiler
  30799. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  30800. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  30801. const f = float( f_immutable ).toVar();
  30802. const t = float( t_immutable ).toVar();
  30803. const b = bool( b_immutable ).toVar();
  30804. return select( b, t, f );
  30805. } ).setLayout( {
  30806. name: 'mx_select',
  30807. type: 'float',
  30808. inputs: [
  30809. { name: 'b', type: 'bool' },
  30810. { name: 't', type: 'float' },
  30811. { name: 'f', type: 'float' }
  30812. ]
  30813. } );
  30814. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  30815. const b = bool( b_immutable ).toVar();
  30816. const val = float( val_immutable ).toVar();
  30817. return select( b, val.negate(), val );
  30818. } ).setLayout( {
  30819. name: 'mx_negate_if',
  30820. type: 'float',
  30821. inputs: [
  30822. { name: 'val', type: 'float' },
  30823. { name: 'b', type: 'bool' }
  30824. ]
  30825. } );
  30826. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30827. const x = float( x_immutable ).toVar();
  30828. return int( floor( x ) );
  30829. } ).setLayout( {
  30830. name: 'mx_floor',
  30831. type: 'int',
  30832. inputs: [
  30833. { name: 'x', type: 'float' }
  30834. ]
  30835. } );
  30836. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  30837. const x = float( x_immutable ).toVar();
  30838. i.assign( mx_floor( x ) );
  30839. return x.sub( float( i ) );
  30840. } );
  30841. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30842. const t = float( t_immutable ).toVar();
  30843. const s = float( s_immutable ).toVar();
  30844. const v3 = float( v3_immutable ).toVar();
  30845. const v2 = float( v2_immutable ).toVar();
  30846. const v1 = float( v1_immutable ).toVar();
  30847. const v0 = float( v0_immutable ).toVar();
  30848. const s1 = float( sub( 1.0, s ) ).toVar();
  30849. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30850. } ).setLayout( {
  30851. name: 'mx_bilerp_0',
  30852. type: 'float',
  30853. inputs: [
  30854. { name: 'v0', type: 'float' },
  30855. { name: 'v1', type: 'float' },
  30856. { name: 'v2', type: 'float' },
  30857. { name: 'v3', type: 'float' },
  30858. { name: 's', type: 'float' },
  30859. { name: 't', type: 'float' }
  30860. ]
  30861. } );
  30862. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30863. const t = float( t_immutable ).toVar();
  30864. const s = float( s_immutable ).toVar();
  30865. const v3 = vec3( v3_immutable ).toVar();
  30866. const v2 = vec3( v2_immutable ).toVar();
  30867. const v1 = vec3( v1_immutable ).toVar();
  30868. const v0 = vec3( v0_immutable ).toVar();
  30869. const s1 = float( sub( 1.0, s ) ).toVar();
  30870. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30871. } ).setLayout( {
  30872. name: 'mx_bilerp_1',
  30873. type: 'vec3',
  30874. inputs: [
  30875. { name: 'v0', type: 'vec3' },
  30876. { name: 'v1', type: 'vec3' },
  30877. { name: 'v2', type: 'vec3' },
  30878. { name: 'v3', type: 'vec3' },
  30879. { name: 's', type: 'float' },
  30880. { name: 't', type: 'float' }
  30881. ]
  30882. } );
  30883. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  30884. 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 ] ) => {
  30885. const r = float( r_immutable ).toVar();
  30886. const t = float( t_immutable ).toVar();
  30887. const s = float( s_immutable ).toVar();
  30888. const v7 = float( v7_immutable ).toVar();
  30889. const v6 = float( v6_immutable ).toVar();
  30890. const v5 = float( v5_immutable ).toVar();
  30891. const v4 = float( v4_immutable ).toVar();
  30892. const v3 = float( v3_immutable ).toVar();
  30893. const v2 = float( v2_immutable ).toVar();
  30894. const v1 = float( v1_immutable ).toVar();
  30895. const v0 = float( v0_immutable ).toVar();
  30896. const s1 = float( sub( 1.0, s ) ).toVar();
  30897. const t1 = float( sub( 1.0, t ) ).toVar();
  30898. const r1 = float( sub( 1.0, r ) ).toVar();
  30899. 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 ) ) ) ) ) );
  30900. } ).setLayout( {
  30901. name: 'mx_trilerp_0',
  30902. type: 'float',
  30903. inputs: [
  30904. { name: 'v0', type: 'float' },
  30905. { name: 'v1', type: 'float' },
  30906. { name: 'v2', type: 'float' },
  30907. { name: 'v3', type: 'float' },
  30908. { name: 'v4', type: 'float' },
  30909. { name: 'v5', type: 'float' },
  30910. { name: 'v6', type: 'float' },
  30911. { name: 'v7', type: 'float' },
  30912. { name: 's', type: 'float' },
  30913. { name: 't', type: 'float' },
  30914. { name: 'r', type: 'float' }
  30915. ]
  30916. } );
  30917. 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 ] ) => {
  30918. const r = float( r_immutable ).toVar();
  30919. const t = float( t_immutable ).toVar();
  30920. const s = float( s_immutable ).toVar();
  30921. const v7 = vec3( v7_immutable ).toVar();
  30922. const v6 = vec3( v6_immutable ).toVar();
  30923. const v5 = vec3( v5_immutable ).toVar();
  30924. const v4 = vec3( v4_immutable ).toVar();
  30925. const v3 = vec3( v3_immutable ).toVar();
  30926. const v2 = vec3( v2_immutable ).toVar();
  30927. const v1 = vec3( v1_immutable ).toVar();
  30928. const v0 = vec3( v0_immutable ).toVar();
  30929. const s1 = float( sub( 1.0, s ) ).toVar();
  30930. const t1 = float( sub( 1.0, t ) ).toVar();
  30931. const r1 = float( sub( 1.0, r ) ).toVar();
  30932. 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 ) ) ) ) ) );
  30933. } ).setLayout( {
  30934. name: 'mx_trilerp_1',
  30935. type: 'vec3',
  30936. inputs: [
  30937. { name: 'v0', type: 'vec3' },
  30938. { name: 'v1', type: 'vec3' },
  30939. { name: 'v2', type: 'vec3' },
  30940. { name: 'v3', type: 'vec3' },
  30941. { name: 'v4', type: 'vec3' },
  30942. { name: 'v5', type: 'vec3' },
  30943. { name: 'v6', type: 'vec3' },
  30944. { name: 'v7', type: 'vec3' },
  30945. { name: 's', type: 'float' },
  30946. { name: 't', type: 'float' },
  30947. { name: 'r', type: 'float' }
  30948. ]
  30949. } );
  30950. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30951. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30952. const y = float( y_immutable ).toVar();
  30953. const x = float( x_immutable ).toVar();
  30954. const hash = uint( hash_immutable ).toVar();
  30955. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30956. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30957. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30958. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30959. } ).setLayout( {
  30960. name: 'mx_gradient_float_0',
  30961. type: 'float',
  30962. inputs: [
  30963. { name: 'hash', type: 'uint' },
  30964. { name: 'x', type: 'float' },
  30965. { name: 'y', type: 'float' }
  30966. ]
  30967. } );
  30968. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30969. const z = float( z_immutable ).toVar();
  30970. const y = float( y_immutable ).toVar();
  30971. const x = float( x_immutable ).toVar();
  30972. const hash = uint( hash_immutable ).toVar();
  30973. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30974. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30975. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30976. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30977. } ).setLayout( {
  30978. name: 'mx_gradient_float_1',
  30979. type: 'float',
  30980. inputs: [
  30981. { name: 'hash', type: 'uint' },
  30982. { name: 'x', type: 'float' },
  30983. { name: 'y', type: 'float' },
  30984. { name: 'z', type: 'float' }
  30985. ]
  30986. } );
  30987. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30988. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30989. const y = float( y_immutable ).toVar();
  30990. const x = float( x_immutable ).toVar();
  30991. const hash = uvec3( hash_immutable ).toVar();
  30992. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30993. } ).setLayout( {
  30994. name: 'mx_gradient_vec3_0',
  30995. type: 'vec3',
  30996. inputs: [
  30997. { name: 'hash', type: 'uvec3' },
  30998. { name: 'x', type: 'float' },
  30999. { name: 'y', type: 'float' }
  31000. ]
  31001. } );
  31002. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  31003. const z = float( z_immutable ).toVar();
  31004. const y = float( y_immutable ).toVar();
  31005. const x = float( x_immutable ).toVar();
  31006. const hash = uvec3( hash_immutable ).toVar();
  31007. 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 ) );
  31008. } ).setLayout( {
  31009. name: 'mx_gradient_vec3_1',
  31010. type: 'vec3',
  31011. inputs: [
  31012. { name: 'hash', type: 'uvec3' },
  31013. { name: 'x', type: 'float' },
  31014. { name: 'y', type: 'float' },
  31015. { name: 'z', type: 'float' }
  31016. ]
  31017. } );
  31018. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  31019. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31020. const v = float( v_immutable ).toVar();
  31021. return mul( 0.6616, v );
  31022. } ).setLayout( {
  31023. name: 'mx_gradient_scale2d_0',
  31024. type: 'float',
  31025. inputs: [
  31026. { name: 'v', type: 'float' }
  31027. ]
  31028. } );
  31029. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31030. const v = float( v_immutable ).toVar();
  31031. return mul( 0.9820, v );
  31032. } ).setLayout( {
  31033. name: 'mx_gradient_scale3d_0',
  31034. type: 'float',
  31035. inputs: [
  31036. { name: 'v', type: 'float' }
  31037. ]
  31038. } );
  31039. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31040. const v = vec3( v_immutable ).toVar();
  31041. return mul( 0.6616, v );
  31042. } ).setLayout( {
  31043. name: 'mx_gradient_scale2d_1',
  31044. type: 'vec3',
  31045. inputs: [
  31046. { name: 'v', type: 'vec3' }
  31047. ]
  31048. } );
  31049. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  31050. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31051. const v = vec3( v_immutable ).toVar();
  31052. return mul( 0.9820, v );
  31053. } ).setLayout( {
  31054. name: 'mx_gradient_scale3d_1',
  31055. type: 'vec3',
  31056. inputs: [
  31057. { name: 'v', type: 'vec3' }
  31058. ]
  31059. } );
  31060. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  31061. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  31062. const k = int( k_immutable ).toVar();
  31063. const x = uint( x_immutable ).toVar();
  31064. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  31065. } ).setLayout( {
  31066. name: 'mx_rotl32',
  31067. type: 'uint',
  31068. inputs: [
  31069. { name: 'x', type: 'uint' },
  31070. { name: 'k', type: 'int' }
  31071. ]
  31072. } );
  31073. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  31074. a.subAssign( c );
  31075. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  31076. c.addAssign( b );
  31077. b.subAssign( a );
  31078. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  31079. a.addAssign( c );
  31080. c.subAssign( b );
  31081. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  31082. b.addAssign( a );
  31083. a.subAssign( c );
  31084. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  31085. c.addAssign( b );
  31086. b.subAssign( a );
  31087. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  31088. a.addAssign( c );
  31089. c.subAssign( b );
  31090. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  31091. b.addAssign( a );
  31092. } );
  31093. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  31094. const c = uint( c_immutable ).toVar();
  31095. const b = uint( b_immutable ).toVar();
  31096. const a = uint( a_immutable ).toVar();
  31097. c.bitXorAssign( b );
  31098. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  31099. a.bitXorAssign( c );
  31100. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  31101. b.bitXorAssign( a );
  31102. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  31103. c.bitXorAssign( b );
  31104. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  31105. a.bitXorAssign( c );
  31106. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  31107. b.bitXorAssign( a );
  31108. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  31109. c.bitXorAssign( b );
  31110. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  31111. return c;
  31112. } ).setLayout( {
  31113. name: 'mx_bjfinal',
  31114. type: 'uint',
  31115. inputs: [
  31116. { name: 'a', type: 'uint' },
  31117. { name: 'b', type: 'uint' },
  31118. { name: 'c', type: 'uint' }
  31119. ]
  31120. } );
  31121. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  31122. const bits = uint( bits_immutable ).toVar();
  31123. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  31124. } ).setLayout( {
  31125. name: 'mx_bits_to_01',
  31126. type: 'float',
  31127. inputs: [
  31128. { name: 'bits', type: 'uint' }
  31129. ]
  31130. } );
  31131. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  31132. const t = float( t_immutable ).toVar();
  31133. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  31134. } ).setLayout( {
  31135. name: 'mx_fade',
  31136. type: 'float',
  31137. inputs: [
  31138. { name: 't', type: 'float' }
  31139. ]
  31140. } );
  31141. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31142. const x = int( x_immutable ).toVar();
  31143. const len = uint( uint( 1 ) ).toVar();
  31144. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  31145. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  31146. } ).setLayout( {
  31147. name: 'mx_hash_int_0',
  31148. type: 'uint',
  31149. inputs: [
  31150. { name: 'x', type: 'int' }
  31151. ]
  31152. } );
  31153. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31154. const y = int( y_immutable ).toVar();
  31155. const x = int( x_immutable ).toVar();
  31156. const len = uint( uint( 2 ) ).toVar();
  31157. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31158. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31159. a.addAssign( uint( x ) );
  31160. b.addAssign( uint( y ) );
  31161. return mx_bjfinal( a, b, c );
  31162. } ).setLayout( {
  31163. name: 'mx_hash_int_1',
  31164. type: 'uint',
  31165. inputs: [
  31166. { name: 'x', type: 'int' },
  31167. { name: 'y', type: 'int' }
  31168. ]
  31169. } );
  31170. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31171. const z = int( z_immutable ).toVar();
  31172. const y = int( y_immutable ).toVar();
  31173. const x = int( x_immutable ).toVar();
  31174. const len = uint( uint( 3 ) ).toVar();
  31175. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31176. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31177. a.addAssign( uint( x ) );
  31178. b.addAssign( uint( y ) );
  31179. c.addAssign( uint( z ) );
  31180. return mx_bjfinal( a, b, c );
  31181. } ).setLayout( {
  31182. name: 'mx_hash_int_2',
  31183. type: 'uint',
  31184. inputs: [
  31185. { name: 'x', type: 'int' },
  31186. { name: 'y', type: 'int' },
  31187. { name: 'z', type: 'int' }
  31188. ]
  31189. } );
  31190. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  31191. const xx = int( xx_immutable ).toVar();
  31192. const z = int( z_immutable ).toVar();
  31193. const y = int( y_immutable ).toVar();
  31194. const x = int( x_immutable ).toVar();
  31195. const len = uint( uint( 4 ) ).toVar();
  31196. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31197. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31198. a.addAssign( uint( x ) );
  31199. b.addAssign( uint( y ) );
  31200. c.addAssign( uint( z ) );
  31201. mx_bjmix( a, b, c );
  31202. a.addAssign( uint( xx ) );
  31203. return mx_bjfinal( a, b, c );
  31204. } ).setLayout( {
  31205. name: 'mx_hash_int_3',
  31206. type: 'uint',
  31207. inputs: [
  31208. { name: 'x', type: 'int' },
  31209. { name: 'y', type: 'int' },
  31210. { name: 'z', type: 'int' },
  31211. { name: 'xx', type: 'int' }
  31212. ]
  31213. } );
  31214. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  31215. const yy = int( yy_immutable ).toVar();
  31216. const xx = int( xx_immutable ).toVar();
  31217. const z = int( z_immutable ).toVar();
  31218. const y = int( y_immutable ).toVar();
  31219. const x = int( x_immutable ).toVar();
  31220. const len = uint( uint( 5 ) ).toVar();
  31221. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31222. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31223. a.addAssign( uint( x ) );
  31224. b.addAssign( uint( y ) );
  31225. c.addAssign( uint( z ) );
  31226. mx_bjmix( a, b, c );
  31227. a.addAssign( uint( xx ) );
  31228. b.addAssign( uint( yy ) );
  31229. return mx_bjfinal( a, b, c );
  31230. } ).setLayout( {
  31231. name: 'mx_hash_int_4',
  31232. type: 'uint',
  31233. inputs: [
  31234. { name: 'x', type: 'int' },
  31235. { name: 'y', type: 'int' },
  31236. { name: 'z', type: 'int' },
  31237. { name: 'xx', type: 'int' },
  31238. { name: 'yy', type: 'int' }
  31239. ]
  31240. } );
  31241. 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 ] );
  31242. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31243. const y = int( y_immutable ).toVar();
  31244. const x = int( x_immutable ).toVar();
  31245. const h = uint( mx_hash_int( x, y ) ).toVar();
  31246. const result = uvec3().toVar();
  31247. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31248. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31249. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31250. return result;
  31251. } ).setLayout( {
  31252. name: 'mx_hash_vec3_0',
  31253. type: 'uvec3',
  31254. inputs: [
  31255. { name: 'x', type: 'int' },
  31256. { name: 'y', type: 'int' }
  31257. ]
  31258. } );
  31259. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31260. const z = int( z_immutable ).toVar();
  31261. const y = int( y_immutable ).toVar();
  31262. const x = int( x_immutable ).toVar();
  31263. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  31264. const result = uvec3().toVar();
  31265. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31266. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31267. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31268. return result;
  31269. } ).setLayout( {
  31270. name: 'mx_hash_vec3_1',
  31271. type: 'uvec3',
  31272. inputs: [
  31273. { name: 'x', type: 'int' },
  31274. { name: 'y', type: 'int' },
  31275. { name: 'z', type: 'int' }
  31276. ]
  31277. } );
  31278. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  31279. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31280. const p = vec2( p_immutable ).toVar();
  31281. const X = int().toVar(), Y = int().toVar();
  31282. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31283. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31284. const u = float( mx_fade( fx ) ).toVar();
  31285. const v = float( mx_fade( fy ) ).toVar();
  31286. 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();
  31287. return mx_gradient_scale2d( result );
  31288. } ).setLayout( {
  31289. name: 'mx_perlin_noise_float_0',
  31290. type: 'float',
  31291. inputs: [
  31292. { name: 'p', type: 'vec2' }
  31293. ]
  31294. } );
  31295. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31296. const p = vec3( p_immutable ).toVar();
  31297. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31298. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31299. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31300. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31301. const u = float( mx_fade( fx ) ).toVar();
  31302. const v = float( mx_fade( fy ) ).toVar();
  31303. const w = float( mx_fade( fz ) ).toVar();
  31304. 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();
  31305. return mx_gradient_scale3d( result );
  31306. } ).setLayout( {
  31307. name: 'mx_perlin_noise_float_1',
  31308. type: 'float',
  31309. inputs: [
  31310. { name: 'p', type: 'vec3' }
  31311. ]
  31312. } );
  31313. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  31314. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31315. const p = vec2( p_immutable ).toVar();
  31316. const X = int().toVar(), Y = int().toVar();
  31317. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31318. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31319. const u = float( mx_fade( fx ) ).toVar();
  31320. const v = float( mx_fade( fy ) ).toVar();
  31321. 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();
  31322. return mx_gradient_scale2d( result );
  31323. } ).setLayout( {
  31324. name: 'mx_perlin_noise_vec3_0',
  31325. type: 'vec3',
  31326. inputs: [
  31327. { name: 'p', type: 'vec2' }
  31328. ]
  31329. } );
  31330. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31331. const p = vec3( p_immutable ).toVar();
  31332. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31333. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31334. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31335. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31336. const u = float( mx_fade( fx ) ).toVar();
  31337. const v = float( mx_fade( fy ) ).toVar();
  31338. const w = float( mx_fade( fz ) ).toVar();
  31339. 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();
  31340. return mx_gradient_scale3d( result );
  31341. } ).setLayout( {
  31342. name: 'mx_perlin_noise_vec3_1',
  31343. type: 'vec3',
  31344. inputs: [
  31345. { name: 'p', type: 'vec3' }
  31346. ]
  31347. } );
  31348. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  31349. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31350. const p = float( p_immutable ).toVar();
  31351. const ix = int( mx_floor( p ) ).toVar();
  31352. return mx_bits_to_01( mx_hash_int( ix ) );
  31353. } ).setLayout( {
  31354. name: 'mx_cell_noise_float_0',
  31355. type: 'float',
  31356. inputs: [
  31357. { name: 'p', type: 'float' }
  31358. ]
  31359. } );
  31360. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31361. const p = vec2( p_immutable ).toVar();
  31362. const ix = int( mx_floor( p.x ) ).toVar();
  31363. const iy = int( mx_floor( p.y ) ).toVar();
  31364. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  31365. } ).setLayout( {
  31366. name: 'mx_cell_noise_float_1',
  31367. type: 'float',
  31368. inputs: [
  31369. { name: 'p', type: 'vec2' }
  31370. ]
  31371. } );
  31372. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31373. const p = vec3( p_immutable ).toVar();
  31374. const ix = int( mx_floor( p.x ) ).toVar();
  31375. const iy = int( mx_floor( p.y ) ).toVar();
  31376. const iz = int( mx_floor( p.z ) ).toVar();
  31377. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  31378. } ).setLayout( {
  31379. name: 'mx_cell_noise_float_2',
  31380. type: 'float',
  31381. inputs: [
  31382. { name: 'p', type: 'vec3' }
  31383. ]
  31384. } );
  31385. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31386. const p = vec4( p_immutable ).toVar();
  31387. const ix = int( mx_floor( p.x ) ).toVar();
  31388. const iy = int( mx_floor( p.y ) ).toVar();
  31389. const iz = int( mx_floor( p.z ) ).toVar();
  31390. const iw = int( mx_floor( p.w ) ).toVar();
  31391. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  31392. } ).setLayout( {
  31393. name: 'mx_cell_noise_float_3',
  31394. type: 'float',
  31395. inputs: [
  31396. { name: 'p', type: 'vec4' }
  31397. ]
  31398. } );
  31399. 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 ] );
  31400. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31401. const p = float( p_immutable ).toVar();
  31402. const ix = int( mx_floor( p ) ).toVar();
  31403. 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 ) ) ) );
  31404. } ).setLayout( {
  31405. name: 'mx_cell_noise_vec3_0',
  31406. type: 'vec3',
  31407. inputs: [
  31408. { name: 'p', type: 'float' }
  31409. ]
  31410. } );
  31411. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31412. const p = vec2( p_immutable ).toVar();
  31413. const ix = int( mx_floor( p.x ) ).toVar();
  31414. const iy = int( mx_floor( p.y ) ).toVar();
  31415. 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 ) ) ) );
  31416. } ).setLayout( {
  31417. name: 'mx_cell_noise_vec3_1',
  31418. type: 'vec3',
  31419. inputs: [
  31420. { name: 'p', type: 'vec2' }
  31421. ]
  31422. } );
  31423. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31424. const p = vec3( p_immutable ).toVar();
  31425. const ix = int( mx_floor( p.x ) ).toVar();
  31426. const iy = int( mx_floor( p.y ) ).toVar();
  31427. const iz = int( mx_floor( p.z ) ).toVar();
  31428. 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 ) ) ) );
  31429. } ).setLayout( {
  31430. name: 'mx_cell_noise_vec3_2',
  31431. type: 'vec3',
  31432. inputs: [
  31433. { name: 'p', type: 'vec3' }
  31434. ]
  31435. } );
  31436. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31437. const p = vec4( p_immutable ).toVar();
  31438. const ix = int( mx_floor( p.x ) ).toVar();
  31439. const iy = int( mx_floor( p.y ) ).toVar();
  31440. const iz = int( mx_floor( p.z ) ).toVar();
  31441. const iw = int( mx_floor( p.w ) ).toVar();
  31442. 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 ) ) ) );
  31443. } ).setLayout( {
  31444. name: 'mx_cell_noise_vec3_3',
  31445. type: 'vec3',
  31446. inputs: [
  31447. { name: 'p', type: 'vec4' }
  31448. ]
  31449. } );
  31450. 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 ] );
  31451. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31452. const diminish = float( diminish_immutable ).toVar();
  31453. const lacunarity = float( lacunarity_immutable ).toVar();
  31454. const octaves = int( octaves_immutable ).toVar();
  31455. const p = vec3( p_immutable ).toVar();
  31456. const result = float( 0.0 ).toVar();
  31457. const amplitude = float( 1.0 ).toVar();
  31458. Loop( octaves, () => {
  31459. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  31460. amplitude.mulAssign( diminish );
  31461. p.mulAssign( lacunarity );
  31462. } );
  31463. return result;
  31464. } ).setLayout( {
  31465. name: 'mx_fractal_noise_float',
  31466. type: 'float',
  31467. inputs: [
  31468. { name: 'p', type: 'vec3' },
  31469. { name: 'octaves', type: 'int' },
  31470. { name: 'lacunarity', type: 'float' },
  31471. { name: 'diminish', type: 'float' }
  31472. ]
  31473. } );
  31474. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31475. const diminish = float( diminish_immutable ).toVar();
  31476. const lacunarity = float( lacunarity_immutable ).toVar();
  31477. const octaves = int( octaves_immutable ).toVar();
  31478. const p = vec3( p_immutable ).toVar();
  31479. const result = vec3( 0.0 ).toVar();
  31480. const amplitude = float( 1.0 ).toVar();
  31481. Loop( octaves, () => {
  31482. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  31483. amplitude.mulAssign( diminish );
  31484. p.mulAssign( lacunarity );
  31485. } );
  31486. return result;
  31487. } ).setLayout( {
  31488. name: 'mx_fractal_noise_vec3',
  31489. type: 'vec3',
  31490. inputs: [
  31491. { name: 'p', type: 'vec3' },
  31492. { name: 'octaves', type: 'int' },
  31493. { name: 'lacunarity', type: 'float' },
  31494. { name: 'diminish', type: 'float' }
  31495. ]
  31496. } );
  31497. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31498. const diminish = float( diminish_immutable ).toVar();
  31499. const lacunarity = float( lacunarity_immutable ).toVar();
  31500. const octaves = int( octaves_immutable ).toVar();
  31501. const p = vec3( p_immutable ).toVar();
  31502. 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 ) );
  31503. } ).setLayout( {
  31504. name: 'mx_fractal_noise_vec2',
  31505. type: 'vec2',
  31506. inputs: [
  31507. { name: 'p', type: 'vec3' },
  31508. { name: 'octaves', type: 'int' },
  31509. { name: 'lacunarity', type: 'float' },
  31510. { name: 'diminish', type: 'float' }
  31511. ]
  31512. } );
  31513. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31514. const diminish = float( diminish_immutable ).toVar();
  31515. const lacunarity = float( lacunarity_immutable ).toVar();
  31516. const octaves = int( octaves_immutable ).toVar();
  31517. const p = vec3( p_immutable ).toVar();
  31518. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  31519. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  31520. return vec4( c, f );
  31521. } ).setLayout( {
  31522. name: 'mx_fractal_noise_vec4',
  31523. type: 'vec4',
  31524. inputs: [
  31525. { name: 'p', type: 'vec3' },
  31526. { name: 'octaves', type: 'int' },
  31527. { name: 'lacunarity', type: 'float' },
  31528. { name: 'diminish', type: 'float' }
  31529. ]
  31530. } );
  31531. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  31532. const metric = int( metric_immutable ).toVar();
  31533. const jitter = float( jitter_immutable ).toVar();
  31534. const yoff = int( yoff_immutable ).toVar();
  31535. const xoff = int( xoff_immutable ).toVar();
  31536. const y = int( y_immutable ).toVar();
  31537. const x = int( x_immutable ).toVar();
  31538. const p = vec2( p_immutable ).toVar();
  31539. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  31540. const off = vec2( tmp.x, tmp.y ).toVar();
  31541. off.subAssign( 0.5 );
  31542. off.mulAssign( jitter );
  31543. off.addAssign( 0.5 );
  31544. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  31545. const diff = vec2( cellpos.sub( p ) ).toVar();
  31546. If( metric.equal( int( 2 ) ), () => {
  31547. return abs( diff.x ).add( abs( diff.y ) );
  31548. } );
  31549. If( metric.equal( int( 3 ) ), () => {
  31550. return max$1( abs( diff.x ), abs( diff.y ) );
  31551. } );
  31552. return dot( diff, diff );
  31553. } ).setLayout( {
  31554. name: 'mx_worley_distance_0',
  31555. type: 'float',
  31556. inputs: [
  31557. { name: 'p', type: 'vec2' },
  31558. { name: 'x', type: 'int' },
  31559. { name: 'y', type: 'int' },
  31560. { name: 'xoff', type: 'int' },
  31561. { name: 'yoff', type: 'int' },
  31562. { name: 'jitter', type: 'float' },
  31563. { name: 'metric', type: 'int' }
  31564. ]
  31565. } );
  31566. 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 ] ) => {
  31567. const metric = int( metric_immutable ).toVar();
  31568. const jitter = float( jitter_immutable ).toVar();
  31569. const zoff = int( zoff_immutable ).toVar();
  31570. const yoff = int( yoff_immutable ).toVar();
  31571. const xoff = int( xoff_immutable ).toVar();
  31572. const z = int( z_immutable ).toVar();
  31573. const y = int( y_immutable ).toVar();
  31574. const x = int( x_immutable ).toVar();
  31575. const p = vec3( p_immutable ).toVar();
  31576. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  31577. off.subAssign( 0.5 );
  31578. off.mulAssign( jitter );
  31579. off.addAssign( 0.5 );
  31580. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  31581. const diff = vec3( cellpos.sub( p ) ).toVar();
  31582. If( metric.equal( int( 2 ) ), () => {
  31583. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  31584. } );
  31585. If( metric.equal( int( 3 ) ), () => {
  31586. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  31587. } );
  31588. return dot( diff, diff );
  31589. } ).setLayout( {
  31590. name: 'mx_worley_distance_1',
  31591. type: 'float',
  31592. inputs: [
  31593. { name: 'p', type: 'vec3' },
  31594. { name: 'x', type: 'int' },
  31595. { name: 'y', type: 'int' },
  31596. { name: 'z', type: 'int' },
  31597. { name: 'xoff', type: 'int' },
  31598. { name: 'yoff', type: 'int' },
  31599. { name: 'zoff', type: 'int' },
  31600. { name: 'jitter', type: 'float' },
  31601. { name: 'metric', type: 'int' }
  31602. ]
  31603. } );
  31604. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31605. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31606. const metric = int( metric_immutable ).toVar();
  31607. const jitter = float( jitter_immutable ).toVar();
  31608. const p = vec2( p_immutable ).toVar();
  31609. const X = int().toVar(), Y = int().toVar();
  31610. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31611. const sqdist = float( 1e6 ).toVar();
  31612. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31613. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31614. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31615. sqdist.assign( min$1( sqdist, dist ) );
  31616. } );
  31617. } );
  31618. If( metric.equal( int( 0 ) ), () => {
  31619. sqdist.assign( sqrt( sqdist ) );
  31620. } );
  31621. return sqdist;
  31622. } ).setLayout( {
  31623. name: 'mx_worley_noise_float_0',
  31624. type: 'float',
  31625. inputs: [
  31626. { name: 'p', type: 'vec2' },
  31627. { name: 'jitter', type: 'float' },
  31628. { name: 'metric', type: 'int' }
  31629. ]
  31630. } );
  31631. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31632. const metric = int( metric_immutable ).toVar();
  31633. const jitter = float( jitter_immutable ).toVar();
  31634. const p = vec2( p_immutable ).toVar();
  31635. const X = int().toVar(), Y = int().toVar();
  31636. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31637. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31638. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31639. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31640. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31641. If( dist.lessThan( sqdist.x ), () => {
  31642. sqdist.y.assign( sqdist.x );
  31643. sqdist.x.assign( dist );
  31644. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31645. sqdist.y.assign( dist );
  31646. } );
  31647. } );
  31648. } );
  31649. If( metric.equal( int( 0 ) ), () => {
  31650. sqdist.assign( sqrt( sqdist ) );
  31651. } );
  31652. return sqdist;
  31653. } ).setLayout( {
  31654. name: 'mx_worley_noise_vec2_0',
  31655. type: 'vec2',
  31656. inputs: [
  31657. { name: 'p', type: 'vec2' },
  31658. { name: 'jitter', type: 'float' },
  31659. { name: 'metric', type: 'int' }
  31660. ]
  31661. } );
  31662. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31663. const metric = int( metric_immutable ).toVar();
  31664. const jitter = float( jitter_immutable ).toVar();
  31665. const p = vec2( p_immutable ).toVar();
  31666. const X = int().toVar(), Y = int().toVar();
  31667. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31668. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31669. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31670. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31671. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31672. If( dist.lessThan( sqdist.x ), () => {
  31673. sqdist.z.assign( sqdist.y );
  31674. sqdist.y.assign( sqdist.x );
  31675. sqdist.x.assign( dist );
  31676. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31677. sqdist.z.assign( sqdist.y );
  31678. sqdist.y.assign( dist );
  31679. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31680. sqdist.z.assign( dist );
  31681. } );
  31682. } );
  31683. } );
  31684. If( metric.equal( int( 0 ) ), () => {
  31685. sqdist.assign( sqrt( sqdist ) );
  31686. } );
  31687. return sqdist;
  31688. } ).setLayout( {
  31689. name: 'mx_worley_noise_vec3_0',
  31690. type: 'vec3',
  31691. inputs: [
  31692. { name: 'p', type: 'vec2' },
  31693. { name: 'jitter', type: 'float' },
  31694. { name: 'metric', type: 'int' }
  31695. ]
  31696. } );
  31697. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31698. const metric = int( metric_immutable ).toVar();
  31699. const jitter = float( jitter_immutable ).toVar();
  31700. const p = vec3( p_immutable ).toVar();
  31701. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31702. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31703. const sqdist = float( 1e6 ).toVar();
  31704. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31705. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31706. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31707. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31708. sqdist.assign( min$1( sqdist, dist ) );
  31709. } );
  31710. } );
  31711. } );
  31712. If( metric.equal( int( 0 ) ), () => {
  31713. sqdist.assign( sqrt( sqdist ) );
  31714. } );
  31715. return sqdist;
  31716. } ).setLayout( {
  31717. name: 'mx_worley_noise_float_1',
  31718. type: 'float',
  31719. inputs: [
  31720. { name: 'p', type: 'vec3' },
  31721. { name: 'jitter', type: 'float' },
  31722. { name: 'metric', type: 'int' }
  31723. ]
  31724. } );
  31725. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31726. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31727. const metric = int( metric_immutable ).toVar();
  31728. const jitter = float( jitter_immutable ).toVar();
  31729. const p = vec3( p_immutable ).toVar();
  31730. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31731. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31732. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31733. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31734. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31735. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31736. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31737. If( dist.lessThan( sqdist.x ), () => {
  31738. sqdist.y.assign( sqdist.x );
  31739. sqdist.x.assign( dist );
  31740. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31741. sqdist.y.assign( dist );
  31742. } );
  31743. } );
  31744. } );
  31745. } );
  31746. If( metric.equal( int( 0 ) ), () => {
  31747. sqdist.assign( sqrt( sqdist ) );
  31748. } );
  31749. return sqdist;
  31750. } ).setLayout( {
  31751. name: 'mx_worley_noise_vec2_1',
  31752. type: 'vec2',
  31753. inputs: [
  31754. { name: 'p', type: 'vec3' },
  31755. { name: 'jitter', type: 'float' },
  31756. { name: 'metric', type: 'int' }
  31757. ]
  31758. } );
  31759. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31760. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31761. const metric = int( metric_immutable ).toVar();
  31762. const jitter = float( jitter_immutable ).toVar();
  31763. const p = vec3( p_immutable ).toVar();
  31764. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31765. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31766. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31767. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31768. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31769. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31770. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31771. If( dist.lessThan( sqdist.x ), () => {
  31772. sqdist.z.assign( sqdist.y );
  31773. sqdist.y.assign( sqdist.x );
  31774. sqdist.x.assign( dist );
  31775. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31776. sqdist.z.assign( sqdist.y );
  31777. sqdist.y.assign( dist );
  31778. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31779. sqdist.z.assign( dist );
  31780. } );
  31781. } );
  31782. } );
  31783. } );
  31784. If( metric.equal( int( 0 ) ), () => {
  31785. sqdist.assign( sqrt( sqdist ) );
  31786. } );
  31787. return sqdist;
  31788. } ).setLayout( {
  31789. name: 'mx_worley_noise_vec3_1',
  31790. type: 'vec3',
  31791. inputs: [
  31792. { name: 'p', type: 'vec3' },
  31793. { name: 'jitter', type: 'float' },
  31794. { name: 'metric', type: 'int' }
  31795. ]
  31796. } );
  31797. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  31798. // Unified Noise 2D
  31799. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  31800. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  31801. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31802. octaves_immutable, lacunarity_immutable, diminish_immutable
  31803. ] ) => {
  31804. const noiseType = int( noiseType_immutable ).toVar();
  31805. const texcoord = vec2( texcoord_immutable ).toVar();
  31806. const freq = vec2( freq_immutable ).toVar();
  31807. const offset = vec2( offset_immutable ).toVar();
  31808. const jitter = float( jitter_immutable ).toVar();
  31809. const outmin = float( outmin_immutable ).toVar();
  31810. const outmax = float( outmax_immutable ).toVar();
  31811. const clampoutput = bool( clampoutput_immutable ).toVar();
  31812. const octaves = int( octaves_immutable ).toVar();
  31813. const lacunarity = float( lacunarity_immutable ).toVar();
  31814. const diminish = float( diminish_immutable ).toVar();
  31815. // Compute input position
  31816. const p = texcoord.mul( freq ).add( offset );
  31817. const result = float( 0.0 ).toVar();
  31818. // Perlin
  31819. If( noiseType.equal( int( 0 ) ), () => {
  31820. result.assign( mx_perlin_noise_vec3( p ) );
  31821. } );
  31822. // Cell
  31823. If( noiseType.equal( int( 1 ) ), () => {
  31824. result.assign( mx_cell_noise_vec3( p ) );
  31825. } );
  31826. // Worley (metric=0 = euclidean)
  31827. If( noiseType.equal( int( 2 ) ), () => {
  31828. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31829. } );
  31830. // Fractal (use vec3(p, 0.0) for 2D input)
  31831. If( noiseType.equal( int( 3 ) ), () => {
  31832. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  31833. } );
  31834. // Remap output to [outmin, outmax]
  31835. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31836. // Clamp if requested
  31837. If( clampoutput, () => {
  31838. result.assign( clamp( result, outmin, outmax ) );
  31839. } );
  31840. return result;
  31841. } ).setLayout( {
  31842. name: 'mx_unifiednoise2d',
  31843. type: 'float',
  31844. inputs: [
  31845. { name: 'noiseType', type: 'int' },
  31846. { name: 'texcoord', type: 'vec2' },
  31847. { name: 'freq', type: 'vec2' },
  31848. { name: 'offset', type: 'vec2' },
  31849. { name: 'jitter', type: 'float' },
  31850. { name: 'outmin', type: 'float' },
  31851. { name: 'outmax', type: 'float' },
  31852. { name: 'clampoutput', type: 'bool' },
  31853. { name: 'octaves', type: 'int' },
  31854. { name: 'lacunarity', type: 'float' },
  31855. { name: 'diminish', type: 'float' }
  31856. ]
  31857. } );
  31858. // Unified Noise 3D
  31859. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  31860. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  31861. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31862. octaves_immutable, lacunarity_immutable, diminish_immutable
  31863. ] ) => {
  31864. const noiseType = int( noiseType_immutable ).toVar();
  31865. const position = vec3( position_immutable ).toVar();
  31866. const freq = vec3( freq_immutable ).toVar();
  31867. const offset = vec3( offset_immutable ).toVar();
  31868. const jitter = float( jitter_immutable ).toVar();
  31869. const outmin = float( outmin_immutable ).toVar();
  31870. const outmax = float( outmax_immutable ).toVar();
  31871. const clampoutput = bool( clampoutput_immutable ).toVar();
  31872. const octaves = int( octaves_immutable ).toVar();
  31873. const lacunarity = float( lacunarity_immutable ).toVar();
  31874. const diminish = float( diminish_immutable ).toVar();
  31875. // Compute input position
  31876. const p = position.mul( freq ).add( offset );
  31877. const result = float( 0.0 ).toVar();
  31878. // Perlin
  31879. If( noiseType.equal( int( 0 ) ), () => {
  31880. result.assign( mx_perlin_noise_vec3( p ) );
  31881. } );
  31882. // Cell
  31883. If( noiseType.equal( int( 1 ) ), () => {
  31884. result.assign( mx_cell_noise_vec3( p ) );
  31885. } );
  31886. // Worley (metric=0 = euclidean)
  31887. If( noiseType.equal( int( 2 ) ), () => {
  31888. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31889. } );
  31890. // Fractal
  31891. If( noiseType.equal( int( 3 ) ), () => {
  31892. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  31893. } );
  31894. // Remap output to [outmin, outmax]
  31895. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31896. // Clamp if requested
  31897. If( clampoutput, () => {
  31898. result.assign( clamp( result, outmin, outmax ) );
  31899. } );
  31900. return result;
  31901. } ).setLayout( {
  31902. name: 'mx_unifiednoise3d',
  31903. type: 'float',
  31904. inputs: [
  31905. { name: 'noiseType', type: 'int' },
  31906. { name: 'position', type: 'vec3' },
  31907. { name: 'freq', type: 'vec3' },
  31908. { name: 'offset', type: 'vec3' },
  31909. { name: 'jitter', type: 'float' },
  31910. { name: 'outmin', type: 'float' },
  31911. { name: 'outmax', type: 'float' },
  31912. { name: 'clampoutput', type: 'bool' },
  31913. { name: 'octaves', type: 'int' },
  31914. { name: 'lacunarity', type: 'float' },
  31915. { name: 'diminish', type: 'float' }
  31916. ]
  31917. } );
  31918. // Three.js Transpiler
  31919. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31920. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31921. const s = hsv.y;
  31922. const v = hsv.z;
  31923. const result = vec3().toVar();
  31924. If( s.lessThan( 0.0001 ), () => {
  31925. result.assign( vec3( v, v, v ) );
  31926. } ).Else( () => {
  31927. let h = hsv.x;
  31928. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31929. const hi = int( trunc( h ) );
  31930. const f = h.sub( float( hi ) );
  31931. const p = v.mul( s.oneMinus() );
  31932. const q = v.mul( s.mul( f ).oneMinus() );
  31933. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31934. If( hi.equal( int( 0 ) ), () => {
  31935. result.assign( vec3( v, t, p ) );
  31936. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31937. result.assign( vec3( q, v, p ) );
  31938. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31939. result.assign( vec3( p, v, t ) );
  31940. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31941. result.assign( vec3( p, q, v ) );
  31942. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31943. result.assign( vec3( t, p, v ) );
  31944. } ).Else( () => {
  31945. result.assign( vec3( v, p, q ) );
  31946. } );
  31947. } );
  31948. return result;
  31949. } ).setLayout( {
  31950. name: 'mx_hsvtorgb',
  31951. type: 'vec3',
  31952. inputs: [
  31953. { name: 'hsv', type: 'vec3' }
  31954. ]
  31955. } );
  31956. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31957. const c = vec3( c_immutable ).toVar();
  31958. const r = float( c.x ).toVar();
  31959. const g = float( c.y ).toVar();
  31960. const b = float( c.z ).toVar();
  31961. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31962. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31963. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31964. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31965. v.assign( maxcomp );
  31966. If( maxcomp.greaterThan( 0.0 ), () => {
  31967. s.assign( delta.div( maxcomp ) );
  31968. } ).Else( () => {
  31969. s.assign( 0.0 );
  31970. } );
  31971. If( s.lessThanEqual( 0.0 ), () => {
  31972. h.assign( 0.0 );
  31973. } ).Else( () => {
  31974. If( r.greaterThanEqual( maxcomp ), () => {
  31975. h.assign( g.sub( b ).div( delta ) );
  31976. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31977. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31978. } ).Else( () => {
  31979. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31980. } );
  31981. h.mulAssign( 1.0 / 6.0 );
  31982. If( h.lessThan( 0.0 ), () => {
  31983. h.addAssign( 1.0 );
  31984. } );
  31985. } );
  31986. return vec3( h, s, v );
  31987. } ).setLayout( {
  31988. name: 'mx_rgbtohsv',
  31989. type: 'vec3',
  31990. inputs: [
  31991. { name: 'c', type: 'vec3' }
  31992. ]
  31993. } );
  31994. // Three.js Transpiler
  31995. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31996. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31997. const color = vec3( color_immutable ).toVar();
  31998. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31999. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  32000. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  32001. return mix( linSeg, powSeg, isAbove );
  32002. } ).setLayout( {
  32003. name: 'mx_srgb_texture_to_lin_rec709',
  32004. type: 'vec3',
  32005. inputs: [
  32006. { name: 'color', type: 'vec3' }
  32007. ]
  32008. } );
  32009. const mx_aastep = ( threshold, value ) => {
  32010. threshold = float( threshold );
  32011. value = float( value );
  32012. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  32013. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  32014. };
  32015. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  32016. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  32017. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  32018. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  32019. const mx_ramp4 = (
  32020. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  32021. ) => {
  32022. const u = texcoord.x.clamp();
  32023. const v = texcoord.y.clamp();
  32024. const top = mix( valuetl, valuetr, u );
  32025. const bottom = mix( valuebl, valuebr, u );
  32026. return mix( top, bottom, v );
  32027. };
  32028. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  32029. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  32030. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  32031. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  32032. const mx_safepower = ( in1, in2 = 1 ) => {
  32033. in1 = float( in1 );
  32034. return in1.abs().pow( in2 ).mul( in1.sign() );
  32035. };
  32036. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  32037. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32038. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32039. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32040. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  32041. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  32042. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  32043. return noise_vec4.mul( amplitude ).add( pivot );
  32044. };
  32045. 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 );
  32046. 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 );
  32047. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32048. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32049. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32050. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  32051. 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 );
  32052. 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 );
  32053. 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 );
  32054. 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 );
  32055. // === Moved from MaterialXLoader.js ===
  32056. // Math ops
  32057. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  32058. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  32059. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  32060. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  32061. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  32062. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  32063. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  32064. const mx_timer = () => time;
  32065. const mx_frame = () => frameId;
  32066. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  32067. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  32068. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  32069. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  32070. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  32071. const mx_separate = ( in1, channelOrOut = null ) => {
  32072. if ( typeof channelOrOut === 'string' ) {
  32073. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32074. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  32075. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  32076. }
  32077. if ( typeof channelOrOut === 'number' ) {
  32078. return in1.element( channelOrOut );
  32079. }
  32080. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  32081. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32082. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  32083. }
  32084. return in1;
  32085. };
  32086. const mx_place2d = (
  32087. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  32088. ) => {
  32089. let uv = texcoord;
  32090. if ( pivot ) uv = uv.sub( pivot );
  32091. if ( scale ) uv = uv.mul( scale );
  32092. if ( rotate ) {
  32093. const rad = rotate.mul( Math.PI / 180.0 );
  32094. const cosR = rad.cos();
  32095. const sinR = rad.sin();
  32096. uv = vec2(
  32097. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  32098. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  32099. );
  32100. }
  32101. if ( pivot ) uv = uv.add( pivot );
  32102. if ( offset ) uv = uv.add( offset );
  32103. return uv;
  32104. };
  32105. const mx_rotate2d = ( input, amount ) => {
  32106. input = vec2( input );
  32107. amount = float( amount );
  32108. const radians = amount.mul( Math.PI / 180.0 );
  32109. return rotate( input, radians );
  32110. };
  32111. const mx_rotate3d = ( input, amount, axis ) => {
  32112. input = vec3( input );
  32113. amount = float( amount );
  32114. axis = vec3( axis );
  32115. const radians = amount.mul( Math.PI / 180.0 );
  32116. const nAxis = axis.normalize();
  32117. const cosA = radians.cos();
  32118. const sinA = radians.sin();
  32119. const oneMinusCosA = float( 1 ).sub( cosA );
  32120. const rot =
  32121. input.mul( cosA )
  32122. .add( nAxis.cross( input ).mul( sinA ) )
  32123. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  32124. return rot;
  32125. };
  32126. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  32127. input = vec3( input );
  32128. scale = float( scale );
  32129. return bumpMap( input, scale );
  32130. };
  32131. /**
  32132. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  32133. *
  32134. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  32135. *
  32136. * ```js
  32137. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  32138. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  32139. * ```
  32140. *
  32141. * @tsl
  32142. * @function
  32143. * @param {Node<vec3>} normal - The normal to correct.
  32144. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  32145. * @param {Node<vec3>} cubePos - The cube position.
  32146. * @return {Node<vec3>} The parallax corrected normal.
  32147. */
  32148. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  32149. const nDir = normalize( normal ).toVar();
  32150. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32151. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32152. const rbminmax = vec3().toVar();
  32153. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  32154. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  32155. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  32156. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  32157. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  32158. return boxIntersection.sub( cubePos );
  32159. } );
  32160. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  32161. // normal is assumed to have unit length
  32162. const x = normal.x, y = normal.y, z = normal.z;
  32163. // band 0
  32164. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  32165. // band 1
  32166. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  32167. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  32168. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  32169. // band 2
  32170. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  32171. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  32172. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  32173. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  32174. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  32175. return result;
  32176. } );
  32177. // constants
  32178. var TSL = /*#__PURE__*/Object.freeze({
  32179. __proto__: null,
  32180. BRDF_GGX: BRDF_GGX,
  32181. BRDF_Lambert: BRDF_Lambert,
  32182. BasicPointShadowFilter: BasicPointShadowFilter,
  32183. BasicShadowFilter: BasicShadowFilter,
  32184. Break: Break,
  32185. Const: Const,
  32186. Continue: Continue,
  32187. DFGApprox: DFGApprox,
  32188. D_GGX: D_GGX,
  32189. Discard: Discard,
  32190. EPSILON: EPSILON,
  32191. F_Schlick: F_Schlick,
  32192. Fn: Fn,
  32193. HALF_PI: HALF_PI,
  32194. INFINITY: INFINITY,
  32195. If: If,
  32196. Loop: Loop,
  32197. NodeAccess: NodeAccess,
  32198. NodeShaderStage: NodeShaderStage,
  32199. NodeType: NodeType,
  32200. NodeUpdateType: NodeUpdateType,
  32201. OnMaterialUpdate: OnMaterialUpdate,
  32202. OnObjectUpdate: OnObjectUpdate,
  32203. PCFShadowFilter: PCFShadowFilter,
  32204. PCFSoftShadowFilter: PCFSoftShadowFilter,
  32205. PI: PI,
  32206. PI2: PI2,
  32207. PointShadowFilter: PointShadowFilter,
  32208. Return: Return,
  32209. Schlick_to_F0: Schlick_to_F0,
  32210. ScriptableNodeResources: ScriptableNodeResources,
  32211. ShaderNode: ShaderNode,
  32212. Stack: Stack,
  32213. Switch: Switch,
  32214. TBNViewMatrix: TBNViewMatrix,
  32215. TWO_PI: TWO_PI,
  32216. VSMShadowFilter: VSMShadowFilter,
  32217. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  32218. Var: Var,
  32219. VarIntent: VarIntent,
  32220. abs: abs,
  32221. acesFilmicToneMapping: acesFilmicToneMapping,
  32222. acos: acos,
  32223. add: add,
  32224. addMethodChaining: addMethodChaining,
  32225. addNodeElement: addNodeElement,
  32226. agxToneMapping: agxToneMapping,
  32227. all: all,
  32228. alphaT: alphaT,
  32229. and: and,
  32230. anisotropy: anisotropy,
  32231. anisotropyB: anisotropyB,
  32232. anisotropyT: anisotropyT,
  32233. any: any,
  32234. append: append,
  32235. array: array,
  32236. arrayBuffer: arrayBuffer,
  32237. asin: asin,
  32238. assign: assign,
  32239. atan: atan,
  32240. atan2: atan2,
  32241. atomicAdd: atomicAdd,
  32242. atomicAnd: atomicAnd,
  32243. atomicFunc: atomicFunc,
  32244. atomicLoad: atomicLoad,
  32245. atomicMax: atomicMax,
  32246. atomicMin: atomicMin,
  32247. atomicOr: atomicOr,
  32248. atomicStore: atomicStore,
  32249. atomicSub: atomicSub,
  32250. atomicXor: atomicXor,
  32251. attenuationColor: attenuationColor,
  32252. attenuationDistance: attenuationDistance,
  32253. attribute: attribute,
  32254. attributeArray: attributeArray,
  32255. backgroundBlurriness: backgroundBlurriness,
  32256. backgroundIntensity: backgroundIntensity,
  32257. backgroundRotation: backgroundRotation,
  32258. batch: batch,
  32259. bentNormalView: bentNormalView,
  32260. billboarding: billboarding,
  32261. bitAnd: bitAnd,
  32262. bitNot: bitNot,
  32263. bitOr: bitOr,
  32264. bitXor: bitXor,
  32265. bitangentGeometry: bitangentGeometry,
  32266. bitangentLocal: bitangentLocal,
  32267. bitangentView: bitangentView,
  32268. bitangentWorld: bitangentWorld,
  32269. bitcast: bitcast,
  32270. blendBurn: blendBurn,
  32271. blendColor: blendColor,
  32272. blendDodge: blendDodge,
  32273. blendOverlay: blendOverlay,
  32274. blendScreen: blendScreen,
  32275. blur: blur,
  32276. bool: bool,
  32277. buffer: buffer,
  32278. bufferAttribute: bufferAttribute,
  32279. builtin: builtin,
  32280. bumpMap: bumpMap,
  32281. burn: burn,
  32282. bvec2: bvec2,
  32283. bvec3: bvec3,
  32284. bvec4: bvec4,
  32285. bypass: bypass,
  32286. cache: cache,
  32287. call: call,
  32288. cameraFar: cameraFar,
  32289. cameraIndex: cameraIndex,
  32290. cameraNear: cameraNear,
  32291. cameraNormalMatrix: cameraNormalMatrix,
  32292. cameraPosition: cameraPosition,
  32293. cameraProjectionMatrix: cameraProjectionMatrix,
  32294. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  32295. cameraViewMatrix: cameraViewMatrix,
  32296. cameraViewport: cameraViewport,
  32297. cameraWorldMatrix: cameraWorldMatrix,
  32298. cbrt: cbrt,
  32299. cdl: cdl,
  32300. ceil: ceil,
  32301. checker: checker,
  32302. cineonToneMapping: cineonToneMapping,
  32303. clamp: clamp,
  32304. clearcoat: clearcoat,
  32305. clearcoatNormalView: clearcoatNormalView,
  32306. clearcoatRoughness: clearcoatRoughness,
  32307. code: code,
  32308. color: color,
  32309. colorSpaceToWorking: colorSpaceToWorking,
  32310. colorToDirection: colorToDirection,
  32311. compute: compute,
  32312. computeKernel: computeKernel,
  32313. computeSkinning: computeSkinning,
  32314. context: context,
  32315. convert: convert,
  32316. convertColorSpace: convertColorSpace,
  32317. convertToTexture: convertToTexture,
  32318. cos: cos,
  32319. cross: cross,
  32320. cubeTexture: cubeTexture,
  32321. cubeTextureBase: cubeTextureBase,
  32322. cubeToUV: cubeToUV,
  32323. dFdx: dFdx,
  32324. dFdy: dFdy,
  32325. dashSize: dashSize,
  32326. debug: debug,
  32327. decrement: decrement,
  32328. decrementBefore: decrementBefore,
  32329. defaultBuildStages: defaultBuildStages,
  32330. defaultShaderStages: defaultShaderStages,
  32331. defined: defined,
  32332. degrees: degrees,
  32333. deltaTime: deltaTime,
  32334. densityFog: densityFog,
  32335. densityFogFactor: densityFogFactor,
  32336. depth: depth,
  32337. depthPass: depthPass,
  32338. determinant: determinant,
  32339. difference: difference,
  32340. diffuseColor: diffuseColor,
  32341. directPointLight: directPointLight,
  32342. directionToColor: directionToColor,
  32343. directionToFaceDirection: directionToFaceDirection,
  32344. dispersion: dispersion,
  32345. distance: distance,
  32346. div: div,
  32347. dodge: dodge,
  32348. dot: dot,
  32349. drawIndex: drawIndex,
  32350. dynamicBufferAttribute: dynamicBufferAttribute,
  32351. element: element,
  32352. emissive: emissive,
  32353. equal: equal,
  32354. equals: equals,
  32355. equirectUV: equirectUV,
  32356. exp: exp,
  32357. exp2: exp2,
  32358. expression: expression,
  32359. faceDirection: faceDirection,
  32360. faceForward: faceForward,
  32361. faceforward: faceforward,
  32362. float: float,
  32363. floatBitsToInt: floatBitsToInt,
  32364. floatBitsToUint: floatBitsToUint,
  32365. floor: floor,
  32366. fog: fog,
  32367. fract: fract,
  32368. frameGroup: frameGroup,
  32369. frameId: frameId,
  32370. frontFacing: frontFacing,
  32371. fwidth: fwidth,
  32372. gain: gain,
  32373. gapSize: gapSize,
  32374. getConstNodeType: getConstNodeType,
  32375. getCurrentStack: getCurrentStack,
  32376. getDirection: getDirection,
  32377. getDistanceAttenuation: getDistanceAttenuation,
  32378. getGeometryRoughness: getGeometryRoughness,
  32379. getNormalFromDepth: getNormalFromDepth,
  32380. getParallaxCorrectNormal: getParallaxCorrectNormal,
  32381. getRoughness: getRoughness,
  32382. getScreenPosition: getScreenPosition,
  32383. getShIrradianceAt: getShIrradianceAt,
  32384. getShadowMaterial: getShadowMaterial,
  32385. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  32386. getTextureIndex: getTextureIndex,
  32387. getViewPosition: getViewPosition,
  32388. globalId: globalId,
  32389. glsl: glsl,
  32390. glslFn: glslFn,
  32391. grayscale: grayscale,
  32392. greaterThan: greaterThan,
  32393. greaterThanEqual: greaterThanEqual,
  32394. hash: hash,
  32395. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  32396. highpModelViewMatrix: highpModelViewMatrix,
  32397. hue: hue,
  32398. increment: increment,
  32399. incrementBefore: incrementBefore,
  32400. inspector: inspector,
  32401. instance: instance,
  32402. instanceIndex: instanceIndex,
  32403. instancedArray: instancedArray,
  32404. instancedBufferAttribute: instancedBufferAttribute,
  32405. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  32406. instancedMesh: instancedMesh,
  32407. int: int,
  32408. intBitsToFloat: intBitsToFloat,
  32409. inverse: inverse,
  32410. inverseSqrt: inverseSqrt,
  32411. inversesqrt: inversesqrt,
  32412. invocationLocalIndex: invocationLocalIndex,
  32413. invocationSubgroupIndex: invocationSubgroupIndex,
  32414. ior: ior,
  32415. iridescence: iridescence,
  32416. iridescenceIOR: iridescenceIOR,
  32417. iridescenceThickness: iridescenceThickness,
  32418. isolate: isolate,
  32419. ivec2: ivec2,
  32420. ivec3: ivec3,
  32421. ivec4: ivec4,
  32422. js: js,
  32423. label: label,
  32424. length: length,
  32425. lengthSq: lengthSq,
  32426. lessThan: lessThan,
  32427. lessThanEqual: lessThanEqual,
  32428. lightPosition: lightPosition,
  32429. lightProjectionUV: lightProjectionUV,
  32430. lightShadowMatrix: lightShadowMatrix,
  32431. lightTargetDirection: lightTargetDirection,
  32432. lightTargetPosition: lightTargetPosition,
  32433. lightViewPosition: lightViewPosition,
  32434. lightingContext: lightingContext,
  32435. lights: lights,
  32436. linearDepth: linearDepth,
  32437. linearToneMapping: linearToneMapping,
  32438. localId: localId,
  32439. log: log,
  32440. log2: log2,
  32441. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  32442. luminance: luminance,
  32443. mat2: mat2,
  32444. mat3: mat3,
  32445. mat4: mat4,
  32446. matcapUV: matcapUV,
  32447. materialAO: materialAO,
  32448. materialAlphaTest: materialAlphaTest,
  32449. materialAnisotropy: materialAnisotropy,
  32450. materialAnisotropyVector: materialAnisotropyVector,
  32451. materialAttenuationColor: materialAttenuationColor,
  32452. materialAttenuationDistance: materialAttenuationDistance,
  32453. materialClearcoat: materialClearcoat,
  32454. materialClearcoatNormal: materialClearcoatNormal,
  32455. materialClearcoatRoughness: materialClearcoatRoughness,
  32456. materialColor: materialColor,
  32457. materialDispersion: materialDispersion,
  32458. materialEmissive: materialEmissive,
  32459. materialEnvIntensity: materialEnvIntensity,
  32460. materialEnvRotation: materialEnvRotation,
  32461. materialIOR: materialIOR,
  32462. materialIridescence: materialIridescence,
  32463. materialIridescenceIOR: materialIridescenceIOR,
  32464. materialIridescenceThickness: materialIridescenceThickness,
  32465. materialLightMap: materialLightMap,
  32466. materialLineDashOffset: materialLineDashOffset,
  32467. materialLineDashSize: materialLineDashSize,
  32468. materialLineGapSize: materialLineGapSize,
  32469. materialLineScale: materialLineScale,
  32470. materialLineWidth: materialLineWidth,
  32471. materialMetalness: materialMetalness,
  32472. materialNormal: materialNormal,
  32473. materialOpacity: materialOpacity,
  32474. materialPointSize: materialPointSize,
  32475. materialReference: materialReference,
  32476. materialReflectivity: materialReflectivity,
  32477. materialRefractionRatio: materialRefractionRatio,
  32478. materialRotation: materialRotation,
  32479. materialRoughness: materialRoughness,
  32480. materialSheen: materialSheen,
  32481. materialSheenRoughness: materialSheenRoughness,
  32482. materialShininess: materialShininess,
  32483. materialSpecular: materialSpecular,
  32484. materialSpecularColor: materialSpecularColor,
  32485. materialSpecularIntensity: materialSpecularIntensity,
  32486. materialSpecularStrength: materialSpecularStrength,
  32487. materialThickness: materialThickness,
  32488. materialTransmission: materialTransmission,
  32489. max: max$1,
  32490. maxMipLevel: maxMipLevel,
  32491. mediumpModelViewMatrix: mediumpModelViewMatrix,
  32492. metalness: metalness,
  32493. min: min$1,
  32494. mix: mix,
  32495. mixElement: mixElement,
  32496. mod: mod,
  32497. modInt: modInt,
  32498. modelDirection: modelDirection,
  32499. modelNormalMatrix: modelNormalMatrix,
  32500. modelPosition: modelPosition,
  32501. modelRadius: modelRadius,
  32502. modelScale: modelScale,
  32503. modelViewMatrix: modelViewMatrix,
  32504. modelViewPosition: modelViewPosition,
  32505. modelViewProjection: modelViewProjection,
  32506. modelWorldMatrix: modelWorldMatrix,
  32507. modelWorldMatrixInverse: modelWorldMatrixInverse,
  32508. morphReference: morphReference,
  32509. mrt: mrt,
  32510. mul: mul,
  32511. mx_aastep: mx_aastep,
  32512. mx_add: mx_add,
  32513. mx_atan2: mx_atan2,
  32514. mx_cell_noise_float: mx_cell_noise_float,
  32515. mx_contrast: mx_contrast,
  32516. mx_divide: mx_divide,
  32517. mx_fractal_noise_float: mx_fractal_noise_float,
  32518. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  32519. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  32520. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  32521. mx_frame: mx_frame,
  32522. mx_heighttonormal: mx_heighttonormal,
  32523. mx_hsvtorgb: mx_hsvtorgb,
  32524. mx_ifequal: mx_ifequal,
  32525. mx_ifgreater: mx_ifgreater,
  32526. mx_ifgreatereq: mx_ifgreatereq,
  32527. mx_invert: mx_invert,
  32528. mx_modulo: mx_modulo,
  32529. mx_multiply: mx_multiply,
  32530. mx_noise_float: mx_noise_float,
  32531. mx_noise_vec3: mx_noise_vec3,
  32532. mx_noise_vec4: mx_noise_vec4,
  32533. mx_place2d: mx_place2d,
  32534. mx_power: mx_power,
  32535. mx_ramp4: mx_ramp4,
  32536. mx_ramplr: mx_ramplr,
  32537. mx_ramptb: mx_ramptb,
  32538. mx_rgbtohsv: mx_rgbtohsv,
  32539. mx_rotate2d: mx_rotate2d,
  32540. mx_rotate3d: mx_rotate3d,
  32541. mx_safepower: mx_safepower,
  32542. mx_separate: mx_separate,
  32543. mx_splitlr: mx_splitlr,
  32544. mx_splittb: mx_splittb,
  32545. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  32546. mx_subtract: mx_subtract,
  32547. mx_timer: mx_timer,
  32548. mx_transform_uv: mx_transform_uv,
  32549. mx_unifiednoise2d: mx_unifiednoise2d,
  32550. mx_unifiednoise3d: mx_unifiednoise3d,
  32551. mx_worley_noise_float: mx_worley_noise_float,
  32552. mx_worley_noise_vec2: mx_worley_noise_vec2,
  32553. mx_worley_noise_vec3: mx_worley_noise_vec3,
  32554. negate: negate,
  32555. neutralToneMapping: neutralToneMapping,
  32556. nodeArray: nodeArray,
  32557. nodeImmutable: nodeImmutable,
  32558. nodeObject: nodeObject,
  32559. nodeObjectIntent: nodeObjectIntent,
  32560. nodeObjects: nodeObjects,
  32561. nodeProxy: nodeProxy,
  32562. nodeProxyIntent: nodeProxyIntent,
  32563. normalFlat: normalFlat,
  32564. normalGeometry: normalGeometry,
  32565. normalLocal: normalLocal,
  32566. normalMap: normalMap,
  32567. normalView: normalView,
  32568. normalViewGeometry: normalViewGeometry,
  32569. normalWorld: normalWorld,
  32570. normalWorldGeometry: normalWorldGeometry,
  32571. normalize: normalize,
  32572. not: not,
  32573. notEqual: notEqual,
  32574. numWorkgroups: numWorkgroups,
  32575. objectDirection: objectDirection,
  32576. objectGroup: objectGroup,
  32577. objectPosition: objectPosition,
  32578. objectRadius: objectRadius,
  32579. objectScale: objectScale,
  32580. objectViewPosition: objectViewPosition,
  32581. objectWorldMatrix: objectWorldMatrix,
  32582. oneMinus: oneMinus,
  32583. or: or,
  32584. orthographicDepthToViewZ: orthographicDepthToViewZ,
  32585. oscSawtooth: oscSawtooth,
  32586. oscSine: oscSine,
  32587. oscSquare: oscSquare,
  32588. oscTriangle: oscTriangle,
  32589. output: output,
  32590. outputStruct: outputStruct,
  32591. overlay: overlay,
  32592. overloadingFn: overloadingFn,
  32593. parabola: parabola,
  32594. parallaxDirection: parallaxDirection,
  32595. parallaxUV: parallaxUV,
  32596. parameter: parameter,
  32597. pass: pass,
  32598. passTexture: passTexture,
  32599. pcurve: pcurve,
  32600. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  32601. pmremTexture: pmremTexture,
  32602. pointShadow: pointShadow,
  32603. pointUV: pointUV,
  32604. pointWidth: pointWidth,
  32605. positionGeometry: positionGeometry,
  32606. positionLocal: positionLocal,
  32607. positionPrevious: positionPrevious,
  32608. positionView: positionView,
  32609. positionViewDirection: positionViewDirection,
  32610. positionWorld: positionWorld,
  32611. positionWorldDirection: positionWorldDirection,
  32612. posterize: posterize,
  32613. pow: pow,
  32614. pow2: pow2,
  32615. pow3: pow3,
  32616. pow4: pow4,
  32617. premultiplyAlpha: premultiplyAlpha,
  32618. property: property,
  32619. quadBroadcast: quadBroadcast,
  32620. quadSwapDiagonal: quadSwapDiagonal,
  32621. quadSwapX: quadSwapX,
  32622. quadSwapY: quadSwapY,
  32623. radians: radians,
  32624. rand: rand,
  32625. range: range,
  32626. rangeFog: rangeFog,
  32627. rangeFogFactor: rangeFogFactor,
  32628. reciprocal: reciprocal,
  32629. reference: reference,
  32630. referenceBuffer: referenceBuffer,
  32631. reflect: reflect,
  32632. reflectVector: reflectVector,
  32633. reflectView: reflectView,
  32634. reflector: reflector,
  32635. refract: refract,
  32636. refractVector: refractVector,
  32637. refractView: refractView,
  32638. reinhardToneMapping: reinhardToneMapping,
  32639. remap: remap,
  32640. remapClamp: remapClamp,
  32641. renderGroup: renderGroup,
  32642. renderOutput: renderOutput,
  32643. rendererReference: rendererReference,
  32644. rotate: rotate,
  32645. rotateUV: rotateUV,
  32646. roughness: roughness,
  32647. round: round,
  32648. rtt: rtt,
  32649. sRGBTransferEOTF: sRGBTransferEOTF,
  32650. sRGBTransferOETF: sRGBTransferOETF,
  32651. sample: sample,
  32652. sampler: sampler,
  32653. samplerComparison: samplerComparison,
  32654. saturate: saturate,
  32655. saturation: saturation,
  32656. screen: screen,
  32657. screenCoordinate: screenCoordinate,
  32658. screenDPR: screenDPR,
  32659. screenSize: screenSize,
  32660. screenUV: screenUV,
  32661. scriptable: scriptable,
  32662. scriptableValue: scriptableValue,
  32663. select: select,
  32664. setCurrentStack: setCurrentStack,
  32665. setName: setName,
  32666. shaderStages: shaderStages,
  32667. shadow: shadow,
  32668. shadowPositionWorld: shadowPositionWorld,
  32669. shapeCircle: shapeCircle,
  32670. sharedUniformGroup: sharedUniformGroup,
  32671. sheen: sheen,
  32672. sheenRoughness: sheenRoughness,
  32673. shiftLeft: shiftLeft,
  32674. shiftRight: shiftRight,
  32675. shininess: shininess,
  32676. sign: sign,
  32677. sin: sin,
  32678. sinc: sinc,
  32679. skinning: skinning,
  32680. smoothstep: smoothstep,
  32681. smoothstepElement: smoothstepElement,
  32682. specularColor: specularColor,
  32683. specularF90: specularF90,
  32684. spherizeUV: spherizeUV,
  32685. split: split,
  32686. spritesheetUV: spritesheetUV,
  32687. sqrt: sqrt,
  32688. stack: stack,
  32689. step: step,
  32690. stepElement: stepElement,
  32691. storage: storage,
  32692. storageBarrier: storageBarrier,
  32693. storageObject: storageObject,
  32694. storageTexture: storageTexture,
  32695. string: string,
  32696. struct: struct,
  32697. sub: sub,
  32698. subBuild: subBuild,
  32699. subgroupAdd: subgroupAdd,
  32700. subgroupAll: subgroupAll,
  32701. subgroupAnd: subgroupAnd,
  32702. subgroupAny: subgroupAny,
  32703. subgroupBallot: subgroupBallot,
  32704. subgroupBroadcast: subgroupBroadcast,
  32705. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32706. subgroupElect: subgroupElect,
  32707. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32708. subgroupExclusiveMul: subgroupExclusiveMul,
  32709. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32710. subgroupInclusiveMul: subgroupInclusiveMul,
  32711. subgroupIndex: subgroupIndex,
  32712. subgroupMax: subgroupMax,
  32713. subgroupMin: subgroupMin,
  32714. subgroupMul: subgroupMul,
  32715. subgroupOr: subgroupOr,
  32716. subgroupShuffle: subgroupShuffle,
  32717. subgroupShuffleDown: subgroupShuffleDown,
  32718. subgroupShuffleUp: subgroupShuffleUp,
  32719. subgroupShuffleXor: subgroupShuffleXor,
  32720. subgroupSize: subgroupSize,
  32721. subgroupXor: subgroupXor,
  32722. tan: tan,
  32723. tangentGeometry: tangentGeometry,
  32724. tangentLocal: tangentLocal,
  32725. tangentView: tangentView,
  32726. tangentWorld: tangentWorld,
  32727. texture: texture,
  32728. texture3D: texture3D,
  32729. textureBarrier: textureBarrier,
  32730. textureBicubic: textureBicubic,
  32731. textureBicubicLevel: textureBicubicLevel,
  32732. textureCubeUV: textureCubeUV,
  32733. textureLevel: textureLevel,
  32734. textureLoad: textureLoad,
  32735. textureSize: textureSize,
  32736. textureStore: textureStore,
  32737. thickness: thickness,
  32738. time: time,
  32739. toneMapping: toneMapping,
  32740. toneMappingExposure: toneMappingExposure,
  32741. toonOutlinePass: toonOutlinePass,
  32742. transformDirection: transformDirection,
  32743. transformNormal: transformNormal,
  32744. transformNormalToView: transformNormalToView,
  32745. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32746. transformedNormalView: transformedNormalView,
  32747. transformedNormalWorld: transformedNormalWorld,
  32748. transmission: transmission,
  32749. transpose: transpose,
  32750. triNoise3D: triNoise3D,
  32751. triplanarTexture: triplanarTexture,
  32752. triplanarTextures: triplanarTextures,
  32753. trunc: trunc,
  32754. uint: uint,
  32755. uintBitsToFloat: uintBitsToFloat,
  32756. uniform: uniform,
  32757. uniformArray: uniformArray,
  32758. uniformCubeTexture: uniformCubeTexture,
  32759. uniformFlow: uniformFlow,
  32760. uniformGroup: uniformGroup,
  32761. uniformTexture: uniformTexture,
  32762. unpremultiplyAlpha: unpremultiplyAlpha,
  32763. userData: userData,
  32764. uv: uv$1,
  32765. uvec2: uvec2,
  32766. uvec3: uvec3,
  32767. uvec4: uvec4,
  32768. varying: varying,
  32769. varyingProperty: varyingProperty,
  32770. vec2: vec2,
  32771. vec3: vec3,
  32772. vec4: vec4,
  32773. vectorComponents: vectorComponents,
  32774. velocity: velocity,
  32775. vertexColor: vertexColor,
  32776. vertexIndex: vertexIndex,
  32777. vertexStage: vertexStage,
  32778. vibrance: vibrance,
  32779. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32780. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32781. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32782. viewport: viewport,
  32783. viewportCoordinate: viewportCoordinate,
  32784. viewportDepthTexture: viewportDepthTexture,
  32785. viewportLinearDepth: viewportLinearDepth,
  32786. viewportMipTexture: viewportMipTexture,
  32787. viewportResolution: viewportResolution,
  32788. viewportSafeUV: viewportSafeUV,
  32789. viewportSharedTexture: viewportSharedTexture,
  32790. viewportSize: viewportSize,
  32791. viewportTexture: viewportTexture,
  32792. viewportUV: viewportUV,
  32793. wgsl: wgsl,
  32794. wgslFn: wgslFn,
  32795. workgroupArray: workgroupArray,
  32796. workgroupBarrier: workgroupBarrier,
  32797. workgroupId: workgroupId,
  32798. workingToColorSpace: workingToColorSpace,
  32799. xor: xor
  32800. });
  32801. const _clearColor = /*@__PURE__*/ new Color4();
  32802. /**
  32803. * This renderer module manages the background.
  32804. *
  32805. * @private
  32806. * @augments DataMap
  32807. */
  32808. class Background extends DataMap {
  32809. /**
  32810. * Constructs a new background management component.
  32811. *
  32812. * @param {Renderer} renderer - The renderer.
  32813. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  32814. */
  32815. constructor( renderer, nodes ) {
  32816. super();
  32817. /**
  32818. * The renderer.
  32819. *
  32820. * @type {Renderer}
  32821. */
  32822. this.renderer = renderer;
  32823. /**
  32824. * Renderer component for managing nodes related logic.
  32825. *
  32826. * @type {Nodes}
  32827. */
  32828. this.nodes = nodes;
  32829. }
  32830. /**
  32831. * Updates the background for the given scene. Depending on how `Scene.background`
  32832. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  32833. * or add a mesh to the render list for rendering the background as a textured plane
  32834. * or skybox.
  32835. *
  32836. * @param {Scene} scene - The scene.
  32837. * @param {RenderList} renderList - The current render list.
  32838. * @param {RenderContext} renderContext - The current render context.
  32839. */
  32840. update( scene, renderList, renderContext ) {
  32841. const renderer = this.renderer;
  32842. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  32843. let forceClear = false;
  32844. if ( background === null ) {
  32845. // no background settings, use clear color configuration from the renderer
  32846. renderer._clearColor.getRGB( _clearColor );
  32847. _clearColor.a = renderer._clearColor.a;
  32848. } else if ( background.isColor === true ) {
  32849. // background is an opaque color
  32850. background.getRGB( _clearColor );
  32851. _clearColor.a = 1;
  32852. forceClear = true;
  32853. } else if ( background.isNode === true ) {
  32854. const sceneData = this.get( scene );
  32855. const backgroundNode = background;
  32856. _clearColor.copy( renderer._clearColor );
  32857. let backgroundMesh = sceneData.backgroundMesh;
  32858. if ( backgroundMesh === undefined ) {
  32859. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  32860. // @TODO: Add Texture2D support using node context
  32861. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  32862. getTextureLevel: () => backgroundBlurriness
  32863. } );
  32864. let viewProj = modelViewProjection;
  32865. viewProj = viewProj.setZ( viewProj.w );
  32866. const nodeMaterial = new NodeMaterial();
  32867. nodeMaterial.name = 'Background.material';
  32868. nodeMaterial.side = BackSide;
  32869. nodeMaterial.depthTest = false;
  32870. nodeMaterial.depthWrite = false;
  32871. nodeMaterial.allowOverride = false;
  32872. nodeMaterial.fog = false;
  32873. nodeMaterial.lights = false;
  32874. nodeMaterial.vertexNode = viewProj;
  32875. nodeMaterial.colorNode = backgroundMeshNode;
  32876. sceneData.backgroundMeshNode = backgroundMeshNode;
  32877. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  32878. backgroundMesh.frustumCulled = false;
  32879. backgroundMesh.name = 'Background.mesh';
  32880. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  32881. this.matrixWorld.copyPosition( camera.matrixWorld );
  32882. };
  32883. function onBackgroundDispose() {
  32884. background.removeEventListener( 'dispose', onBackgroundDispose );
  32885. backgroundMesh.material.dispose();
  32886. backgroundMesh.geometry.dispose();
  32887. }
  32888. background.addEventListener( 'dispose', onBackgroundDispose );
  32889. }
  32890. const backgroundCacheKey = backgroundNode.getCacheKey();
  32891. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  32892. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  32893. sceneData.backgroundMeshNode.needsUpdate = true;
  32894. backgroundMesh.material.needsUpdate = true;
  32895. sceneData.backgroundCacheKey = backgroundCacheKey;
  32896. }
  32897. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  32898. } else {
  32899. error( 'Renderer: Unsupported background configuration.', background );
  32900. }
  32901. //
  32902. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  32903. if ( environmentBlendMode === 'additive' ) {
  32904. _clearColor.set( 0, 0, 0, 1 );
  32905. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32906. _clearColor.set( 0, 0, 0, 0 );
  32907. }
  32908. //
  32909. if ( renderer.autoClear === true || forceClear === true ) {
  32910. const clearColorValue = renderContext.clearColorValue;
  32911. clearColorValue.r = _clearColor.r;
  32912. clearColorValue.g = _clearColor.g;
  32913. clearColorValue.b = _clearColor.b;
  32914. clearColorValue.a = _clearColor.a;
  32915. // premultiply alpha
  32916. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32917. clearColorValue.r *= clearColorValue.a;
  32918. clearColorValue.g *= clearColorValue.a;
  32919. clearColorValue.b *= clearColorValue.a;
  32920. }
  32921. //
  32922. renderContext.depthClearValue = renderer._clearDepth;
  32923. renderContext.stencilClearValue = renderer._clearStencil;
  32924. renderContext.clearColor = renderer.autoClearColor === true;
  32925. renderContext.clearDepth = renderer.autoClearDepth === true;
  32926. renderContext.clearStencil = renderer.autoClearStencil === true;
  32927. } else {
  32928. renderContext.clearColor = false;
  32929. renderContext.clearDepth = false;
  32930. renderContext.clearStencil = false;
  32931. }
  32932. }
  32933. }
  32934. let _id$6 = 0;
  32935. /**
  32936. * A bind group represents a collection of bindings and thus a collection
  32937. * or resources. Bind groups are assigned to pipelines to provide them
  32938. * with the required resources (like uniform buffers or textures).
  32939. *
  32940. * @private
  32941. */
  32942. class BindGroup {
  32943. /**
  32944. * Constructs a new bind group.
  32945. *
  32946. * @param {string} name - The bind group's name.
  32947. * @param {Array<Binding>} bindings - An array of bindings.
  32948. * @param {number} index - The group index.
  32949. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32950. */
  32951. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32952. /**
  32953. * The bind group's name.
  32954. *
  32955. * @type {string}
  32956. */
  32957. this.name = name;
  32958. /**
  32959. * An array of bindings.
  32960. *
  32961. * @type {Array<Binding>}
  32962. */
  32963. this.bindings = bindings;
  32964. /**
  32965. * The group index.
  32966. *
  32967. * @type {number}
  32968. */
  32969. this.index = index;
  32970. /**
  32971. * An array of reference bindings.
  32972. *
  32973. * @type {Array<Binding>}
  32974. */
  32975. this.bindingsReference = bindingsReference;
  32976. /**
  32977. * The group's ID.
  32978. *
  32979. * @type {number}
  32980. */
  32981. this.id = _id$6 ++;
  32982. }
  32983. }
  32984. /**
  32985. * This module represents the state of a node builder after it was
  32986. * used to build the nodes for a render object. The state holds the
  32987. * results of the build for further processing in the renderer.
  32988. *
  32989. * Render objects with identical cache keys share the same node builder state.
  32990. *
  32991. * @private
  32992. */
  32993. class NodeBuilderState {
  32994. /**
  32995. * Constructs a new node builder state.
  32996. *
  32997. * @param {string} vertexShader - The native vertex shader code.
  32998. * @param {string} fragmentShader - The native fragment shader code.
  32999. * @param {string} computeShader - The native compute shader code.
  33000. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  33001. * @param {Array<BindGroup>} bindings - An array of bind groups.
  33002. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  33003. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  33004. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  33005. * @param {NodeMaterialObserver} observer - A node material observer.
  33006. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  33007. */
  33008. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  33009. /**
  33010. * The native vertex shader code.
  33011. *
  33012. * @type {string}
  33013. */
  33014. this.vertexShader = vertexShader;
  33015. /**
  33016. * The native fragment shader code.
  33017. *
  33018. * @type {string}
  33019. */
  33020. this.fragmentShader = fragmentShader;
  33021. /**
  33022. * The native compute shader code.
  33023. *
  33024. * @type {string}
  33025. */
  33026. this.computeShader = computeShader;
  33027. /**
  33028. * An array with transform attribute objects.
  33029. * Only relevant when using compute shaders with WebGL 2.
  33030. *
  33031. * @type {Array<Object>}
  33032. */
  33033. this.transforms = transforms;
  33034. /**
  33035. * An array of node attributes representing
  33036. * the attributes of the shaders.
  33037. *
  33038. * @type {Array<NodeAttribute>}
  33039. */
  33040. this.nodeAttributes = nodeAttributes;
  33041. /**
  33042. * An array of bind groups representing the uniform or storage
  33043. * buffers, texture or samplers of the shader.
  33044. *
  33045. * @type {Array<BindGroup>}
  33046. */
  33047. this.bindings = bindings;
  33048. /**
  33049. * An array of nodes that implement their `update()` method.
  33050. *
  33051. * @type {Array<Node>}
  33052. */
  33053. this.updateNodes = updateNodes;
  33054. /**
  33055. * An array of nodes that implement their `updateBefore()` method.
  33056. *
  33057. * @type {Array<Node>}
  33058. */
  33059. this.updateBeforeNodes = updateBeforeNodes;
  33060. /**
  33061. * An array of nodes that implement their `updateAfter()` method.
  33062. *
  33063. * @type {Array<Node>}
  33064. */
  33065. this.updateAfterNodes = updateAfterNodes;
  33066. /**
  33067. * A node material observer.
  33068. *
  33069. * @type {NodeMaterialObserver}
  33070. */
  33071. this.observer = observer;
  33072. /**
  33073. * How often this state is used by render objects.
  33074. *
  33075. * @type {number}
  33076. */
  33077. this.usedTimes = 0;
  33078. }
  33079. /**
  33080. * This method is used to create a array of bind groups based
  33081. * on the existing bind groups of this state. Shared groups are
  33082. * not cloned.
  33083. *
  33084. * @return {Array<BindGroup>} A array of bind groups.
  33085. */
  33086. createBindings() {
  33087. const bindings = [];
  33088. for ( const instanceGroup of this.bindings ) {
  33089. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  33090. if ( shared !== true ) {
  33091. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  33092. bindings.push( bindingsGroup );
  33093. for ( const instanceBinding of instanceGroup.bindings ) {
  33094. bindingsGroup.bindings.push( instanceBinding.clone() );
  33095. }
  33096. } else {
  33097. bindings.push( instanceGroup );
  33098. }
  33099. }
  33100. return bindings;
  33101. }
  33102. }
  33103. /**
  33104. * {@link NodeBuilder} is going to create instances of this class during the build process
  33105. * of nodes. They represent the final shader attributes that are going to be generated
  33106. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  33107. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  33108. */
  33109. class NodeAttribute {
  33110. /**
  33111. * Constructs a new node attribute.
  33112. *
  33113. * @param {string} name - The name of the attribute.
  33114. * @param {string} type - The type of the attribute.
  33115. * @param {?Node} node - An optional reference to the node.
  33116. */
  33117. constructor( name, type, node = null ) {
  33118. /**
  33119. * This flag can be used for type testing.
  33120. *
  33121. * @type {boolean}
  33122. * @readonly
  33123. * @default true
  33124. */
  33125. this.isNodeAttribute = true;
  33126. /**
  33127. * The name of the attribute.
  33128. *
  33129. * @type {string}
  33130. */
  33131. this.name = name;
  33132. /**
  33133. * The type of the attribute.
  33134. *
  33135. * @type {string}
  33136. */
  33137. this.type = type;
  33138. /**
  33139. * An optional reference to the node.
  33140. *
  33141. * @type {?Node}
  33142. * @default null
  33143. */
  33144. this.node = node;
  33145. }
  33146. }
  33147. /**
  33148. * {@link NodeBuilder} is going to create instances of this class during the build process
  33149. * of nodes. They represent the final shader uniforms that are going to be generated
  33150. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  33151. * for this purpose.
  33152. */
  33153. class NodeUniform {
  33154. /**
  33155. * Constructs a new node uniform.
  33156. *
  33157. * @param {string} name - The name of the uniform.
  33158. * @param {string} type - The type of the uniform.
  33159. * @param {UniformNode} node - An reference to the node.
  33160. */
  33161. constructor( name, type, node ) {
  33162. /**
  33163. * This flag can be used for type testing.
  33164. *
  33165. * @type {boolean}
  33166. * @readonly
  33167. * @default true
  33168. */
  33169. this.isNodeUniform = true;
  33170. /**
  33171. * The name of the uniform.
  33172. *
  33173. * @type {string}
  33174. */
  33175. this.name = name;
  33176. /**
  33177. * The type of the uniform.
  33178. *
  33179. * @type {string}
  33180. */
  33181. this.type = type;
  33182. /**
  33183. * An reference to the node.
  33184. *
  33185. * @type {UniformNode}
  33186. */
  33187. this.node = node;
  33188. }
  33189. /**
  33190. * The value of the uniform node.
  33191. *
  33192. * @type {any}
  33193. */
  33194. get value() {
  33195. return this.node.value;
  33196. }
  33197. set value( val ) {
  33198. this.node.value = val;
  33199. }
  33200. /**
  33201. * The id of the uniform node.
  33202. *
  33203. * @type {number}
  33204. */
  33205. get id() {
  33206. return this.node.id;
  33207. }
  33208. /**
  33209. * The uniform node's group.
  33210. *
  33211. * @type {UniformGroupNode}
  33212. */
  33213. get groupNode() {
  33214. return this.node.groupNode;
  33215. }
  33216. }
  33217. /**
  33218. * {@link NodeBuilder} is going to create instances of this class during the build process
  33219. * of nodes. They represent the final shader variables that are going to be generated
  33220. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  33221. * this purpose.
  33222. */
  33223. class NodeVar {
  33224. /**
  33225. * Constructs a new node variable.
  33226. *
  33227. * @param {string} name - The name of the variable.
  33228. * @param {string} type - The type of the variable.
  33229. * @param {boolean} [readOnly=false] - The read-only flag.
  33230. * @param {?number} [count=null] - The size.
  33231. */
  33232. constructor( name, type, readOnly = false, count = null ) {
  33233. /**
  33234. * This flag can be used for type testing.
  33235. *
  33236. * @type {boolean}
  33237. * @readonly
  33238. * @default true
  33239. */
  33240. this.isNodeVar = true;
  33241. /**
  33242. * The name of the variable.
  33243. *
  33244. * @type {string}
  33245. */
  33246. this.name = name;
  33247. /**
  33248. * The type of the variable.
  33249. *
  33250. * @type {string}
  33251. */
  33252. this.type = type;
  33253. /**
  33254. * The read-only flag.
  33255. *
  33256. * @type {boolean}
  33257. */
  33258. this.readOnly = readOnly;
  33259. /**
  33260. * The size.
  33261. *
  33262. * @type {?number}
  33263. */
  33264. this.count = count;
  33265. }
  33266. }
  33267. /**
  33268. * {@link NodeBuilder} is going to create instances of this class during the build process
  33269. * of nodes. They represent the final shader varyings that are going to be generated
  33270. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  33271. * this purpose.
  33272. *
  33273. * @augments NodeVar
  33274. */
  33275. class NodeVarying extends NodeVar {
  33276. /**
  33277. * Constructs a new node varying.
  33278. *
  33279. * @param {string} name - The name of the varying.
  33280. * @param {string} type - The type of the varying.
  33281. * @param {?string} interpolationType - The interpolation type of the varying.
  33282. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33283. */
  33284. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  33285. super( name, type );
  33286. /**
  33287. * Whether this varying requires interpolation or not. This property can be used
  33288. * to check if the varying can be optimized for a variable.
  33289. *
  33290. * @type {boolean}
  33291. * @default false
  33292. */
  33293. this.needsInterpolation = false;
  33294. /**
  33295. * This flag can be used for type testing.
  33296. *
  33297. * @type {boolean}
  33298. * @readonly
  33299. * @default true
  33300. */
  33301. this.isNodeVarying = true;
  33302. /**
  33303. * The interpolation type of the varying data.
  33304. *
  33305. * @type {?string}
  33306. * @default null
  33307. */
  33308. this.interpolationType = interpolationType;
  33309. /**
  33310. * The interpolation sampling type of varying data.
  33311. *
  33312. * @type {?string}
  33313. * @default null
  33314. */
  33315. this.interpolationSampling = interpolationSampling;
  33316. }
  33317. }
  33318. /**
  33319. * {@link NodeBuilder} is going to create instances of this class during the build process
  33320. * of nodes. They represent user-defined, native shader code portions that are going to be
  33321. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  33322. * for this purpose.
  33323. */
  33324. class NodeCode {
  33325. /**
  33326. * Constructs a new code node.
  33327. *
  33328. * @param {string} name - The name of the code.
  33329. * @param {string} type - The node type.
  33330. * @param {string} [code=''] - The native shader code.
  33331. */
  33332. constructor( name, type, code = '' ) {
  33333. /**
  33334. * The name of the code.
  33335. *
  33336. * @type {string}
  33337. */
  33338. this.name = name;
  33339. /**
  33340. * The node type.
  33341. *
  33342. * @type {string}
  33343. */
  33344. this.type = type;
  33345. /**
  33346. * The native shader code.
  33347. *
  33348. * @type {string}
  33349. * @default ''
  33350. */
  33351. this.code = code;
  33352. Object.defineProperty( this, 'isNodeCode', { value: true } );
  33353. }
  33354. }
  33355. let _id$5 = 0;
  33356. /**
  33357. * This utility class is used in {@link NodeBuilder} as an internal
  33358. * cache data structure for node data.
  33359. */
  33360. class NodeCache {
  33361. /**
  33362. * Constructs a new node cache.
  33363. *
  33364. * @param {?NodeCache} parent - A reference to a parent cache.
  33365. */
  33366. constructor( parent = null ) {
  33367. /**
  33368. * The id of the cache.
  33369. *
  33370. * @type {number}
  33371. * @readonly
  33372. */
  33373. this.id = _id$5 ++;
  33374. /**
  33375. * A weak map for managing node data.
  33376. *
  33377. * @type {WeakMap<Node, Object>}
  33378. */
  33379. this.nodesData = new WeakMap();
  33380. /**
  33381. * Reference to a parent node cache.
  33382. *
  33383. * @type {?NodeCache}
  33384. * @default null
  33385. */
  33386. this.parent = parent;
  33387. }
  33388. /**
  33389. * Returns the data for the given node.
  33390. *
  33391. * @param {Node} node - The node.
  33392. * @return {?Object} The data for the node.
  33393. */
  33394. getData( node ) {
  33395. let data = this.nodesData.get( node );
  33396. if ( data === undefined && this.parent !== null ) {
  33397. data = this.parent.getData( node );
  33398. }
  33399. return data;
  33400. }
  33401. /**
  33402. * Sets the data for a given node.
  33403. *
  33404. * @param {Node} node - The node.
  33405. * @param {Object} data - The data that should be cached.
  33406. */
  33407. setData( node, data ) {
  33408. this.nodesData.set( node, data );
  33409. }
  33410. }
  33411. class StructType {
  33412. constructor( name, members ) {
  33413. this.name = name;
  33414. this.members = members;
  33415. this.output = false;
  33416. }
  33417. }
  33418. /**
  33419. * Abstract base class for uniforms.
  33420. *
  33421. * @abstract
  33422. * @private
  33423. */
  33424. class Uniform {
  33425. /**
  33426. * Constructs a new uniform.
  33427. *
  33428. * @param {string} name - The uniform's name.
  33429. * @param {any} value - The uniform's value.
  33430. */
  33431. constructor( name, value ) {
  33432. /**
  33433. * The uniform's name.
  33434. *
  33435. * @type {string}
  33436. */
  33437. this.name = name;
  33438. /**
  33439. * The uniform's value.
  33440. *
  33441. * @type {any}
  33442. */
  33443. this.value = value;
  33444. /**
  33445. * Used to build the uniform buffer according to the STD140 layout.
  33446. * Derived uniforms will set this property to a data type specific
  33447. * value.
  33448. *
  33449. * @type {number}
  33450. */
  33451. this.boundary = 0;
  33452. /**
  33453. * The item size. Derived uniforms will set this property to a data
  33454. * type specific value.
  33455. *
  33456. * @type {number}
  33457. */
  33458. this.itemSize = 0;
  33459. /**
  33460. * This property is set by {@link UniformsGroup} and marks
  33461. * the start position in the uniform buffer.
  33462. *
  33463. * @type {number}
  33464. */
  33465. this.offset = 0;
  33466. }
  33467. /**
  33468. * Sets the uniform's value.
  33469. *
  33470. * @param {any} value - The value to set.
  33471. */
  33472. setValue( value ) {
  33473. this.value = value;
  33474. }
  33475. /**
  33476. * Returns the uniform's value.
  33477. *
  33478. * @return {any} The value.
  33479. */
  33480. getValue() {
  33481. return this.value;
  33482. }
  33483. }
  33484. /**
  33485. * Represents a Number uniform.
  33486. *
  33487. * @private
  33488. * @augments Uniform
  33489. */
  33490. class NumberUniform extends Uniform {
  33491. /**
  33492. * Constructs a new Number uniform.
  33493. *
  33494. * @param {string} name - The uniform's name.
  33495. * @param {number} value - The uniform's value.
  33496. */
  33497. constructor( name, value = 0 ) {
  33498. super( name, value );
  33499. /**
  33500. * This flag can be used for type testing.
  33501. *
  33502. * @type {boolean}
  33503. * @readonly
  33504. * @default true
  33505. */
  33506. this.isNumberUniform = true;
  33507. this.boundary = 4;
  33508. this.itemSize = 1;
  33509. }
  33510. }
  33511. /**
  33512. * Represents a Vector2 uniform.
  33513. *
  33514. * @private
  33515. * @augments Uniform
  33516. */
  33517. class Vector2Uniform extends Uniform {
  33518. /**
  33519. * Constructs a new Number uniform.
  33520. *
  33521. * @param {string} name - The uniform's name.
  33522. * @param {Vector2} value - The uniform's value.
  33523. */
  33524. constructor( name, value = new Vector2() ) {
  33525. super( name, value );
  33526. /**
  33527. * This flag can be used for type testing.
  33528. *
  33529. * @type {boolean}
  33530. * @readonly
  33531. * @default true
  33532. */
  33533. this.isVector2Uniform = true;
  33534. this.boundary = 8;
  33535. this.itemSize = 2;
  33536. }
  33537. }
  33538. /**
  33539. * Represents a Vector3 uniform.
  33540. *
  33541. * @private
  33542. * @augments Uniform
  33543. */
  33544. class Vector3Uniform extends Uniform {
  33545. /**
  33546. * Constructs a new Number uniform.
  33547. *
  33548. * @param {string} name - The uniform's name.
  33549. * @param {Vector3} value - The uniform's value.
  33550. */
  33551. constructor( name, value = new Vector3() ) {
  33552. super( name, value );
  33553. /**
  33554. * This flag can be used for type testing.
  33555. *
  33556. * @type {boolean}
  33557. * @readonly
  33558. * @default true
  33559. */
  33560. this.isVector3Uniform = true;
  33561. this.boundary = 16;
  33562. this.itemSize = 3;
  33563. }
  33564. }
  33565. /**
  33566. * Represents a Vector4 uniform.
  33567. *
  33568. * @private
  33569. * @augments Uniform
  33570. */
  33571. class Vector4Uniform extends Uniform {
  33572. /**
  33573. * Constructs a new Number uniform.
  33574. *
  33575. * @param {string} name - The uniform's name.
  33576. * @param {Vector4} value - The uniform's value.
  33577. */
  33578. constructor( name, value = new Vector4() ) {
  33579. super( name, value );
  33580. /**
  33581. * This flag can be used for type testing.
  33582. *
  33583. * @type {boolean}
  33584. * @readonly
  33585. * @default true
  33586. */
  33587. this.isVector4Uniform = true;
  33588. this.boundary = 16;
  33589. this.itemSize = 4;
  33590. }
  33591. }
  33592. /**
  33593. * Represents a Color uniform.
  33594. *
  33595. * @private
  33596. * @augments Uniform
  33597. */
  33598. class ColorUniform extends Uniform {
  33599. /**
  33600. * Constructs a new Number uniform.
  33601. *
  33602. * @param {string} name - The uniform's name.
  33603. * @param {Color} value - The uniform's value.
  33604. */
  33605. constructor( name, value = new Color() ) {
  33606. super( name, value );
  33607. /**
  33608. * This flag can be used for type testing.
  33609. *
  33610. * @type {boolean}
  33611. * @readonly
  33612. * @default true
  33613. */
  33614. this.isColorUniform = true;
  33615. this.boundary = 16;
  33616. this.itemSize = 3;
  33617. }
  33618. }
  33619. /**
  33620. * Represents a Matrix2 uniform.
  33621. *
  33622. * @private
  33623. * @augments Uniform
  33624. */
  33625. class Matrix2Uniform extends Uniform {
  33626. /**
  33627. * Constructs a new Number uniform.
  33628. *
  33629. * @param {string} name - The uniform's name.
  33630. * @param {Matrix2} value - The uniform's value.
  33631. */
  33632. constructor( name, value = new Matrix2() ) {
  33633. super( name, value );
  33634. /**
  33635. * This flag can be used for type testing.
  33636. *
  33637. * @type {boolean}
  33638. * @readonly
  33639. * @default true
  33640. */
  33641. this.isMatrix2Uniform = true;
  33642. this.boundary = 8;
  33643. this.itemSize = 4;
  33644. }
  33645. }
  33646. /**
  33647. * Represents a Matrix3 uniform.
  33648. *
  33649. * @private
  33650. * @augments Uniform
  33651. */
  33652. class Matrix3Uniform extends Uniform {
  33653. /**
  33654. * Constructs a new Number uniform.
  33655. *
  33656. * @param {string} name - The uniform's name.
  33657. * @param {Matrix3} value - The uniform's value.
  33658. */
  33659. constructor( name, value = new Matrix3() ) {
  33660. super( name, value );
  33661. /**
  33662. * This flag can be used for type testing.
  33663. *
  33664. * @type {boolean}
  33665. * @readonly
  33666. * @default true
  33667. */
  33668. this.isMatrix3Uniform = true;
  33669. this.boundary = 48;
  33670. this.itemSize = 12;
  33671. }
  33672. }
  33673. /**
  33674. * Represents a Matrix4 uniform.
  33675. *
  33676. * @private
  33677. * @augments Uniform
  33678. */
  33679. class Matrix4Uniform extends Uniform {
  33680. /**
  33681. * Constructs a new Number uniform.
  33682. *
  33683. * @param {string} name - The uniform's name.
  33684. * @param {Matrix4} value - The uniform's value.
  33685. */
  33686. constructor( name, value = new Matrix4() ) {
  33687. super( name, value );
  33688. /**
  33689. * This flag can be used for type testing.
  33690. *
  33691. * @type {boolean}
  33692. * @readonly
  33693. * @default true
  33694. */
  33695. this.isMatrix4Uniform = true;
  33696. this.boundary = 64;
  33697. this.itemSize = 16;
  33698. }
  33699. }
  33700. /**
  33701. * A special form of Number uniform binding type.
  33702. * It's value is managed by a node object.
  33703. *
  33704. * @private
  33705. * @augments NumberUniform
  33706. */
  33707. class NumberNodeUniform extends NumberUniform {
  33708. /**
  33709. * Constructs a new node-based Number uniform.
  33710. *
  33711. * @param {NodeUniform} nodeUniform - The node uniform.
  33712. */
  33713. constructor( nodeUniform ) {
  33714. super( nodeUniform.name, nodeUniform.value );
  33715. /**
  33716. * The node uniform.
  33717. *
  33718. * @type {NodeUniform}
  33719. */
  33720. this.nodeUniform = nodeUniform;
  33721. }
  33722. /**
  33723. * Overwritten to return the value of the node uniform.
  33724. *
  33725. * @return {number} The value.
  33726. */
  33727. getValue() {
  33728. return this.nodeUniform.value;
  33729. }
  33730. /**
  33731. * Returns the node uniform data type.
  33732. *
  33733. * @return {string} The data type.
  33734. */
  33735. getType() {
  33736. return this.nodeUniform.type;
  33737. }
  33738. }
  33739. /**
  33740. * A special form of Vector2 uniform binding type.
  33741. * It's value is managed by a node object.
  33742. *
  33743. * @private
  33744. * @augments Vector2Uniform
  33745. */
  33746. class Vector2NodeUniform extends Vector2Uniform {
  33747. /**
  33748. * Constructs a new node-based Vector2 uniform.
  33749. *
  33750. * @param {NodeUniform} nodeUniform - The node uniform.
  33751. */
  33752. constructor( nodeUniform ) {
  33753. super( nodeUniform.name, nodeUniform.value );
  33754. /**
  33755. * The node uniform.
  33756. *
  33757. * @type {NodeUniform}
  33758. */
  33759. this.nodeUniform = nodeUniform;
  33760. }
  33761. /**
  33762. * Overwritten to return the value of the node uniform.
  33763. *
  33764. * @return {Vector2} The value.
  33765. */
  33766. getValue() {
  33767. return this.nodeUniform.value;
  33768. }
  33769. /**
  33770. * Returns the node uniform data type.
  33771. *
  33772. * @return {string} The data type.
  33773. */
  33774. getType() {
  33775. return this.nodeUniform.type;
  33776. }
  33777. }
  33778. /**
  33779. * A special form of Vector3 uniform binding type.
  33780. * It's value is managed by a node object.
  33781. *
  33782. * @private
  33783. * @augments Vector3Uniform
  33784. */
  33785. class Vector3NodeUniform extends Vector3Uniform {
  33786. /**
  33787. * Constructs a new node-based Vector3 uniform.
  33788. *
  33789. * @param {NodeUniform} nodeUniform - The node uniform.
  33790. */
  33791. constructor( nodeUniform ) {
  33792. super( nodeUniform.name, nodeUniform.value );
  33793. /**
  33794. * The node uniform.
  33795. *
  33796. * @type {NodeUniform}
  33797. */
  33798. this.nodeUniform = nodeUniform;
  33799. }
  33800. /**
  33801. * Overwritten to return the value of the node uniform.
  33802. *
  33803. * @return {Vector3} The value.
  33804. */
  33805. getValue() {
  33806. return this.nodeUniform.value;
  33807. }
  33808. /**
  33809. * Returns the node uniform data type.
  33810. *
  33811. * @return {string} The data type.
  33812. */
  33813. getType() {
  33814. return this.nodeUniform.type;
  33815. }
  33816. }
  33817. /**
  33818. * A special form of Vector4 uniform binding type.
  33819. * It's value is managed by a node object.
  33820. *
  33821. * @private
  33822. * @augments Vector4Uniform
  33823. */
  33824. class Vector4NodeUniform extends Vector4Uniform {
  33825. /**
  33826. * Constructs a new node-based Vector4 uniform.
  33827. *
  33828. * @param {NodeUniform} nodeUniform - The node uniform.
  33829. */
  33830. constructor( nodeUniform ) {
  33831. super( nodeUniform.name, nodeUniform.value );
  33832. /**
  33833. * The node uniform.
  33834. *
  33835. * @type {NodeUniform}
  33836. */
  33837. this.nodeUniform = nodeUniform;
  33838. }
  33839. /**
  33840. * Overwritten to return the value of the node uniform.
  33841. *
  33842. * @return {Vector4} The value.
  33843. */
  33844. getValue() {
  33845. return this.nodeUniform.value;
  33846. }
  33847. /**
  33848. * Returns the node uniform data type.
  33849. *
  33850. * @return {string} The data type.
  33851. */
  33852. getType() {
  33853. return this.nodeUniform.type;
  33854. }
  33855. }
  33856. /**
  33857. * A special form of Color uniform binding type.
  33858. * It's value is managed by a node object.
  33859. *
  33860. * @private
  33861. * @augments ColorUniform
  33862. */
  33863. class ColorNodeUniform extends ColorUniform {
  33864. /**
  33865. * Constructs a new node-based Color uniform.
  33866. *
  33867. * @param {NodeUniform} nodeUniform - The node uniform.
  33868. */
  33869. constructor( nodeUniform ) {
  33870. super( nodeUniform.name, nodeUniform.value );
  33871. /**
  33872. * The node uniform.
  33873. *
  33874. * @type {NodeUniform}
  33875. */
  33876. this.nodeUniform = nodeUniform;
  33877. }
  33878. /**
  33879. * Overwritten to return the value of the node uniform.
  33880. *
  33881. * @return {Color} The value.
  33882. */
  33883. getValue() {
  33884. return this.nodeUniform.value;
  33885. }
  33886. /**
  33887. * Returns the node uniform data type.
  33888. *
  33889. * @return {string} The data type.
  33890. */
  33891. getType() {
  33892. return this.nodeUniform.type;
  33893. }
  33894. }
  33895. /**
  33896. * A special form of Matrix2 uniform binding type.
  33897. * It's value is managed by a node object.
  33898. *
  33899. * @private
  33900. * @augments Matrix2Uniform
  33901. */
  33902. class Matrix2NodeUniform extends Matrix2Uniform {
  33903. /**
  33904. * Constructs a new node-based Matrix2 uniform.
  33905. *
  33906. * @param {NodeUniform} nodeUniform - The node uniform.
  33907. */
  33908. constructor( nodeUniform ) {
  33909. super( nodeUniform.name, nodeUniform.value );
  33910. /**
  33911. * The node uniform.
  33912. *
  33913. * @type {NodeUniform}
  33914. */
  33915. this.nodeUniform = nodeUniform;
  33916. }
  33917. /**
  33918. * Overwritten to return the value of the node uniform.
  33919. *
  33920. * @return {Matrix2} The value.
  33921. */
  33922. getValue() {
  33923. return this.nodeUniform.value;
  33924. }
  33925. /**
  33926. * Returns the node uniform data type.
  33927. *
  33928. * @return {string} The data type.
  33929. */
  33930. getType() {
  33931. return this.nodeUniform.type;
  33932. }
  33933. }
  33934. /**
  33935. * A special form of Matrix3 uniform binding type.
  33936. * It's value is managed by a node object.
  33937. *
  33938. * @private
  33939. * @augments Matrix3Uniform
  33940. */
  33941. class Matrix3NodeUniform extends Matrix3Uniform {
  33942. /**
  33943. * Constructs a new node-based Matrix3 uniform.
  33944. *
  33945. * @param {NodeUniform} nodeUniform - The node uniform.
  33946. */
  33947. constructor( nodeUniform ) {
  33948. super( nodeUniform.name, nodeUniform.value );
  33949. /**
  33950. * The node uniform.
  33951. *
  33952. * @type {NodeUniform}
  33953. */
  33954. this.nodeUniform = nodeUniform;
  33955. }
  33956. /**
  33957. * Overwritten to return the value of the node uniform.
  33958. *
  33959. * @return {Matrix3} The value.
  33960. */
  33961. getValue() {
  33962. return this.nodeUniform.value;
  33963. }
  33964. /**
  33965. * Returns the node uniform data type.
  33966. *
  33967. * @return {string} The data type.
  33968. */
  33969. getType() {
  33970. return this.nodeUniform.type;
  33971. }
  33972. }
  33973. /**
  33974. * A special form of Matrix4 uniform binding type.
  33975. * It's value is managed by a node object.
  33976. *
  33977. * @private
  33978. * @augments Matrix4Uniform
  33979. */
  33980. class Matrix4NodeUniform extends Matrix4Uniform {
  33981. /**
  33982. * Constructs a new node-based Matrix4 uniform.
  33983. *
  33984. * @param {NodeUniform} nodeUniform - The node uniform.
  33985. */
  33986. constructor( nodeUniform ) {
  33987. super( nodeUniform.name, nodeUniform.value );
  33988. /**
  33989. * The node uniform.
  33990. *
  33991. * @type {NodeUniform}
  33992. */
  33993. this.nodeUniform = nodeUniform;
  33994. }
  33995. /**
  33996. * Overwritten to return the value of the node uniform.
  33997. *
  33998. * @return {Matrix4} The value.
  33999. */
  34000. getValue() {
  34001. return this.nodeUniform.value;
  34002. }
  34003. /**
  34004. * Returns the node uniform data type.
  34005. *
  34006. * @return {string} The data type.
  34007. */
  34008. getType() {
  34009. return this.nodeUniform.type;
  34010. }
  34011. }
  34012. const rendererCache = new WeakMap();
  34013. const typeFromArray = new Map( [
  34014. [ Int8Array, 'int' ],
  34015. [ Int16Array, 'int' ],
  34016. [ Int32Array, 'int' ],
  34017. [ Uint8Array, 'uint' ],
  34018. [ Uint16Array, 'uint' ],
  34019. [ Uint32Array, 'uint' ],
  34020. [ Float32Array, 'float' ]
  34021. ] );
  34022. const toFloat = ( value ) => {
  34023. if ( /e/g.test( value ) ) {
  34024. return String( value ).replace( /\+/g, '' );
  34025. } else {
  34026. value = Number( value );
  34027. return value + ( value % 1 ? '' : '.0' );
  34028. }
  34029. };
  34030. /**
  34031. * Base class for builders which generate a shader program based
  34032. * on a 3D object and its node material definition.
  34033. */
  34034. class NodeBuilder {
  34035. /**
  34036. * Constructs a new node builder.
  34037. *
  34038. * @param {Object3D} object - The 3D object.
  34039. * @param {Renderer} renderer - The current renderer.
  34040. * @param {NodeParser} parser - A reference to a node parser.
  34041. */
  34042. constructor( object, renderer, parser ) {
  34043. /**
  34044. * The 3D object.
  34045. *
  34046. * @type {Object3D}
  34047. */
  34048. this.object = object;
  34049. /**
  34050. * The material of the 3D object.
  34051. *
  34052. * @type {?Material}
  34053. */
  34054. this.material = ( object && object.material ) || null;
  34055. /**
  34056. * The geometry of the 3D object.
  34057. *
  34058. * @type {?BufferGeometry}
  34059. */
  34060. this.geometry = ( object && object.geometry ) || null;
  34061. /**
  34062. * The current renderer.
  34063. *
  34064. * @type {Renderer}
  34065. */
  34066. this.renderer = renderer;
  34067. /**
  34068. * A reference to a node parser.
  34069. *
  34070. * @type {NodeParser}
  34071. */
  34072. this.parser = parser;
  34073. /**
  34074. * The scene the 3D object belongs to.
  34075. *
  34076. * @type {?Scene}
  34077. * @default null
  34078. */
  34079. this.scene = null;
  34080. /**
  34081. * The camera the 3D object is rendered with.
  34082. *
  34083. * @type {?Camera}
  34084. * @default null
  34085. */
  34086. this.camera = null;
  34087. /**
  34088. * A list of all nodes the builder is processing
  34089. * for this 3D object.
  34090. *
  34091. * @type {Array<Node>}
  34092. */
  34093. this.nodes = [];
  34094. /**
  34095. * A list of all sequential nodes.
  34096. *
  34097. * @type {Array<Node>}
  34098. */
  34099. this.sequentialNodes = [];
  34100. /**
  34101. * A list of all nodes which {@link Node#update} method should be executed.
  34102. *
  34103. * @type {Array<Node>}
  34104. */
  34105. this.updateNodes = [];
  34106. /**
  34107. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  34108. *
  34109. * @type {Array<Node>}
  34110. */
  34111. this.updateBeforeNodes = [];
  34112. /**
  34113. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  34114. *
  34115. * @type {Array<Node>}
  34116. */
  34117. this.updateAfterNodes = [];
  34118. /**
  34119. * A dictionary that assigns each node to a unique hash.
  34120. *
  34121. * @type {Object<number,Node>}
  34122. */
  34123. this.hashNodes = {};
  34124. /**
  34125. * A reference to a node material observer.
  34126. *
  34127. * @type {?NodeMaterialObserver}
  34128. * @default null
  34129. */
  34130. this.observer = null;
  34131. /**
  34132. * A reference to the current lights node.
  34133. *
  34134. * @type {?LightsNode}
  34135. * @default null
  34136. */
  34137. this.lightsNode = null;
  34138. /**
  34139. * A reference to the current environment node.
  34140. *
  34141. * @type {?Node}
  34142. * @default null
  34143. */
  34144. this.environmentNode = null;
  34145. /**
  34146. * A reference to the current fog node.
  34147. *
  34148. * @type {?Node}
  34149. * @default null
  34150. */
  34151. this.fogNode = null;
  34152. /**
  34153. * The current clipping context.
  34154. *
  34155. * @type {?ClippingContext}
  34156. */
  34157. this.clippingContext = null;
  34158. /**
  34159. * The generated vertex shader.
  34160. *
  34161. * @type {?string}
  34162. */
  34163. this.vertexShader = null;
  34164. /**
  34165. * The generated fragment shader.
  34166. *
  34167. * @type {?string}
  34168. */
  34169. this.fragmentShader = null;
  34170. /**
  34171. * The generated compute shader.
  34172. *
  34173. * @type {?string}
  34174. */
  34175. this.computeShader = null;
  34176. /**
  34177. * Nodes used in the primary flow of code generation.
  34178. *
  34179. * @type {Object<string,Array<Node>>}
  34180. */
  34181. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  34182. /**
  34183. * Nodes code from `.flowNodes`.
  34184. *
  34185. * @type {Object<string,string>}
  34186. */
  34187. this.flowCode = { vertex: '', fragment: '', compute: '' };
  34188. /**
  34189. * This dictionary holds the node uniforms of the builder.
  34190. * The uniforms are maintained in an array for each shader stage.
  34191. *
  34192. * @type {Object}
  34193. */
  34194. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  34195. /**
  34196. * This dictionary holds the output structs of the builder.
  34197. * The structs are maintained in an array for each shader stage.
  34198. *
  34199. * @type {Object}
  34200. */
  34201. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  34202. /**
  34203. * This dictionary holds the types of the builder.
  34204. *
  34205. * @type {Object}
  34206. */
  34207. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  34208. /**
  34209. * This dictionary holds the bindings for each shader stage.
  34210. *
  34211. * @type {Object}
  34212. */
  34213. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  34214. /**
  34215. * This dictionary maintains the binding indices per bind group.
  34216. *
  34217. * @type {Object}
  34218. */
  34219. this.bindingsIndexes = {};
  34220. /**
  34221. * Reference to the array of bind groups.
  34222. *
  34223. * @type {?Array<BindGroup>}
  34224. */
  34225. this.bindGroups = null;
  34226. /**
  34227. * This array holds the node attributes of this builder
  34228. * created via {@link AttributeNode}.
  34229. *
  34230. * @type {Array<NodeAttribute>}
  34231. */
  34232. this.attributes = [];
  34233. /**
  34234. * This array holds the node attributes of this builder
  34235. * created via {@link BufferAttributeNode}.
  34236. *
  34237. * @type {Array<NodeAttribute>}
  34238. */
  34239. this.bufferAttributes = [];
  34240. /**
  34241. * This array holds the node varyings of this builder.
  34242. *
  34243. * @type {Array<NodeVarying>}
  34244. */
  34245. this.varyings = [];
  34246. /**
  34247. * This dictionary holds the (native) node codes of this builder.
  34248. * The codes are maintained in an array for each shader stage.
  34249. *
  34250. * @type {Object<string,Array<NodeCode>>}
  34251. */
  34252. this.codes = {};
  34253. /**
  34254. * This dictionary holds the node variables of this builder.
  34255. * The variables are maintained in an array for each shader stage.
  34256. * This dictionary is also used to count the number of variables
  34257. * according to their type (const, vars).
  34258. *
  34259. * @type {Object<string,Array<NodeVar>|number>}
  34260. */
  34261. this.vars = {};
  34262. /**
  34263. * This dictionary holds the declarations for each shader stage.
  34264. *
  34265. * @type {Object}
  34266. */
  34267. this.declarations = {};
  34268. /**
  34269. * Current code flow.
  34270. * All code generated in this stack will be stored in `.flow`.
  34271. *
  34272. * @type {{code: string}}
  34273. */
  34274. this.flow = { code: '' };
  34275. /**
  34276. * A chain of nodes.
  34277. * Used to check recursive calls in node-graph.
  34278. *
  34279. * @type {Array<Node>}
  34280. */
  34281. this.chaining = [];
  34282. /**
  34283. * The current stack.
  34284. * This reflects the current process in the code block hierarchy,
  34285. * it is useful to know if the current process is inside a conditional for example.
  34286. *
  34287. * @type {StackNode}
  34288. */
  34289. this.stack = stack();
  34290. /**
  34291. * List of stack nodes.
  34292. * The current stack hierarchy is stored in an array.
  34293. *
  34294. * @type {Array<StackNode>}
  34295. */
  34296. this.stacks = [];
  34297. /**
  34298. * A tab value. Used for shader string generation.
  34299. *
  34300. * @type {string}
  34301. * @default '\t'
  34302. */
  34303. this.tab = '\t';
  34304. /**
  34305. * Reference to the current function node.
  34306. *
  34307. * @type {?FunctionNode}
  34308. * @default null
  34309. */
  34310. this.currentFunctionNode = null;
  34311. /**
  34312. * The builder's context.
  34313. *
  34314. * @type {Object}
  34315. */
  34316. this.context = {
  34317. material: this.material
  34318. };
  34319. /**
  34320. * The builder's cache.
  34321. *
  34322. * @type {NodeCache}
  34323. */
  34324. this.cache = new NodeCache();
  34325. /**
  34326. * Since the {@link NodeBuilder#cache} might be temporarily
  34327. * overwritten by other caches, this member retains the reference
  34328. * to the builder's own cache.
  34329. *
  34330. * @type {NodeCache}
  34331. * @default this.cache
  34332. */
  34333. this.globalCache = this.cache;
  34334. this.flowsData = new WeakMap();
  34335. /**
  34336. * The current shader stage.
  34337. *
  34338. * @type {?('vertex'|'fragment'|'compute'|'any')}
  34339. */
  34340. this.shaderStage = null;
  34341. /**
  34342. * The current build stage.
  34343. *
  34344. * @type {?('setup'|'analyze'|'generate')}
  34345. */
  34346. this.buildStage = null;
  34347. /**
  34348. * The sub-build layers.
  34349. *
  34350. * @type {Array<SubBuildNode>}
  34351. * @default []
  34352. */
  34353. this.subBuildLayers = [];
  34354. /**
  34355. * The current stack of nodes.
  34356. *
  34357. * @type {?StackNode}
  34358. * @default null
  34359. */
  34360. this.currentStack = null;
  34361. /**
  34362. * The current sub-build TSL function(Fn).
  34363. *
  34364. * @type {?string}
  34365. * @default null
  34366. */
  34367. this.subBuildFn = null;
  34368. /**
  34369. * The current TSL function(Fn) call node.
  34370. *
  34371. * @type {?Node}
  34372. * @default null
  34373. */
  34374. this.fnCall = null;
  34375. }
  34376. /**
  34377. * Returns the bind groups of the current renderer.
  34378. *
  34379. * @return {ChainMap} The cache.
  34380. */
  34381. getBindGroupsCache() {
  34382. let bindGroupsCache = rendererCache.get( this.renderer );
  34383. if ( bindGroupsCache === undefined ) {
  34384. bindGroupsCache = new ChainMap();
  34385. rendererCache.set( this.renderer, bindGroupsCache );
  34386. }
  34387. return bindGroupsCache;
  34388. }
  34389. /**
  34390. * Factory method for creating an instance of {@link RenderTarget} with the given
  34391. * dimensions and options.
  34392. *
  34393. * @param {number} width - The width of the render target.
  34394. * @param {number} height - The height of the render target.
  34395. * @param {Object} options - The options of the render target.
  34396. * @return {RenderTarget} The render target.
  34397. */
  34398. createRenderTarget( width, height, options ) {
  34399. return new RenderTarget( width, height, options );
  34400. }
  34401. /**
  34402. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  34403. * dimensions and options.
  34404. *
  34405. * @param {number} size - The size of the cube render target.
  34406. * @param {Object} options - The options of the cube render target.
  34407. * @return {CubeRenderTarget} The cube render target.
  34408. */
  34409. createCubeRenderTarget( size, options ) {
  34410. return new CubeRenderTarget( size, options );
  34411. }
  34412. /**
  34413. * Whether the given node is included in the internal array of nodes or not.
  34414. *
  34415. * @param {Node} node - The node to test.
  34416. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  34417. */
  34418. includes( node ) {
  34419. return this.nodes.includes( node );
  34420. }
  34421. /**
  34422. * Returns the output struct name which is required by
  34423. * {@link OutputStructNode}.
  34424. *
  34425. * @abstract
  34426. * @return {string} The name of the output struct.
  34427. */
  34428. getOutputStructName() {}
  34429. /**
  34430. * Returns a bind group for the given group name and binding.
  34431. *
  34432. * @private
  34433. * @param {string} groupName - The group name.
  34434. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  34435. * @return {BindGroup} The bind group
  34436. */
  34437. _getBindGroup( groupName, bindings ) {
  34438. const bindGroupsCache = this.getBindGroupsCache();
  34439. //
  34440. const bindingsArray = [];
  34441. let sharedGroup = true;
  34442. for ( const binding of bindings ) {
  34443. bindingsArray.push( binding );
  34444. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  34445. }
  34446. //
  34447. let bindGroup;
  34448. if ( sharedGroup ) {
  34449. bindGroup = bindGroupsCache.get( bindingsArray );
  34450. if ( bindGroup === undefined ) {
  34451. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34452. bindGroupsCache.set( bindingsArray, bindGroup );
  34453. }
  34454. } else {
  34455. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34456. }
  34457. return bindGroup;
  34458. }
  34459. /**
  34460. * Returns an array of node uniform groups for the given group name and shader stage.
  34461. *
  34462. * @param {string} groupName - The group name.
  34463. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34464. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  34465. */
  34466. getBindGroupArray( groupName, shaderStage ) {
  34467. const bindings = this.bindings[ shaderStage ];
  34468. let bindGroup = bindings[ groupName ];
  34469. if ( bindGroup === undefined ) {
  34470. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  34471. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  34472. }
  34473. bindings[ groupName ] = bindGroup = [];
  34474. }
  34475. return bindGroup;
  34476. }
  34477. /**
  34478. * Returns a list bindings of all shader stages separated by groups.
  34479. *
  34480. * @return {Array<BindGroup>} The list of bindings.
  34481. */
  34482. getBindings() {
  34483. let bindingsGroups = this.bindGroups;
  34484. if ( bindingsGroups === null ) {
  34485. const groups = {};
  34486. const bindings = this.bindings;
  34487. for ( const shaderStage of shaderStages ) {
  34488. for ( const groupName in bindings[ shaderStage ] ) {
  34489. const uniforms = bindings[ shaderStage ][ groupName ];
  34490. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  34491. groupUniforms.push( ...uniforms );
  34492. }
  34493. }
  34494. bindingsGroups = [];
  34495. for ( const groupName in groups ) {
  34496. const group = groups[ groupName ];
  34497. const bindingsGroup = this._getBindGroup( groupName, group );
  34498. bindingsGroups.push( bindingsGroup );
  34499. }
  34500. this.bindGroups = bindingsGroups;
  34501. }
  34502. return bindingsGroups;
  34503. }
  34504. /**
  34505. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  34506. */
  34507. sortBindingGroups() {
  34508. const bindingsGroups = this.getBindings();
  34509. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  34510. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  34511. const bindingGroup = bindingsGroups[ i ];
  34512. this.bindingsIndexes[ bindingGroup.name ].group = i;
  34513. bindingGroup.index = i;
  34514. }
  34515. }
  34516. /**
  34517. * The builder maintains each node in a hash-based dictionary.
  34518. * This method sets the given node (value) with the given hash (key) into this dictionary.
  34519. *
  34520. * @param {Node} node - The node to add.
  34521. * @param {number} hash - The hash of the node.
  34522. */
  34523. setHashNode( node, hash ) {
  34524. this.hashNodes[ hash ] = node;
  34525. }
  34526. /**
  34527. * Adds a node to this builder.
  34528. *
  34529. * @param {Node} node - The node to add.
  34530. */
  34531. addNode( node ) {
  34532. if ( this.nodes.includes( node ) === false ) {
  34533. this.nodes.push( node );
  34534. this.setHashNode( node, node.getHash( this ) );
  34535. }
  34536. }
  34537. /**
  34538. * It is used to add Nodes that will be used as FRAME and RENDER events,
  34539. * and need to follow a certain sequence in the calls to work correctly.
  34540. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  34541. *
  34542. * @param {Node} node - The node to add.
  34543. */
  34544. addSequentialNode( node ) {
  34545. if ( this.sequentialNodes.includes( node ) === false ) {
  34546. this.sequentialNodes.push( node );
  34547. }
  34548. }
  34549. /**
  34550. * Checks the update types of nodes
  34551. */
  34552. buildUpdateNodes() {
  34553. for ( const node of this.nodes ) {
  34554. const updateType = node.getUpdateType();
  34555. if ( updateType !== NodeUpdateType.NONE ) {
  34556. this.updateNodes.push( node );
  34557. }
  34558. }
  34559. for ( const node of this.sequentialNodes ) {
  34560. const updateBeforeType = node.getUpdateBeforeType();
  34561. const updateAfterType = node.getUpdateAfterType();
  34562. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  34563. this.updateBeforeNodes.push( node );
  34564. }
  34565. if ( updateAfterType !== NodeUpdateType.NONE ) {
  34566. this.updateAfterNodes.push( node );
  34567. }
  34568. }
  34569. }
  34570. /**
  34571. * A reference the current node which is the
  34572. * last node in the chain of nodes.
  34573. *
  34574. * @type {Node}
  34575. */
  34576. get currentNode() {
  34577. return this.chaining[ this.chaining.length - 1 ];
  34578. }
  34579. /**
  34580. * Whether the given texture is filtered or not.
  34581. *
  34582. * @param {Texture} texture - The texture to check.
  34583. * @return {boolean} Whether the given texture is filtered or not.
  34584. */
  34585. isFilteredTexture( texture ) {
  34586. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  34587. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  34588. }
  34589. /**
  34590. * Adds the given node to the internal node chain.
  34591. * This is used to check recursive calls in node-graph.
  34592. *
  34593. * @param {Node} node - The node to add.
  34594. */
  34595. addChain( node ) {
  34596. /*
  34597. if ( this.chaining.indexOf( node ) !== - 1 ) {
  34598. warn( 'Recursive node: ', node );
  34599. }
  34600. */
  34601. this.chaining.push( node );
  34602. }
  34603. /**
  34604. * Removes the given node from the internal node chain.
  34605. *
  34606. * @param {Node} node - The node to remove.
  34607. */
  34608. removeChain( node ) {
  34609. const lastChain = this.chaining.pop();
  34610. if ( lastChain !== node ) {
  34611. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  34612. }
  34613. }
  34614. /**
  34615. * Returns the native shader method name for a given generic name. E.g.
  34616. * the method name `textureDimensions` matches the WGSL name but must be
  34617. * resolved to `textureSize` in GLSL.
  34618. *
  34619. * @abstract
  34620. * @param {string} method - The method name to resolve.
  34621. * @return {string} The resolved method name.
  34622. */
  34623. getMethod( method ) {
  34624. return method;
  34625. }
  34626. /**
  34627. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34628. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34629. *
  34630. * @abstract
  34631. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34632. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34633. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34634. * @return {string} The resolved method name.
  34635. */
  34636. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34637. return null;
  34638. }
  34639. /**
  34640. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34641. *
  34642. * @param {number} hash - The hash of the node.
  34643. * @return {Node} The found node.
  34644. */
  34645. getNodeFromHash( hash ) {
  34646. return this.hashNodes[ hash ];
  34647. }
  34648. /**
  34649. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34650. *
  34651. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34652. * @param {Node} node - The node to add.
  34653. * @return {Node} The node.
  34654. */
  34655. addFlow( shaderStage, node ) {
  34656. this.flowNodes[ shaderStage ].push( node );
  34657. return node;
  34658. }
  34659. /**
  34660. * Sets builder's context.
  34661. *
  34662. * @param {Object} context - The context to set.
  34663. */
  34664. setContext( context ) {
  34665. this.context = context;
  34666. }
  34667. /**
  34668. * Returns the builder's current context.
  34669. *
  34670. * @return {Object} The builder's current context.
  34671. */
  34672. getContext() {
  34673. return this.context;
  34674. }
  34675. /**
  34676. * Adds context data to the builder's current context.
  34677. *
  34678. * @param {Object} context - The context to add.
  34679. * @return {Object} The previous context.
  34680. */
  34681. addContext( context ) {
  34682. const previousContext = this.getContext();
  34683. this.setContext( { ...this.context, ...context } );
  34684. return previousContext;
  34685. }
  34686. /**
  34687. * Gets a context used in shader construction that can be shared across different materials.
  34688. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34689. *
  34690. * @return {Object} The builder's current context without material.
  34691. */
  34692. getSharedContext() {
  34693. ({ ...this.context });
  34694. return this.context;
  34695. }
  34696. /**
  34697. * Sets builder's cache.
  34698. *
  34699. * @param {NodeCache} cache - The cache to set.
  34700. */
  34701. setCache( cache ) {
  34702. this.cache = cache;
  34703. }
  34704. /**
  34705. * Returns the builder's current cache.
  34706. *
  34707. * @return {NodeCache} The builder's current cache.
  34708. */
  34709. getCache() {
  34710. return this.cache;
  34711. }
  34712. /**
  34713. * Returns a cache for the given node.
  34714. *
  34715. * @param {Node} node - The node.
  34716. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34717. * @return {NodeCache} The cache.
  34718. */
  34719. getCacheFromNode( node, parent = true ) {
  34720. const data = this.getDataFromNode( node );
  34721. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34722. return data.cache;
  34723. }
  34724. /**
  34725. * Whether the requested feature is available or not.
  34726. *
  34727. * @abstract
  34728. * @param {string} name - The requested feature.
  34729. * @return {boolean} Whether the requested feature is supported or not.
  34730. */
  34731. isAvailable( /*name*/ ) {
  34732. return false;
  34733. }
  34734. /**
  34735. * Returns the vertexIndex input variable as a native shader string.
  34736. *
  34737. * @abstract
  34738. * @return {string} The instanceIndex shader string.
  34739. */
  34740. getVertexIndex() {
  34741. warn( 'Abstract function.' );
  34742. }
  34743. /**
  34744. * Contextually returns either the vertex stage instance index builtin
  34745. * or the linearized index of an compute invocation within a grid of workgroups.
  34746. *
  34747. * @abstract
  34748. * @return {string} The instanceIndex shader string.
  34749. */
  34750. getInstanceIndex() {
  34751. warn( 'Abstract function.' );
  34752. }
  34753. /**
  34754. * Returns the drawIndex input variable as a native shader string.
  34755. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34756. *
  34757. * @abstract
  34758. * @return {?string} The drawIndex shader string.
  34759. */
  34760. getDrawIndex() {
  34761. warn( 'Abstract function.' );
  34762. }
  34763. /**
  34764. * Returns the frontFacing input variable as a native shader string.
  34765. *
  34766. * @abstract
  34767. * @return {string} The frontFacing shader string.
  34768. */
  34769. getFrontFacing() {
  34770. warn( 'Abstract function.' );
  34771. }
  34772. /**
  34773. * Returns the fragCoord input variable as a native shader string.
  34774. *
  34775. * @abstract
  34776. * @return {string} The fragCoord shader string.
  34777. */
  34778. getFragCoord() {
  34779. warn( 'Abstract function.' );
  34780. }
  34781. /**
  34782. * Whether to flip texture data along its vertical axis or not. WebGL needs
  34783. * this method evaluate to `true`, WebGPU to `false`.
  34784. *
  34785. * @abstract
  34786. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  34787. */
  34788. isFlipY() {
  34789. return false;
  34790. }
  34791. /**
  34792. * Calling this method increases the usage count for the given node by one.
  34793. *
  34794. * @param {Node} node - The node to increase the usage count for.
  34795. * @return {number} The updated usage count.
  34796. */
  34797. increaseUsage( node ) {
  34798. const nodeData = this.getDataFromNode( node );
  34799. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  34800. return nodeData.usageCount;
  34801. }
  34802. /**
  34803. * Generates a texture sample shader string for the given texture data.
  34804. *
  34805. * @abstract
  34806. * @param {Texture} texture - The texture.
  34807. * @param {string} textureProperty - The texture property name.
  34808. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34809. * @return {string} The generated shader string.
  34810. */
  34811. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  34812. warn( 'Abstract function.' );
  34813. }
  34814. /**
  34815. * Generates a texture LOD shader string for the given texture data.
  34816. *
  34817. * @abstract
  34818. * @param {Texture} texture - The texture.
  34819. * @param {string} textureProperty - The texture property name.
  34820. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34821. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  34822. * @param {string} levelSnippet - Snippet defining the mip level.
  34823. * @return {string} The generated shader string.
  34824. */
  34825. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  34826. warn( 'Abstract function.' );
  34827. }
  34828. /**
  34829. * Generates the array declaration string.
  34830. *
  34831. * @param {string} type - The type.
  34832. * @param {?number} [count] - The count.
  34833. * @return {string} The generated value as a shader string.
  34834. */
  34835. generateArrayDeclaration( type, count ) {
  34836. return this.getType( type ) + '[ ' + count + ' ]';
  34837. }
  34838. /**
  34839. * Generates the array shader string for the given type and value.
  34840. *
  34841. * @param {string} type - The type.
  34842. * @param {?number} [count] - The count.
  34843. * @param {?Array<Node>} [values=null] - The default values.
  34844. * @return {string} The generated value as a shader string.
  34845. */
  34846. generateArray( type, count, values = null ) {
  34847. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  34848. for ( let i = 0; i < count; i ++ ) {
  34849. const value = values ? values[ i ] : null;
  34850. if ( value !== null ) {
  34851. snippet += value.build( this, type );
  34852. } else {
  34853. snippet += this.generateConst( type );
  34854. }
  34855. if ( i < count - 1 ) snippet += ', ';
  34856. }
  34857. snippet += ' )';
  34858. return snippet;
  34859. }
  34860. /**
  34861. * Generates the struct shader string.
  34862. *
  34863. * @param {string} type - The type.
  34864. * @param {Array<Object>} [membersLayout] - The count.
  34865. * @param {?Array<Node>} [values=null] - The default values.
  34866. * @return {string} The generated value as a shader string.
  34867. */
  34868. generateStruct( type, membersLayout, values = null ) {
  34869. const snippets = [];
  34870. for ( const member of membersLayout ) {
  34871. const { name, type } = member;
  34872. if ( values && values[ name ] && values[ name ].isNode ) {
  34873. snippets.push( values[ name ].build( this, type ) );
  34874. } else {
  34875. snippets.push( this.generateConst( type ) );
  34876. }
  34877. }
  34878. return type + '( ' + snippets.join( ', ' ) + ' )';
  34879. }
  34880. /**
  34881. * Generates the shader string for the given type and value.
  34882. *
  34883. * @param {string} type - The type.
  34884. * @param {?any} [value=null] - The value.
  34885. * @return {string} The generated value as a shader string.
  34886. */
  34887. generateConst( type, value = null ) {
  34888. if ( value === null ) {
  34889. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  34890. else if ( type === 'bool' ) value = false;
  34891. else if ( type === 'color' ) value = new Color();
  34892. else if ( type === 'vec2' ) value = new Vector2();
  34893. else if ( type === 'vec3' ) value = new Vector3();
  34894. else if ( type === 'vec4' ) value = new Vector4();
  34895. }
  34896. if ( type === 'float' ) return toFloat( value );
  34897. if ( type === 'int' ) return `${ Math.round( value ) }`;
  34898. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  34899. if ( type === 'bool' ) return value ? 'true' : 'false';
  34900. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  34901. const typeLength = this.getTypeLength( type );
  34902. const componentType = this.getComponentType( type );
  34903. const generateConst = value => this.generateConst( componentType, value );
  34904. if ( typeLength === 2 ) {
  34905. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  34906. } else if ( typeLength === 3 ) {
  34907. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  34908. } else if ( typeLength === 4 && type !== 'mat2' ) {
  34909. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  34910. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  34911. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  34912. } else if ( typeLength > 4 ) {
  34913. return `${ this.getType( type ) }()`;
  34914. }
  34915. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  34916. }
  34917. /**
  34918. * It might be necessary to convert certain data types to different ones
  34919. * so this method can be used to hide the conversion.
  34920. *
  34921. * @param {string} type - The type.
  34922. * @return {string} The updated type.
  34923. */
  34924. getType( type ) {
  34925. if ( type === 'color' ) return 'vec3';
  34926. return type;
  34927. }
  34928. /**
  34929. * Whether the given attribute name is defined in the geometry or not.
  34930. *
  34931. * @param {string} name - The attribute name.
  34932. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34933. */
  34934. hasGeometryAttribute( name ) {
  34935. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34936. }
  34937. /**
  34938. * Returns a node attribute for the given name and type.
  34939. *
  34940. * @param {string} name - The attribute's name.
  34941. * @param {string} type - The attribute's type.
  34942. * @return {NodeAttribute} The node attribute.
  34943. */
  34944. getAttribute( name, type ) {
  34945. const attributes = this.attributes;
  34946. // find attribute
  34947. for ( const attribute of attributes ) {
  34948. if ( attribute.name === name ) {
  34949. return attribute;
  34950. }
  34951. }
  34952. // create a new if no exist
  34953. const attribute = new NodeAttribute( name, type );
  34954. this.registerDeclaration( attribute );
  34955. attributes.push( attribute );
  34956. return attribute;
  34957. }
  34958. /**
  34959. * Returns for the given node and shader stage the property name for the shader.
  34960. *
  34961. * @param {Node} node - The node.
  34962. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34963. * @return {string} The property name.
  34964. */
  34965. getPropertyName( node/*, shaderStage*/ ) {
  34966. return node.name;
  34967. }
  34968. /**
  34969. * Whether the given type is a vector type or not.
  34970. *
  34971. * @param {string} type - The type to check.
  34972. * @return {boolean} Whether the given type is a vector type or not.
  34973. */
  34974. isVector( type ) {
  34975. return /vec\d/.test( type );
  34976. }
  34977. /**
  34978. * Whether the given type is a matrix type or not.
  34979. *
  34980. * @param {string} type - The type to check.
  34981. * @return {boolean} Whether the given type is a matrix type or not.
  34982. */
  34983. isMatrix( type ) {
  34984. return /mat\d/.test( type );
  34985. }
  34986. /**
  34987. * Whether the given type is a reference type or not.
  34988. *
  34989. * @param {string} type - The type to check.
  34990. * @return {boolean} Whether the given type is a reference type or not.
  34991. */
  34992. isReference( type ) {
  34993. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34994. }
  34995. /**
  34996. * Checks if the given texture requires a manual conversion to the working color space.
  34997. *
  34998. * @abstract
  34999. * @param {Texture} texture - The texture to check.
  35000. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  35001. */
  35002. needsToWorkingColorSpace( /*texture*/ ) {
  35003. return false;
  35004. }
  35005. /**
  35006. * Returns the component type of a given texture.
  35007. *
  35008. * @param {Texture} texture - The texture.
  35009. * @return {string} The component type.
  35010. */
  35011. getComponentTypeFromTexture( texture ) {
  35012. const type = texture.type;
  35013. if ( texture.isDataTexture ) {
  35014. if ( type === IntType ) return 'int';
  35015. if ( type === UnsignedIntType ) return 'uint';
  35016. }
  35017. return 'float';
  35018. }
  35019. /**
  35020. * Returns the element type for a given type.
  35021. *
  35022. * @param {string} type - The type.
  35023. * @return {string} The element type.
  35024. */
  35025. getElementType( type ) {
  35026. if ( type === 'mat2' ) return 'vec2';
  35027. if ( type === 'mat3' ) return 'vec3';
  35028. if ( type === 'mat4' ) return 'vec4';
  35029. return this.getComponentType( type );
  35030. }
  35031. /**
  35032. * Returns the component type for a given type.
  35033. *
  35034. * @param {string} type - The type.
  35035. * @return {string} The component type.
  35036. */
  35037. getComponentType( type ) {
  35038. type = this.getVectorType( type );
  35039. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  35040. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  35041. if ( componentType === null ) return null;
  35042. if ( componentType[ 1 ] === 'b' ) return 'bool';
  35043. if ( componentType[ 1 ] === 'i' ) return 'int';
  35044. if ( componentType[ 1 ] === 'u' ) return 'uint';
  35045. return 'float';
  35046. }
  35047. /**
  35048. * Returns the vector type for a given type.
  35049. *
  35050. * @param {string} type - The type.
  35051. * @return {string} The vector type.
  35052. */
  35053. getVectorType( type ) {
  35054. if ( type === 'color' ) return 'vec3';
  35055. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  35056. return type;
  35057. }
  35058. /**
  35059. * Returns the data type for the given the length and component type.
  35060. *
  35061. * @param {number} length - The length.
  35062. * @param {string} [componentType='float'] - The component type.
  35063. * @return {string} The type.
  35064. */
  35065. getTypeFromLength( length, componentType = 'float' ) {
  35066. if ( length === 1 ) return componentType;
  35067. let baseType = getTypeFromLength( length );
  35068. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  35069. // fix edge case for mat2x2 being same size as vec4
  35070. if ( /mat2/.test( componentType ) === true ) {
  35071. baseType = baseType.replace( 'vec', 'mat' );
  35072. }
  35073. return prefix + baseType;
  35074. }
  35075. /**
  35076. * Returns the type for a given typed array.
  35077. *
  35078. * @param {TypedArray} array - The typed array.
  35079. * @return {string} The type.
  35080. */
  35081. getTypeFromArray( array ) {
  35082. return typeFromArray.get( array.constructor );
  35083. }
  35084. /**
  35085. * Returns the type is an integer type.
  35086. *
  35087. * @param {string} type - The type.
  35088. * @return {boolean} Whether the type is an integer type or not.
  35089. */
  35090. isInteger( type ) {
  35091. return /int|uint|(i|u)vec/.test( type );
  35092. }
  35093. /**
  35094. * Returns the type for a given buffer attribute.
  35095. *
  35096. * @param {BufferAttribute} attribute - The buffer attribute.
  35097. * @return {string} The type.
  35098. */
  35099. getTypeFromAttribute( attribute ) {
  35100. let dataAttribute = attribute;
  35101. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35102. const array = dataAttribute.array;
  35103. const itemSize = attribute.itemSize;
  35104. const normalized = attribute.normalized;
  35105. let arrayType;
  35106. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  35107. arrayType = this.getTypeFromArray( array );
  35108. }
  35109. return this.getTypeFromLength( itemSize, arrayType );
  35110. }
  35111. /**
  35112. * Returns the length for the given data type.
  35113. *
  35114. * @param {string} type - The data type.
  35115. * @return {number} The length.
  35116. */
  35117. getTypeLength( type ) {
  35118. const vecType = this.getVectorType( type );
  35119. const vecNum = /vec([2-4])/.exec( vecType );
  35120. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  35121. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  35122. if ( /mat2/.test( type ) === true ) return 4;
  35123. if ( /mat3/.test( type ) === true ) return 9;
  35124. if ( /mat4/.test( type ) === true ) return 16;
  35125. return 0;
  35126. }
  35127. /**
  35128. * Returns the vector type for a given matrix type.
  35129. *
  35130. * @param {string} type - The matrix type.
  35131. * @return {string} The vector type.
  35132. */
  35133. getVectorFromMatrix( type ) {
  35134. return type.replace( 'mat', 'vec' );
  35135. }
  35136. /**
  35137. * For a given type this method changes the component type to the
  35138. * given value. E.g. `vec4` should be changed to the new component type
  35139. * `uint` which results in `uvec4`.
  35140. *
  35141. * @param {string} type - The type.
  35142. * @param {string} newComponentType - The new component type.
  35143. * @return {string} The new type.
  35144. */
  35145. changeComponentType( type, newComponentType ) {
  35146. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  35147. }
  35148. /**
  35149. * Returns the integer type pendant for the given type.
  35150. *
  35151. * @param {string} type - The type.
  35152. * @return {string} The integer type.
  35153. */
  35154. getIntegerType( type ) {
  35155. const componentType = this.getComponentType( type );
  35156. if ( componentType === 'int' || componentType === 'uint' ) return type;
  35157. return this.changeComponentType( type, 'int' );
  35158. }
  35159. /**
  35160. * Adds a stack node to the internal stack.
  35161. *
  35162. * @return {StackNode} The added stack node.
  35163. */
  35164. addStack() {
  35165. this.stack = stack( this.stack );
  35166. const previousStack = getCurrentStack();
  35167. this.stacks.push( previousStack );
  35168. setCurrentStack( this.stack );
  35169. return this.stack;
  35170. }
  35171. /**
  35172. * Removes the last stack node from the internal stack.
  35173. *
  35174. * @return {StackNode} The removed stack node.
  35175. */
  35176. removeStack() {
  35177. const lastStack = this.stack;
  35178. this.stack = lastStack.parent;
  35179. setCurrentStack( this.stacks.pop() );
  35180. return lastStack;
  35181. }
  35182. /**
  35183. * The builder maintains (cached) data for each node during the building process. This method
  35184. * can be used to get these data for a specific shader stage and cache.
  35185. *
  35186. * @param {Node} node - The node to get the data for.
  35187. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35188. * @param {?NodeCache} cache - An optional cache.
  35189. * @return {Object} The node data.
  35190. */
  35191. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  35192. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  35193. let nodeData = cache.getData( node );
  35194. if ( nodeData === undefined ) {
  35195. nodeData = {};
  35196. cache.setData( node, nodeData );
  35197. }
  35198. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  35199. //
  35200. let data = nodeData[ shaderStage ];
  35201. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  35202. const subBuild = this.getClosestSubBuild( subBuilds );
  35203. if ( subBuild ) {
  35204. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  35205. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  35206. data.subBuilds = subBuilds;
  35207. }
  35208. return data;
  35209. }
  35210. /**
  35211. * Returns the properties for the given node and shader stage.
  35212. *
  35213. * Properties are typically used within a build stage to reference a node's
  35214. * child node or nodes manually assigned to the properties in a separate build stage.
  35215. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  35216. * to the current node's properties in the setup stage and building those properties in the generate stage.
  35217. *
  35218. * @param {Node} node - The node to get the properties for.
  35219. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  35220. * @return {Object} The node properties.
  35221. */
  35222. getNodeProperties( node, shaderStage = 'any' ) {
  35223. const nodeData = this.getDataFromNode( node, shaderStage );
  35224. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  35225. }
  35226. /**
  35227. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  35228. *
  35229. * @param {BufferAttributeNode} node - The buffer attribute node.
  35230. * @param {string} type - The node type.
  35231. * @return {NodeAttribute} The node attribute.
  35232. */
  35233. getBufferAttributeFromNode( node, type ) {
  35234. const nodeData = this.getDataFromNode( node );
  35235. let bufferAttribute = nodeData.bufferAttribute;
  35236. if ( bufferAttribute === undefined ) {
  35237. const index = this.uniforms.index ++;
  35238. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  35239. this.bufferAttributes.push( bufferAttribute );
  35240. nodeData.bufferAttribute = bufferAttribute;
  35241. }
  35242. return bufferAttribute;
  35243. }
  35244. /**
  35245. * Returns an instance of {@link StructType} for the given struct name and shader stage
  35246. * or null if not found.
  35247. *
  35248. * @param {string} name - The name of the struct.
  35249. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35250. * @return {?StructType} The struct type or null if not found.
  35251. */
  35252. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  35253. return this.types[ shaderStage ][ name ] || null;
  35254. }
  35255. /**
  35256. * Returns an instance of {@link StructType} for the given output struct node.
  35257. *
  35258. * @param {OutputStructNode} node - The output struct node.
  35259. * @param {Array<Object>} membersLayout - The output struct types.
  35260. * @param {?string} [name=null] - The name of the struct.
  35261. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35262. * @return {StructType} The struct type attribute.
  35263. */
  35264. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  35265. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35266. let structType = nodeData.structType;
  35267. if ( structType === undefined ) {
  35268. const index = this.structs.index ++;
  35269. if ( name === null ) name = 'StructType' + index;
  35270. structType = new StructType( name, membersLayout );
  35271. this.structs[ shaderStage ].push( structType );
  35272. this.types[ shaderStage ][ name ] = node;
  35273. nodeData.structType = structType;
  35274. }
  35275. return structType;
  35276. }
  35277. /**
  35278. * Returns an instance of {@link StructType} for the given output struct node.
  35279. *
  35280. * @param {OutputStructNode} node - The output struct node.
  35281. * @param {Array<Object>} membersLayout - The output struct types.
  35282. * @return {StructType} The struct type attribute.
  35283. */
  35284. getOutputStructTypeFromNode( node, membersLayout ) {
  35285. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  35286. structType.output = true;
  35287. return structType;
  35288. }
  35289. /**
  35290. * Returns an instance of {@link NodeUniform} for the given uniform node.
  35291. *
  35292. * @param {UniformNode} node - The uniform node.
  35293. * @param {string} type - The uniform type.
  35294. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35295. * @param {?string} name - The name of the uniform.
  35296. * @return {NodeUniform} The node uniform.
  35297. */
  35298. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  35299. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35300. let nodeUniform = nodeData.uniform;
  35301. if ( nodeUniform === undefined ) {
  35302. const index = this.uniforms.index ++;
  35303. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  35304. this.uniforms[ shaderStage ].push( nodeUniform );
  35305. this.registerDeclaration( nodeUniform );
  35306. nodeData.uniform = nodeUniform;
  35307. }
  35308. return nodeUniform;
  35309. }
  35310. /**
  35311. * Returns an instance of {@link NodeVar} for the given variable node.
  35312. *
  35313. * @param {VarNode} node - The variable node.
  35314. * @param {?string} name - The variable's name.
  35315. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  35316. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35317. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  35318. *
  35319. * @return {NodeVar} The node variable.
  35320. */
  35321. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  35322. const nodeData = this.getDataFromNode( node, shaderStage );
  35323. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  35324. let nodeVar = nodeData[ subBuildVariable ];
  35325. if ( nodeVar === undefined ) {
  35326. const idNS = readOnly ? '_const' : '_var';
  35327. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  35328. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  35329. if ( name === null ) {
  35330. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  35331. this.vars[ idNS ] ++;
  35332. }
  35333. //
  35334. if ( subBuildVariable !== 'variable' ) {
  35335. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35336. }
  35337. //
  35338. const count = node.getArrayCount( this );
  35339. nodeVar = new NodeVar( name, type, readOnly, count );
  35340. if ( ! readOnly ) {
  35341. vars.push( nodeVar );
  35342. }
  35343. this.registerDeclaration( nodeVar );
  35344. nodeData[ subBuildVariable ] = nodeVar;
  35345. }
  35346. return nodeVar;
  35347. }
  35348. /**
  35349. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  35350. *
  35351. * @param {Node} node - The varying node.
  35352. * @return {boolean} Returns true if deterministic.
  35353. */
  35354. isDeterministic( node ) {
  35355. if ( node.isMathNode ) {
  35356. return this.isDeterministic( node.aNode ) &&
  35357. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  35358. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  35359. } else if ( node.isOperatorNode ) {
  35360. return this.isDeterministic( node.aNode ) &&
  35361. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  35362. } else if ( node.isArrayNode ) {
  35363. if ( node.values !== null ) {
  35364. for ( const n of node.values ) {
  35365. if ( ! this.isDeterministic( n ) ) {
  35366. return false;
  35367. }
  35368. }
  35369. }
  35370. return true;
  35371. } else if ( node.isConstNode ) {
  35372. return true;
  35373. }
  35374. return false;
  35375. }
  35376. /**
  35377. * Returns an instance of {@link NodeVarying} for the given varying node.
  35378. *
  35379. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  35380. * @param {?string} name - The varying's name.
  35381. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  35382. * @param {?string} interpolationType - The interpolation type of the varying.
  35383. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35384. * @return {NodeVar} The node varying.
  35385. */
  35386. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  35387. const nodeData = this.getDataFromNode( node, 'any' );
  35388. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  35389. let nodeVarying = nodeData[ subBuildVarying ];
  35390. if ( nodeVarying === undefined ) {
  35391. const varyings = this.varyings;
  35392. const index = varyings.length;
  35393. if ( name === null ) name = 'nodeVarying' + index;
  35394. //
  35395. if ( subBuildVarying !== 'varying' ) {
  35396. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35397. }
  35398. //
  35399. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  35400. varyings.push( nodeVarying );
  35401. this.registerDeclaration( nodeVarying );
  35402. nodeData[ subBuildVarying ] = nodeVarying;
  35403. }
  35404. return nodeVarying;
  35405. }
  35406. /**
  35407. * Registers a node declaration in the current shader stage.
  35408. *
  35409. * @param {Object} node - The node to be registered.
  35410. */
  35411. registerDeclaration( node ) {
  35412. const shaderStage = this.shaderStage;
  35413. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  35414. const property = this.getPropertyName( node );
  35415. let index = 1;
  35416. let name = property;
  35417. // Automatically renames the property if the name is already in use.
  35418. while ( declarations[ name ] !== undefined ) {
  35419. name = property + '_' + index ++;
  35420. }
  35421. if ( index > 1 ) {
  35422. node.name = name;
  35423. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  35424. }
  35425. declarations[ name ] = node;
  35426. }
  35427. /**
  35428. * Returns an instance of {@link NodeCode} for the given code node.
  35429. *
  35430. * @param {CodeNode} node - The code node.
  35431. * @param {string} type - The node type.
  35432. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35433. * @return {NodeCode} The node code.
  35434. */
  35435. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  35436. const nodeData = this.getDataFromNode( node );
  35437. let nodeCode = nodeData.code;
  35438. if ( nodeCode === undefined ) {
  35439. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  35440. const index = codes.length;
  35441. nodeCode = new NodeCode( 'nodeCode' + index, type );
  35442. codes.push( nodeCode );
  35443. nodeData.code = nodeCode;
  35444. }
  35445. return nodeCode;
  35446. }
  35447. /**
  35448. * Adds a code flow based on the code-block hierarchy.
  35449. * This is used so that code-blocks like If,Else create their variables locally if the Node
  35450. * is only used inside one of these conditionals in the current shader stage.
  35451. *
  35452. * @param {Node} node - The node to add.
  35453. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  35454. */
  35455. addFlowCodeHierarchy( node, nodeBlock ) {
  35456. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  35457. let needsFlowCode = true;
  35458. let nodeBlockHierarchy = nodeBlock;
  35459. while ( nodeBlockHierarchy ) {
  35460. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  35461. needsFlowCode = false;
  35462. break;
  35463. }
  35464. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  35465. }
  35466. if ( needsFlowCode ) {
  35467. for ( const flowCode of flowCodes ) {
  35468. this.addLineFlowCode( flowCode );
  35469. }
  35470. }
  35471. }
  35472. /**
  35473. * Add a inline-code to the current flow code-block.
  35474. *
  35475. * @param {Node} node - The node to add.
  35476. * @param {string} code - The code to add.
  35477. * @param {Node} nodeBlock - Current ConditionalNode
  35478. */
  35479. addLineFlowCodeBlock( node, code, nodeBlock ) {
  35480. const nodeData = this.getDataFromNode( node );
  35481. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  35482. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  35483. flowCodes.push( code );
  35484. codeBlock.set( nodeBlock, true );
  35485. }
  35486. /**
  35487. * Add a inline-code to the current flow.
  35488. *
  35489. * @param {string} code - The code to add.
  35490. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  35491. * @return {NodeBuilder} A reference to this node builder.
  35492. */
  35493. addLineFlowCode( code, node = null ) {
  35494. if ( code === '' ) return this;
  35495. if ( node !== null && this.context.nodeBlock ) {
  35496. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  35497. }
  35498. code = this.tab + code;
  35499. if ( ! /;\s*$/.test( code ) ) {
  35500. code = code + ';\n';
  35501. }
  35502. this.flow.code += code;
  35503. return this;
  35504. }
  35505. /**
  35506. * Adds a code to the current code flow.
  35507. *
  35508. * @param {string} code - Shader code.
  35509. * @return {NodeBuilder} A reference to this node builder.
  35510. */
  35511. addFlowCode( code ) {
  35512. this.flow.code += code;
  35513. return this;
  35514. }
  35515. /**
  35516. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  35517. * Typically used in codes with If,Else.
  35518. *
  35519. * @return {NodeBuilder} A reference to this node builder.
  35520. */
  35521. addFlowTab() {
  35522. this.tab += '\t';
  35523. return this;
  35524. }
  35525. /**
  35526. * Removes a tab.
  35527. *
  35528. * @return {NodeBuilder} A reference to this node builder.
  35529. */
  35530. removeFlowTab() {
  35531. this.tab = this.tab.slice( 0, -1 );
  35532. return this;
  35533. }
  35534. /**
  35535. * Gets the current flow data based on a Node.
  35536. *
  35537. * @param {Node} node - Node that the flow was started.
  35538. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35539. * @return {Object} The flow data.
  35540. */
  35541. getFlowData( node/*, shaderStage*/ ) {
  35542. return this.flowsData.get( node );
  35543. }
  35544. /**
  35545. * Executes the node flow based on a root node to generate the final shader code.
  35546. *
  35547. * @param {Node} node - The node to execute.
  35548. * @return {Object} The code flow.
  35549. */
  35550. flowNode( node ) {
  35551. const output = node.getNodeType( this );
  35552. const flowData = this.flowChildNode( node, output );
  35553. this.flowsData.set( node, flowData );
  35554. return flowData;
  35555. }
  35556. /**
  35557. * Includes a node in the current function node.
  35558. *
  35559. * @param {Node} node - The node to include.
  35560. * @returns {void}
  35561. */
  35562. addInclude( node ) {
  35563. if ( this.currentFunctionNode !== null ) {
  35564. this.currentFunctionNode.includes.push( node );
  35565. }
  35566. }
  35567. /**
  35568. * Returns the native shader operator name for a given generic name.
  35569. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35570. *
  35571. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  35572. * @return {FunctionNode} The build function node.
  35573. */
  35574. buildFunctionNode( shaderNode ) {
  35575. const fn = new FunctionNode();
  35576. const previous = this.currentFunctionNode;
  35577. this.currentFunctionNode = fn;
  35578. fn.code = this.buildFunctionCode( shaderNode );
  35579. this.currentFunctionNode = previous;
  35580. return fn;
  35581. }
  35582. /**
  35583. * Generates a code flow based on a TSL function: Fn().
  35584. *
  35585. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  35586. * @return {Object}
  35587. */
  35588. flowShaderNode( shaderNode ) {
  35589. const layout = shaderNode.layout;
  35590. const inputs = {
  35591. [ Symbol.iterator ]() {
  35592. let index = 0;
  35593. const values = Object.values( this );
  35594. return {
  35595. next: () => ( {
  35596. value: values[ index ],
  35597. done: index ++ >= values.length
  35598. } )
  35599. };
  35600. }
  35601. };
  35602. for ( const input of layout.inputs ) {
  35603. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  35604. }
  35605. //
  35606. shaderNode.layout = null;
  35607. const callNode = shaderNode.call( inputs );
  35608. const flowData = this.flowStagesNode( callNode, layout.type );
  35609. shaderNode.layout = layout;
  35610. return flowData;
  35611. }
  35612. /**
  35613. * Executes the node in a specific build stage.
  35614. *
  35615. * This function can be used to arbitrarily execute the specified build stage
  35616. * outside of the standard build process. For instance, if a node's type depends
  35617. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  35618. * can be used to execute the setup build stage and access its generated nodes
  35619. * before the standard build process begins.
  35620. *
  35621. * @param {Node} node - The node to execute.
  35622. * @param {string} buildStage - The build stage to execute the node in.
  35623. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  35624. * @return {?(Node|string)} The result of the node build.
  35625. */
  35626. flowBuildStage( node, buildStage, output = null ) {
  35627. const previousBuildStage = this.getBuildStage();
  35628. this.setBuildStage( buildStage );
  35629. const result = node.build( this, output );
  35630. this.setBuildStage( previousBuildStage );
  35631. return result;
  35632. }
  35633. /**
  35634. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  35635. *
  35636. * @param {Node} node - The node to execute.
  35637. * @param {?string} output - Expected output type. For example 'vec3'.
  35638. * @return {Object}
  35639. */
  35640. flowStagesNode( node, output = null ) {
  35641. const previousFlow = this.flow;
  35642. const previousVars = this.vars;
  35643. const previousDeclarations = this.declarations;
  35644. const previousCache = this.cache;
  35645. const previousBuildStage = this.buildStage;
  35646. const previousStack = this.stack;
  35647. const flow = {
  35648. code: ''
  35649. };
  35650. this.flow = flow;
  35651. this.vars = {};
  35652. this.declarations = {};
  35653. this.cache = new NodeCache();
  35654. this.stack = stack();
  35655. for ( const buildStage of defaultBuildStages ) {
  35656. this.setBuildStage( buildStage );
  35657. flow.result = node.build( this, output );
  35658. }
  35659. flow.vars = this.getVars( this.shaderStage );
  35660. this.flow = previousFlow;
  35661. this.vars = previousVars;
  35662. this.declarations = previousDeclarations;
  35663. this.cache = previousCache;
  35664. this.stack = previousStack;
  35665. this.setBuildStage( previousBuildStage );
  35666. return flow;
  35667. }
  35668. /**
  35669. * Returns the native shader operator name for a given generic name.
  35670. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35671. *
  35672. * @abstract
  35673. * @param {string} op - The operator name to resolve.
  35674. * @return {?string} The resolved operator name.
  35675. */
  35676. getFunctionOperator( /* op */ ) {
  35677. return null;
  35678. }
  35679. /**
  35680. * Builds the given shader node.
  35681. *
  35682. * @abstract
  35683. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35684. * @return {string} The function code.
  35685. */
  35686. buildFunctionCode( /* shaderNode */ ) {
  35687. warn( 'Abstract function.' );
  35688. }
  35689. /**
  35690. * Generates a code flow based on a child Node.
  35691. *
  35692. * @param {Node} node - The node to execute.
  35693. * @param {?string} output - Expected output type. For example 'vec3'.
  35694. * @return {Object} The code flow.
  35695. */
  35696. flowChildNode( node, output = null ) {
  35697. const previousFlow = this.flow;
  35698. const flow = {
  35699. code: ''
  35700. };
  35701. this.flow = flow;
  35702. flow.result = node.build( this, output );
  35703. this.flow = previousFlow;
  35704. return flow;
  35705. }
  35706. /**
  35707. * Executes a flow of code in a different stage.
  35708. *
  35709. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35710. * return the value in fragment-stage even if it is being executed in an input fragment.
  35711. *
  35712. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35713. * @param {Node} node - The node to execute.
  35714. * @param {?string} output - Expected output type. For example 'vec3'.
  35715. * @param {?string} propertyName - The property name to assign the result.
  35716. * @return {?(Object|Node)} The code flow or node.build() result.
  35717. */
  35718. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35719. const previousTab = this.tab;
  35720. const previousCache = this.cache;
  35721. const previousShaderStage = this.shaderStage;
  35722. const previousContext = this.context;
  35723. this.setShaderStage( shaderStage );
  35724. const context = { ...this.context };
  35725. delete context.nodeBlock;
  35726. this.cache = this.globalCache;
  35727. this.tab = '\t';
  35728. this.context = context;
  35729. let result = null;
  35730. if ( this.buildStage === 'generate' ) {
  35731. const flowData = this.flowChildNode( node, output );
  35732. if ( propertyName !== null ) {
  35733. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  35734. }
  35735. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  35736. result = flowData;
  35737. } else {
  35738. result = node.build( this );
  35739. }
  35740. this.setShaderStage( previousShaderStage );
  35741. this.cache = previousCache;
  35742. this.tab = previousTab;
  35743. this.context = previousContext;
  35744. return result;
  35745. }
  35746. /**
  35747. * Returns an array holding all node attributes of this node builder.
  35748. *
  35749. * @return {Array<NodeAttribute>} The node attributes of this builder.
  35750. */
  35751. getAttributesArray() {
  35752. return this.attributes.concat( this.bufferAttributes );
  35753. }
  35754. /**
  35755. * Returns the attribute definitions as a shader string for the given shader stage.
  35756. *
  35757. * @abstract
  35758. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35759. * @return {string} The attribute code section.
  35760. */
  35761. getAttributes( /*shaderStage*/ ) {
  35762. warn( 'Abstract function.' );
  35763. }
  35764. /**
  35765. * Returns the varying definitions as a shader string for the given shader stage.
  35766. *
  35767. * @abstract
  35768. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35769. * @return {string} The varying code section.
  35770. */
  35771. getVaryings( /*shaderStage*/ ) {
  35772. warn( 'Abstract function.' );
  35773. }
  35774. /**
  35775. * Returns a single variable definition as a shader string for the given variable type and name.
  35776. *
  35777. * @param {string} type - The variable's type.
  35778. * @param {string} name - The variable's name.
  35779. * @param {?number} [count=null] - The array length.
  35780. * @return {string} The shader string.
  35781. */
  35782. getVar( type, name, count = null ) {
  35783. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  35784. }
  35785. /**
  35786. * Returns the variable definitions as a shader string for the given shader stage.
  35787. *
  35788. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35789. * @return {string} The variable code section.
  35790. */
  35791. getVars( shaderStage ) {
  35792. let snippet = '';
  35793. const vars = this.vars[ shaderStage ];
  35794. if ( vars !== undefined ) {
  35795. for ( const variable of vars ) {
  35796. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  35797. }
  35798. }
  35799. return snippet;
  35800. }
  35801. /**
  35802. * Returns the uniform definitions as a shader string for the given shader stage.
  35803. *
  35804. * @abstract
  35805. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35806. * @return {string} The uniform code section.
  35807. */
  35808. getUniforms( /*shaderStage*/ ) {
  35809. warn( 'Abstract function.' );
  35810. }
  35811. /**
  35812. * Returns the native code definitions as a shader string for the given shader stage.
  35813. *
  35814. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35815. * @return {string} The native code section.
  35816. */
  35817. getCodes( shaderStage ) {
  35818. const codes = this.codes[ shaderStage ];
  35819. let code = '';
  35820. if ( codes !== undefined ) {
  35821. for ( const nodeCode of codes ) {
  35822. code += nodeCode.code + '\n';
  35823. }
  35824. }
  35825. return code;
  35826. }
  35827. /**
  35828. * Returns the hash of this node builder.
  35829. *
  35830. * @return {string} The hash.
  35831. */
  35832. getHash() {
  35833. return this.vertexShader + this.fragmentShader + this.computeShader;
  35834. }
  35835. /**
  35836. * Sets the current shader stage.
  35837. *
  35838. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  35839. */
  35840. setShaderStage( shaderStage ) {
  35841. this.shaderStage = shaderStage;
  35842. }
  35843. /**
  35844. * Returns the current shader stage.
  35845. *
  35846. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  35847. */
  35848. getShaderStage() {
  35849. return this.shaderStage;
  35850. }
  35851. /**
  35852. * Sets the current build stage.
  35853. *
  35854. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  35855. */
  35856. setBuildStage( buildStage ) {
  35857. this.buildStage = buildStage;
  35858. }
  35859. /**
  35860. * Returns the current build stage.
  35861. *
  35862. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  35863. */
  35864. getBuildStage() {
  35865. return this.buildStage;
  35866. }
  35867. /**
  35868. * Controls the code build of the shader stages.
  35869. *
  35870. * @abstract
  35871. */
  35872. buildCode() {
  35873. warn( 'Abstract function.' );
  35874. }
  35875. /**
  35876. * Returns the current sub-build layer.
  35877. *
  35878. * @return {SubBuildNode} The current sub-build layers.
  35879. */
  35880. get subBuild() {
  35881. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  35882. }
  35883. /**
  35884. * Adds a sub-build layer to the node builder.
  35885. *
  35886. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  35887. */
  35888. addSubBuild( subBuild ) {
  35889. this.subBuildLayers.push( subBuild );
  35890. }
  35891. /**
  35892. * Removes the last sub-build layer from the node builder.
  35893. *
  35894. * @return {SubBuildNode} The removed sub-build layer.
  35895. */
  35896. removeSubBuild() {
  35897. return this.subBuildLayers.pop();
  35898. }
  35899. /**
  35900. * Returns the closest sub-build layer for the given data.
  35901. *
  35902. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  35903. * @return {?string} The closest sub-build name or null if none found.
  35904. */
  35905. getClosestSubBuild( data ) {
  35906. let subBuilds;
  35907. if ( data && data.isNode ) {
  35908. if ( data.isShaderCallNodeInternal ) {
  35909. subBuilds = data.shaderNode.subBuilds;
  35910. } else if ( data.isStackNode ) {
  35911. subBuilds = [ data.subBuild ];
  35912. } else {
  35913. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  35914. }
  35915. } else if ( data instanceof Set ) {
  35916. subBuilds = [ ...data ];
  35917. } else {
  35918. subBuilds = data;
  35919. }
  35920. if ( ! subBuilds ) return null;
  35921. const subBuildLayers = this.subBuildLayers;
  35922. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  35923. const subBuild = subBuilds[ i ];
  35924. if ( subBuildLayers.includes( subBuild ) ) {
  35925. return subBuild;
  35926. }
  35927. }
  35928. return null;
  35929. }
  35930. /**
  35931. * Returns the output node of a sub-build layer.
  35932. *
  35933. * @param {Node} node - The node to get the output from.
  35934. * @return {string} The output node name.
  35935. */
  35936. getSubBuildOutput( node ) {
  35937. return this.getSubBuildProperty( 'outputNode', node );
  35938. }
  35939. /**
  35940. * Returns the sub-build property name for the given property and node.
  35941. *
  35942. * @param {string} [property=''] - The property name.
  35943. * @param {?Node} [node=null] - The node to get the sub-build from.
  35944. * @return {string} The sub-build property name.
  35945. */
  35946. getSubBuildProperty( property = '', node = null ) {
  35947. let subBuild;
  35948. if ( node !== null ) {
  35949. subBuild = this.getClosestSubBuild( node );
  35950. } else {
  35951. subBuild = this.subBuildFn;
  35952. }
  35953. let result;
  35954. if ( subBuild ) {
  35955. result = property ? ( subBuild + '_' + property ) : subBuild;
  35956. } else {
  35957. result = property;
  35958. }
  35959. return result;
  35960. }
  35961. /**
  35962. * Central build method which controls the build for the given object.
  35963. *
  35964. * @return {NodeBuilder} A reference to this node builder.
  35965. */
  35966. build() {
  35967. const { object, material, renderer } = this;
  35968. if ( material !== null ) {
  35969. let nodeMaterial = renderer.library.fromMaterial( material );
  35970. if ( nodeMaterial === null ) {
  35971. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35972. nodeMaterial = new NodeMaterial();
  35973. }
  35974. nodeMaterial.build( this );
  35975. } else {
  35976. this.addFlow( 'compute', object );
  35977. }
  35978. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35979. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35980. // generate() -> stage 3: generate shader
  35981. for ( const buildStage of defaultBuildStages ) {
  35982. this.setBuildStage( buildStage );
  35983. if ( this.context.vertex && this.context.vertex.isNode ) {
  35984. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35985. }
  35986. for ( const shaderStage of shaderStages ) {
  35987. this.setShaderStage( shaderStage );
  35988. const flowNodes = this.flowNodes[ shaderStage ];
  35989. for ( const node of flowNodes ) {
  35990. if ( buildStage === 'generate' ) {
  35991. this.flowNode( node );
  35992. } else {
  35993. node.build( this );
  35994. }
  35995. }
  35996. }
  35997. }
  35998. this.setBuildStage( null );
  35999. this.setShaderStage( null );
  36000. // stage 4: build code for a specific output
  36001. this.buildCode();
  36002. this.buildUpdateNodes();
  36003. return this;
  36004. }
  36005. /**
  36006. * Returns a uniform representation which is later used for UBO generation and rendering.
  36007. *
  36008. * @param {NodeUniform} uniformNode - The uniform node.
  36009. * @param {string} type - The requested type.
  36010. * @return {Uniform} The uniform.
  36011. */
  36012. getNodeUniform( uniformNode, type ) {
  36013. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36014. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36015. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36016. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36017. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36018. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  36019. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36020. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36021. throw new Error( `Uniform "${type}" not declared.` );
  36022. }
  36023. /**
  36024. * Formats the given shader snippet from a given type into another one. E.g.
  36025. * this method might be used to convert a simple float string `"1.0"` into a
  36026. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  36027. *
  36028. * @param {string} snippet - The shader snippet.
  36029. * @param {string} fromType - The source type.
  36030. * @param {string} toType - The target type.
  36031. * @return {string} The updated shader string.
  36032. */
  36033. format( snippet, fromType, toType ) {
  36034. fromType = this.getVectorType( fromType );
  36035. toType = this.getVectorType( toType );
  36036. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36037. return snippet;
  36038. }
  36039. const fromTypeLength = this.getTypeLength( fromType );
  36040. const toTypeLength = this.getTypeLength( toType );
  36041. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36042. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  36043. }
  36044. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36045. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  36046. }
  36047. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36048. // @TODO: ignore for now
  36049. return snippet;
  36050. }
  36051. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36052. // @TODO: ignore for now
  36053. return snippet;
  36054. }
  36055. if ( fromTypeLength === toTypeLength ) {
  36056. return `${ this.getType( toType ) }( ${ snippet } )`;
  36057. }
  36058. if ( fromTypeLength > toTypeLength ) {
  36059. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  36060. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36061. }
  36062. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36063. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36064. }
  36065. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36066. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36067. }
  36068. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36069. // convert a number value to vector type, e.g:
  36070. // vec3( 1u ) -> vec3( float( 1u ) )
  36071. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36072. }
  36073. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36074. }
  36075. /**
  36076. * Returns a signature with the engine's current revision.
  36077. *
  36078. * @return {string} The signature.
  36079. */
  36080. getSignature() {
  36081. return `// Three.js r${ REVISION } - Node System\n`;
  36082. }
  36083. }
  36084. /**
  36085. * Management class for updating nodes. The module tracks metrics like
  36086. * the elapsed time, delta time, the render and frame ID to correctly
  36087. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  36088. * and {@link Node#updateAfter} depending on the node's configuration.
  36089. */
  36090. class NodeFrame {
  36091. /**
  36092. * Constructs a new node fame.
  36093. */
  36094. constructor() {
  36095. /**
  36096. * The elapsed time in seconds.
  36097. *
  36098. * @type {number}
  36099. * @default 0
  36100. */
  36101. this.time = 0;
  36102. /**
  36103. * The delta time in seconds.
  36104. *
  36105. * @type {number}
  36106. * @default 0
  36107. */
  36108. this.deltaTime = 0;
  36109. /**
  36110. * The frame ID.
  36111. *
  36112. * @type {number}
  36113. * @default 0
  36114. */
  36115. this.frameId = 0;
  36116. /**
  36117. * The render ID.
  36118. *
  36119. * @type {number}
  36120. * @default 0
  36121. */
  36122. this.renderId = 0;
  36123. /**
  36124. * Used to control the {@link Node#update} call.
  36125. *
  36126. * @type {WeakMap<Node, Object>}
  36127. */
  36128. this.updateMap = new WeakMap();
  36129. /**
  36130. * Used to control the {@link Node#updateBefore} call.
  36131. *
  36132. * @type {WeakMap<Node, Object>}
  36133. */
  36134. this.updateBeforeMap = new WeakMap();
  36135. /**
  36136. * Used to control the {@link Node#updateAfter} call.
  36137. *
  36138. * @type {WeakMap<Node, Object>}
  36139. */
  36140. this.updateAfterMap = new WeakMap();
  36141. /**
  36142. * A reference to the current renderer.
  36143. *
  36144. * @type {?Renderer}
  36145. * @default null
  36146. */
  36147. this.renderer = null;
  36148. /**
  36149. * A reference to the current material.
  36150. *
  36151. * @type {?Material}
  36152. * @default null
  36153. */
  36154. this.material = null;
  36155. /**
  36156. * A reference to the current camera.
  36157. *
  36158. * @type {?Camera}
  36159. * @default null
  36160. */
  36161. this.camera = null;
  36162. /**
  36163. * A reference to the current 3D object.
  36164. *
  36165. * @type {?Object3D}
  36166. * @default null
  36167. */
  36168. this.object = null;
  36169. /**
  36170. * A reference to the current scene.
  36171. *
  36172. * @type {?Scene}
  36173. * @default null
  36174. */
  36175. this.scene = null;
  36176. }
  36177. /**
  36178. * Returns a dictionary for a given node and update map which
  36179. * is used to correctly call node update methods per frame or render.
  36180. *
  36181. * @private
  36182. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  36183. * @param {Node} nodeRef - The reference to the current node.
  36184. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  36185. */
  36186. _getMaps( referenceMap, nodeRef ) {
  36187. let maps = referenceMap.get( nodeRef );
  36188. if ( maps === undefined ) {
  36189. maps = {
  36190. renderId: 0,
  36191. frameId: 0,
  36192. };
  36193. referenceMap.set( nodeRef, maps );
  36194. }
  36195. return maps;
  36196. }
  36197. /**
  36198. * This method executes the {@link Node#updateBefore} for the given node.
  36199. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  36200. * is only executed once per frame, render or object depending on the update
  36201. * type.
  36202. *
  36203. * @param {Node} node - The node that should be updated.
  36204. */
  36205. updateBeforeNode( node ) {
  36206. const updateType = node.getUpdateBeforeType();
  36207. const reference = node.updateReference( this );
  36208. if ( updateType === NodeUpdateType.FRAME ) {
  36209. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36210. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  36211. if ( node.updateBefore( this ) !== false ) {
  36212. nodeUpdateBeforeMap.frameId = this.frameId;
  36213. }
  36214. }
  36215. } else if ( updateType === NodeUpdateType.RENDER ) {
  36216. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36217. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  36218. if ( node.updateBefore( this ) !== false ) {
  36219. nodeUpdateBeforeMap.renderId = this.renderId;
  36220. }
  36221. }
  36222. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36223. node.updateBefore( this );
  36224. }
  36225. }
  36226. /**
  36227. * This method executes the {@link Node#updateAfter} for the given node.
  36228. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  36229. * is only executed once per frame, render or object depending on the update
  36230. * type.
  36231. *
  36232. * @param {Node} node - The node that should be updated.
  36233. */
  36234. updateAfterNode( node ) {
  36235. const updateType = node.getUpdateAfterType();
  36236. const reference = node.updateReference( this );
  36237. if ( updateType === NodeUpdateType.FRAME ) {
  36238. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36239. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  36240. if ( node.updateAfter( this ) !== false ) {
  36241. nodeUpdateAfterMap.frameId = this.frameId;
  36242. }
  36243. }
  36244. } else if ( updateType === NodeUpdateType.RENDER ) {
  36245. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36246. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  36247. if ( node.updateAfter( this ) !== false ) {
  36248. nodeUpdateAfterMap.renderId = this.renderId;
  36249. }
  36250. }
  36251. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36252. node.updateAfter( this );
  36253. }
  36254. }
  36255. /**
  36256. * This method executes the {@link Node#update} for the given node.
  36257. * It makes sure {@link Node#updateType} is honored meaning the update
  36258. * is only executed once per frame, render or object depending on the update
  36259. * type.
  36260. *
  36261. * @param {Node} node - The node that should be updated.
  36262. */
  36263. updateNode( node ) {
  36264. const updateType = node.getUpdateType();
  36265. const reference = node.updateReference( this );
  36266. if ( updateType === NodeUpdateType.FRAME ) {
  36267. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36268. if ( nodeUpdateMap.frameId !== this.frameId ) {
  36269. if ( node.update( this ) !== false ) {
  36270. nodeUpdateMap.frameId = this.frameId;
  36271. }
  36272. }
  36273. } else if ( updateType === NodeUpdateType.RENDER ) {
  36274. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36275. if ( nodeUpdateMap.renderId !== this.renderId ) {
  36276. if ( node.update( this ) !== false ) {
  36277. nodeUpdateMap.renderId = this.renderId;
  36278. }
  36279. }
  36280. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36281. node.update( this );
  36282. }
  36283. }
  36284. /**
  36285. * Updates the internal state of the node frame. This method is
  36286. * called by the renderer in its internal animation loop.
  36287. */
  36288. update() {
  36289. this.frameId ++;
  36290. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36291. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36292. this.lastTime = performance.now();
  36293. this.time += this.deltaTime;
  36294. }
  36295. }
  36296. /**
  36297. * Describes the input of a {@link NodeFunction}.
  36298. */
  36299. class NodeFunctionInput {
  36300. /**
  36301. * Constructs a new node function input.
  36302. *
  36303. * @param {string} type - The input type.
  36304. * @param {string} name - The input name.
  36305. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  36306. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  36307. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  36308. */
  36309. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36310. /**
  36311. * The input type.
  36312. *
  36313. * @type {string}
  36314. */
  36315. this.type = type;
  36316. /**
  36317. * The input name.
  36318. *
  36319. * @type {string}
  36320. */
  36321. this.name = name;
  36322. /**
  36323. * If the input is an Array, count will be the length.
  36324. *
  36325. * @type {?number}
  36326. * @default null
  36327. */
  36328. this.count = count;
  36329. /**
  36330. *The parameter qualifier (only relevant for GLSL).
  36331. *
  36332. * @type {('in'|'out'|'inout')}
  36333. * @default ''
  36334. */
  36335. this.qualifier = qualifier;
  36336. /**
  36337. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  36338. *
  36339. * @type {boolean}
  36340. * @default false
  36341. */
  36342. this.isConst = isConst;
  36343. }
  36344. }
  36345. NodeFunctionInput.isNodeFunctionInput = true;
  36346. /**
  36347. * Module for representing directional lights as nodes.
  36348. *
  36349. * @augments AnalyticLightNode
  36350. */
  36351. class DirectionalLightNode extends AnalyticLightNode {
  36352. static get type() {
  36353. return 'DirectionalLightNode';
  36354. }
  36355. /**
  36356. * Constructs a new directional light node.
  36357. *
  36358. * @param {?DirectionalLight} [light=null] - The directional light source.
  36359. */
  36360. constructor( light = null ) {
  36361. super( light );
  36362. }
  36363. setupDirect() {
  36364. const lightColor = this.colorNode;
  36365. const lightDirection = lightTargetDirection( this.light );
  36366. return { lightDirection, lightColor };
  36367. }
  36368. }
  36369. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36370. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36371. let _ltcLib = null;
  36372. /**
  36373. * Module for representing rect area lights as nodes.
  36374. *
  36375. * @augments AnalyticLightNode
  36376. */
  36377. class RectAreaLightNode extends AnalyticLightNode {
  36378. static get type() {
  36379. return 'RectAreaLightNode';
  36380. }
  36381. /**
  36382. * Constructs a new rect area light node.
  36383. *
  36384. * @param {?RectAreaLight} [light=null] - The rect area light source.
  36385. */
  36386. constructor( light = null ) {
  36387. super( light );
  36388. /**
  36389. * Uniform node representing the half height of the are light.
  36390. *
  36391. * @type {UniformNode<vec3>}
  36392. */
  36393. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36394. /**
  36395. * Uniform node representing the half width of the are light.
  36396. *
  36397. * @type {UniformNode<vec3>}
  36398. */
  36399. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36400. /**
  36401. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  36402. * relies on `viewMatrix` which might vary per render call.
  36403. *
  36404. * @type {string}
  36405. * @default 'render'
  36406. */
  36407. this.updateType = NodeUpdateType.RENDER;
  36408. }
  36409. /**
  36410. * Overwritten to updated rect area light specific uniforms.
  36411. *
  36412. * @param {NodeFrame} frame - A reference to the current node frame.
  36413. */
  36414. update( frame ) {
  36415. super.update( frame );
  36416. const { light } = this;
  36417. const viewMatrix = frame.camera.matrixWorldInverse;
  36418. _matrix42.identity();
  36419. _matrix41.copy( light.matrixWorld );
  36420. _matrix41.premultiply( viewMatrix );
  36421. _matrix42.extractRotation( _matrix41 );
  36422. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36423. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36424. this.halfWidth.value.applyMatrix4( _matrix42 );
  36425. this.halfHeight.value.applyMatrix4( _matrix42 );
  36426. }
  36427. setupDirectRectArea( builder ) {
  36428. let ltc_1, ltc_2;
  36429. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36430. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  36431. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  36432. } else {
  36433. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  36434. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  36435. }
  36436. const { colorNode, light } = this;
  36437. const lightPosition = lightViewPosition( light );
  36438. return {
  36439. lightColor: colorNode,
  36440. lightPosition,
  36441. halfWidth: this.halfWidth,
  36442. halfHeight: this.halfHeight,
  36443. ltc_1,
  36444. ltc_2
  36445. };
  36446. }
  36447. /**
  36448. * Used to configure the internal BRDF approximation texture data.
  36449. *
  36450. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  36451. */
  36452. static setLTC( ltc ) {
  36453. _ltcLib = ltc;
  36454. }
  36455. }
  36456. /**
  36457. * Module for representing spot lights as nodes.
  36458. *
  36459. * @augments AnalyticLightNode
  36460. */
  36461. class SpotLightNode extends AnalyticLightNode {
  36462. static get type() {
  36463. return 'SpotLightNode';
  36464. }
  36465. /**
  36466. * Constructs a new spot light node.
  36467. *
  36468. * @param {?SpotLight} [light=null] - The spot light source.
  36469. */
  36470. constructor( light = null ) {
  36471. super( light );
  36472. /**
  36473. * Uniform node representing the cone cosine.
  36474. *
  36475. * @type {UniformNode<float>}
  36476. */
  36477. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36478. /**
  36479. * Uniform node representing the penumbra cosine.
  36480. *
  36481. * @type {UniformNode<float>}
  36482. */
  36483. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36484. /**
  36485. * Uniform node representing the cutoff distance.
  36486. *
  36487. * @type {UniformNode<float>}
  36488. */
  36489. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36490. /**
  36491. * Uniform node representing the decay exponent.
  36492. *
  36493. * @type {UniformNode<float>}
  36494. */
  36495. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36496. /**
  36497. * Uniform node representing the light color.
  36498. *
  36499. * @type {UniformNode<Color>}
  36500. */
  36501. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  36502. }
  36503. /**
  36504. * Overwritten to updated spot light specific uniforms.
  36505. *
  36506. * @param {NodeFrame} frame - A reference to the current node frame.
  36507. */
  36508. update( frame ) {
  36509. super.update( frame );
  36510. const { light } = this;
  36511. this.coneCosNode.value = Math.cos( light.angle );
  36512. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36513. this.cutoffDistanceNode.value = light.distance;
  36514. this.decayExponentNode.value = light.decay;
  36515. }
  36516. /**
  36517. * Computes the spot attenuation for the given angle.
  36518. *
  36519. * @param {NodeBuilder} builder - The node builder.
  36520. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36521. * @return {Node<float>} The spot attenuation.
  36522. */
  36523. getSpotAttenuation( builder, angleCosine ) {
  36524. const { coneCosNode, penumbraCosNode } = this;
  36525. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36526. }
  36527. getLightCoord( builder ) {
  36528. const properties = builder.getNodeProperties( this );
  36529. let projectionUV = properties.projectionUV;
  36530. if ( projectionUV === undefined ) {
  36531. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  36532. properties.projectionUV = projectionUV;
  36533. }
  36534. return projectionUV;
  36535. }
  36536. setupDirect( builder ) {
  36537. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36538. const lightVector = this.getLightVector( builder );
  36539. const lightDirection = lightVector.normalize();
  36540. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36541. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  36542. const lightDistance = lightVector.length();
  36543. const lightAttenuation = getDistanceAttenuation( {
  36544. lightDistance,
  36545. cutoffDistance: cutoffDistanceNode,
  36546. decayExponent: decayExponentNode
  36547. } );
  36548. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36549. let projected, lightCoord;
  36550. if ( light.colorNode ) {
  36551. lightCoord = this.getLightCoord( builder );
  36552. projected = light.colorNode( lightCoord );
  36553. } else if ( light.map ) {
  36554. lightCoord = this.getLightCoord( builder );
  36555. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  36556. }
  36557. if ( projected ) {
  36558. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  36559. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  36560. }
  36561. return { lightColor, lightDirection };
  36562. }
  36563. }
  36564. /**
  36565. * An IES version of the default spot light node.
  36566. *
  36567. * @augments SpotLightNode
  36568. */
  36569. class IESSpotLightNode extends SpotLightNode {
  36570. static get type() {
  36571. return 'IESSpotLightNode';
  36572. }
  36573. /**
  36574. * Overwrites the default implementation to compute an IES conform spot attenuation.
  36575. *
  36576. * @param {NodeBuilder} builder - The node builder.
  36577. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36578. * @return {Node<float>} The spot attenuation.
  36579. */
  36580. getSpotAttenuation( builder, angleCosine ) {
  36581. const iesMap = this.light.iesMap;
  36582. let spotAttenuation = null;
  36583. if ( iesMap && iesMap.isTexture === true ) {
  36584. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36585. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36586. } else {
  36587. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36588. }
  36589. return spotAttenuation;
  36590. }
  36591. }
  36592. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  36593. const d = p.abs().sub( b );
  36594. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  36595. } );
  36596. /**
  36597. * An implementation of a projector light node.
  36598. *
  36599. * @augments SpotLightNode
  36600. */
  36601. class ProjectorLightNode extends SpotLightNode {
  36602. static get type() {
  36603. return 'ProjectorLightNode';
  36604. }
  36605. update( frame ) {
  36606. super.update( frame );
  36607. const light = this.light;
  36608. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  36609. if ( light.aspect === null ) {
  36610. let aspect = 1;
  36611. if ( light.map !== null ) {
  36612. aspect = light.map.width / light.map.height;
  36613. }
  36614. light.shadow.aspect = aspect;
  36615. } else {
  36616. light.shadow.aspect = light.aspect;
  36617. }
  36618. }
  36619. /**
  36620. * Overwrites the default implementation to compute projection attenuation.
  36621. *
  36622. * @param {NodeBuilder} builder - The node builder.
  36623. * @return {Node<float>} The spot attenuation.
  36624. */
  36625. getSpotAttenuation( builder ) {
  36626. const attenuation = float( 0 );
  36627. const penumbraCos = this.penumbraCosNode;
  36628. // compute the fragment's position in the light's clip space
  36629. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  36630. // the sign of w determines whether the current fragment is in front or behind the light.
  36631. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  36632. If( spotLightCoord.w.greaterThan( 0 ), () => {
  36633. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  36634. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  36635. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36636. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36637. } );
  36638. return attenuation;
  36639. }
  36640. }
  36641. /**
  36642. * Module for representing ambient lights as nodes.
  36643. *
  36644. * @augments AnalyticLightNode
  36645. */
  36646. class AmbientLightNode extends AnalyticLightNode {
  36647. static get type() {
  36648. return 'AmbientLightNode';
  36649. }
  36650. /**
  36651. * Constructs a new ambient light node.
  36652. *
  36653. * @param {?AmbientLight} [light=null] - The ambient light source.
  36654. */
  36655. constructor( light = null ) {
  36656. super( light );
  36657. }
  36658. setup( { context } ) {
  36659. context.irradiance.addAssign( this.colorNode );
  36660. }
  36661. }
  36662. /**
  36663. * Module for representing hemisphere lights as nodes.
  36664. *
  36665. * @augments AnalyticLightNode
  36666. */
  36667. class HemisphereLightNode extends AnalyticLightNode {
  36668. static get type() {
  36669. return 'HemisphereLightNode';
  36670. }
  36671. /**
  36672. * Constructs a new hemisphere light node.
  36673. *
  36674. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36675. */
  36676. constructor( light = null ) {
  36677. super( light );
  36678. /**
  36679. * Uniform node representing the light's position.
  36680. *
  36681. * @type {UniformNode<vec3>}
  36682. */
  36683. this.lightPositionNode = lightPosition( light );
  36684. /**
  36685. * A node representing the light's direction.
  36686. *
  36687. * @type {Node<vec3>}
  36688. */
  36689. this.lightDirectionNode = this.lightPositionNode.normalize();
  36690. /**
  36691. * Uniform node representing the light's ground color.
  36692. *
  36693. * @type {UniformNode<vec3>}
  36694. */
  36695. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36696. }
  36697. /**
  36698. * Overwritten to updated hemisphere light specific uniforms.
  36699. *
  36700. * @param {NodeFrame} frame - A reference to the current node frame.
  36701. */
  36702. update( frame ) {
  36703. const { light } = this;
  36704. super.update( frame );
  36705. this.lightPositionNode.object3d = light;
  36706. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36707. }
  36708. setup( builder ) {
  36709. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36710. const dotNL = normalWorld.dot( lightDirectionNode );
  36711. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36712. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36713. builder.context.irradiance.addAssign( irradiance );
  36714. }
  36715. }
  36716. /**
  36717. * Module for representing light probes as nodes.
  36718. *
  36719. * @augments AnalyticLightNode
  36720. */
  36721. class LightProbeNode extends AnalyticLightNode {
  36722. static get type() {
  36723. return 'LightProbeNode';
  36724. }
  36725. /**
  36726. * Constructs a new light probe node.
  36727. *
  36728. * @param {?LightProbe} [light=null] - The light probe.
  36729. */
  36730. constructor( light = null ) {
  36731. super( light );
  36732. const array = [];
  36733. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36734. /**
  36735. * Light probe represented as a uniform of spherical harmonics.
  36736. *
  36737. * @type {UniformArrayNode}
  36738. */
  36739. this.lightProbe = uniformArray( array );
  36740. }
  36741. /**
  36742. * Overwritten to updated light probe specific uniforms.
  36743. *
  36744. * @param {NodeFrame} frame - A reference to the current node frame.
  36745. */
  36746. update( frame ) {
  36747. const { light } = this;
  36748. super.update( frame );
  36749. //
  36750. for ( let i = 0; i < 9; i ++ ) {
  36751. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36752. }
  36753. }
  36754. setup( builder ) {
  36755. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36756. builder.context.irradiance.addAssign( irradiance );
  36757. }
  36758. }
  36759. /**
  36760. * Base class for node parsers. A derived parser must be implemented
  36761. * for each supported native shader language.
  36762. */
  36763. class NodeParser {
  36764. /**
  36765. * The method parses the given native code an returns a node function.
  36766. *
  36767. * @abstract
  36768. * @param {string} source - The native shader code.
  36769. * @return {NodeFunction} A node function.
  36770. */
  36771. parseFunction( /*source*/ ) {
  36772. warn( 'Abstract function.' );
  36773. }
  36774. }
  36775. /**
  36776. * Base class for node functions. A derived module must be implemented
  36777. * for each supported native shader language. Similar to other `Node*` modules,
  36778. * this class is only relevant during the building process and not used
  36779. * in user-level code.
  36780. */
  36781. class NodeFunction {
  36782. /**
  36783. * Constructs a new node function.
  36784. *
  36785. * @param {string} type - The node type. This type is the return type of the node function.
  36786. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  36787. * @param {string} [name=''] - The function's name.
  36788. * @param {string} [precision=''] - The precision qualifier.
  36789. */
  36790. constructor( type, inputs, name = '', precision = '' ) {
  36791. /**
  36792. * The node type. This type is the return type of the node function.
  36793. *
  36794. * @type {string}
  36795. */
  36796. this.type = type;
  36797. /**
  36798. * The function's inputs.
  36799. *
  36800. * @type {Array<NodeFunctionInput>}
  36801. */
  36802. this.inputs = inputs;
  36803. /**
  36804. * The name of the uniform.
  36805. *
  36806. * @type {string}
  36807. * @default ''
  36808. */
  36809. this.name = name;
  36810. /**
  36811. * The precision qualifier.
  36812. *
  36813. * @type {string}
  36814. * @default ''
  36815. */
  36816. this.precision = precision;
  36817. }
  36818. /**
  36819. * This method returns the native code of the node function.
  36820. *
  36821. * @abstract
  36822. * @param {string} name - The function's name.
  36823. * @return {string} A shader code.
  36824. */
  36825. getCode( /*name = this.name*/ ) {
  36826. warn( 'Abstract function.' );
  36827. }
  36828. }
  36829. NodeFunction.isNodeFunction = true;
  36830. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36831. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36832. const pragmaMain = '#pragma main';
  36833. const parse$1 = ( source ) => {
  36834. source = source.trim();
  36835. const pragmaMainIndex = source.indexOf( pragmaMain );
  36836. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36837. const declaration = mainCode.match( declarationRegexp$1 );
  36838. if ( declaration !== null && declaration.length === 5 ) {
  36839. // tokenizer
  36840. const inputsCode = declaration[ 4 ];
  36841. const propsMatches = [];
  36842. let nameMatch = null;
  36843. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36844. propsMatches.push( nameMatch );
  36845. }
  36846. // parser
  36847. const inputs = [];
  36848. let i = 0;
  36849. while ( i < propsMatches.length ) {
  36850. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36851. if ( isConst === true ) {
  36852. i ++;
  36853. }
  36854. let qualifier = propsMatches[ i ][ 0 ];
  36855. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36856. i ++;
  36857. } else {
  36858. qualifier = '';
  36859. }
  36860. const type = propsMatches[ i ++ ][ 0 ];
  36861. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36862. if ( Number.isNaN( count ) === false ) i ++;
  36863. else count = null;
  36864. const name = propsMatches[ i ++ ][ 0 ];
  36865. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36866. }
  36867. //
  36868. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36869. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36870. const type = declaration[ 2 ];
  36871. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36872. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  36873. return {
  36874. type,
  36875. inputs,
  36876. name,
  36877. precision,
  36878. inputsCode,
  36879. blockCode,
  36880. headerCode
  36881. };
  36882. } else {
  36883. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36884. }
  36885. };
  36886. /**
  36887. * This class represents a GLSL node function.
  36888. *
  36889. * @augments NodeFunction
  36890. */
  36891. class GLSLNodeFunction extends NodeFunction {
  36892. /**
  36893. * Constructs a new GLSL node function.
  36894. *
  36895. * @param {string} source - The GLSL source.
  36896. */
  36897. constructor( source ) {
  36898. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36899. super( type, inputs, name, precision );
  36900. this.inputsCode = inputsCode;
  36901. this.blockCode = blockCode;
  36902. this.headerCode = headerCode;
  36903. }
  36904. /**
  36905. * This method returns the GLSL code of the node function.
  36906. *
  36907. * @param {string} [name=this.name] - The function's name.
  36908. * @return {string} The shader code.
  36909. */
  36910. getCode( name = this.name ) {
  36911. let code;
  36912. const blockCode = this.blockCode;
  36913. if ( blockCode !== '' ) {
  36914. const { type, inputsCode, headerCode, precision } = this;
  36915. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36916. if ( precision !== '' ) {
  36917. declarationCode = `${ precision } ${ declarationCode }`;
  36918. }
  36919. code = headerCode + declarationCode + blockCode;
  36920. } else {
  36921. // interface function
  36922. code = '';
  36923. }
  36924. return code;
  36925. }
  36926. }
  36927. /**
  36928. * A GLSL node parser.
  36929. *
  36930. * @augments NodeParser
  36931. */
  36932. class GLSLNodeParser extends NodeParser {
  36933. /**
  36934. * The method parses the given GLSL code an returns a node function.
  36935. *
  36936. * @param {string} source - The GLSL code.
  36937. * @return {GLSLNodeFunction} A node function.
  36938. */
  36939. parseFunction( source ) {
  36940. return new GLSLNodeFunction( source );
  36941. }
  36942. }
  36943. const _outputNodeMap = new WeakMap();
  36944. const _chainKeys$2 = [];
  36945. const _cacheKeyValues = [];
  36946. /**
  36947. * This renderer module manages node-related objects and is the
  36948. * primary interface between the renderer and the node system.
  36949. *
  36950. * @private
  36951. * @augments DataMap
  36952. */
  36953. class Nodes extends DataMap {
  36954. /**
  36955. * Constructs a new nodes management component.
  36956. *
  36957. * @param {Renderer} renderer - The renderer.
  36958. * @param {Backend} backend - The renderer's backend.
  36959. */
  36960. constructor( renderer, backend ) {
  36961. super();
  36962. /**
  36963. * The renderer.
  36964. *
  36965. * @type {Renderer}
  36966. */
  36967. this.renderer = renderer;
  36968. /**
  36969. * The renderer's backend.
  36970. *
  36971. * @type {Backend}
  36972. */
  36973. this.backend = backend;
  36974. /**
  36975. * The node frame.
  36976. *
  36977. * @type {Renderer}
  36978. */
  36979. this.nodeFrame = new NodeFrame();
  36980. /**
  36981. * A cache for managing node builder states.
  36982. *
  36983. * @type {Map<number,NodeBuilderState>}
  36984. */
  36985. this.nodeBuilderCache = new Map();
  36986. /**
  36987. * A cache for managing data cache key data.
  36988. *
  36989. * @type {ChainMap}
  36990. */
  36991. this.callHashCache = new ChainMap();
  36992. /**
  36993. * A cache for managing node uniforms group data.
  36994. *
  36995. * @type {ChainMap}
  36996. */
  36997. this.groupsData = new ChainMap();
  36998. /**
  36999. * A cache for managing node objects of
  37000. * scene properties like fog or environments.
  37001. *
  37002. * @type {Object<string,WeakMap>}
  37003. */
  37004. this.cacheLib = {};
  37005. }
  37006. /**
  37007. * Returns `true` if the given node uniforms group must be updated or not.
  37008. *
  37009. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  37010. * @return {boolean} Whether the node uniforms group requires an update or not.
  37011. */
  37012. updateGroup( nodeUniformsGroup ) {
  37013. const groupNode = nodeUniformsGroup.groupNode;
  37014. const name = groupNode.name;
  37015. // objectGroup is always updated
  37016. if ( name === objectGroup.name ) return true;
  37017. // renderGroup is updated once per render/compute call
  37018. if ( name === renderGroup.name ) {
  37019. const uniformsGroupData = this.get( nodeUniformsGroup );
  37020. const renderId = this.nodeFrame.renderId;
  37021. if ( uniformsGroupData.renderId !== renderId ) {
  37022. uniformsGroupData.renderId = renderId;
  37023. return true;
  37024. }
  37025. return false;
  37026. }
  37027. // frameGroup is updated once per frame
  37028. if ( name === frameGroup.name ) {
  37029. const uniformsGroupData = this.get( nodeUniformsGroup );
  37030. const frameId = this.nodeFrame.frameId;
  37031. if ( uniformsGroupData.frameId !== frameId ) {
  37032. uniformsGroupData.frameId = frameId;
  37033. return true;
  37034. }
  37035. return false;
  37036. }
  37037. // other groups are updated just when groupNode.needsUpdate is true
  37038. _chainKeys$2[ 0 ] = groupNode;
  37039. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  37040. let groupData = this.groupsData.get( _chainKeys$2 );
  37041. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  37042. _chainKeys$2.length = 0;
  37043. if ( groupData.version !== groupNode.version ) {
  37044. groupData.version = groupNode.version;
  37045. return true;
  37046. }
  37047. return false;
  37048. }
  37049. /**
  37050. * Returns the cache key for the given render object.
  37051. *
  37052. * @param {RenderObject} renderObject - The render object.
  37053. * @return {number} The cache key.
  37054. */
  37055. getForRenderCacheKey( renderObject ) {
  37056. return renderObject.initialCacheKey;
  37057. }
  37058. /**
  37059. * Returns a node builder state for the given render object.
  37060. *
  37061. * @param {RenderObject} renderObject - The render object.
  37062. * @return {NodeBuilderState} The node builder state.
  37063. */
  37064. getForRender( renderObject ) {
  37065. const renderObjectData = this.get( renderObject );
  37066. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37067. if ( nodeBuilderState === undefined ) {
  37068. const { nodeBuilderCache } = this;
  37069. const cacheKey = this.getForRenderCacheKey( renderObject );
  37070. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37071. if ( nodeBuilderState === undefined ) {
  37072. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37073. nodeBuilder.scene = renderObject.scene;
  37074. nodeBuilder.material = renderObject.material;
  37075. nodeBuilder.camera = renderObject.camera;
  37076. nodeBuilder.context.material = renderObject.material;
  37077. nodeBuilder.lightsNode = renderObject.lightsNode;
  37078. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37079. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37080. nodeBuilder.clippingContext = renderObject.clippingContext;
  37081. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  37082. nodeBuilder.enableMultiview();
  37083. }
  37084. nodeBuilder.build();
  37085. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37086. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37087. }
  37088. nodeBuilderState.usedTimes ++;
  37089. renderObjectData.nodeBuilderState = nodeBuilderState;
  37090. }
  37091. return nodeBuilderState;
  37092. }
  37093. /**
  37094. * Deletes the given object from the internal data map
  37095. *
  37096. * @param {any} object - The object to delete.
  37097. * @return {?Object} The deleted dictionary.
  37098. */
  37099. delete( object ) {
  37100. if ( object.isRenderObject ) {
  37101. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37102. nodeBuilderState.usedTimes --;
  37103. if ( nodeBuilderState.usedTimes === 0 ) {
  37104. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37105. }
  37106. }
  37107. return super.delete( object );
  37108. }
  37109. /**
  37110. * Returns a node builder state for the given compute node.
  37111. *
  37112. * @param {Node} computeNode - The compute node.
  37113. * @return {NodeBuilderState} The node builder state.
  37114. */
  37115. getForCompute( computeNode ) {
  37116. const computeData = this.get( computeNode );
  37117. let nodeBuilderState = computeData.nodeBuilderState;
  37118. if ( nodeBuilderState === undefined ) {
  37119. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37120. nodeBuilder.build();
  37121. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37122. computeData.nodeBuilderState = nodeBuilderState;
  37123. }
  37124. return nodeBuilderState;
  37125. }
  37126. /**
  37127. * Creates a node builder state for the given node builder.
  37128. *
  37129. * @private
  37130. * @param {NodeBuilder} nodeBuilder - The node builder.
  37131. * @return {NodeBuilderState} The node builder state.
  37132. */
  37133. _createNodeBuilderState( nodeBuilder ) {
  37134. return new NodeBuilderState(
  37135. nodeBuilder.vertexShader,
  37136. nodeBuilder.fragmentShader,
  37137. nodeBuilder.computeShader,
  37138. nodeBuilder.getAttributesArray(),
  37139. nodeBuilder.getBindings(),
  37140. nodeBuilder.updateNodes,
  37141. nodeBuilder.updateBeforeNodes,
  37142. nodeBuilder.updateAfterNodes,
  37143. nodeBuilder.observer,
  37144. nodeBuilder.transforms
  37145. );
  37146. }
  37147. /**
  37148. * Returns an environment node for the current configured
  37149. * scene environment.
  37150. *
  37151. * @param {Scene} scene - The scene.
  37152. * @return {Node} A node representing the current scene environment.
  37153. */
  37154. getEnvironmentNode( scene ) {
  37155. this.updateEnvironment( scene );
  37156. let environmentNode = null;
  37157. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  37158. environmentNode = scene.environmentNode;
  37159. } else {
  37160. const sceneData = this.get( scene );
  37161. if ( sceneData.environmentNode ) {
  37162. environmentNode = sceneData.environmentNode;
  37163. }
  37164. }
  37165. return environmentNode;
  37166. }
  37167. /**
  37168. * Returns a background node for the current configured
  37169. * scene background.
  37170. *
  37171. * @param {Scene} scene - The scene.
  37172. * @return {Node} A node representing the current scene background.
  37173. */
  37174. getBackgroundNode( scene ) {
  37175. this.updateBackground( scene );
  37176. let backgroundNode = null;
  37177. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  37178. backgroundNode = scene.backgroundNode;
  37179. } else {
  37180. const sceneData = this.get( scene );
  37181. if ( sceneData.backgroundNode ) {
  37182. backgroundNode = sceneData.backgroundNode;
  37183. }
  37184. }
  37185. return backgroundNode;
  37186. }
  37187. /**
  37188. * Returns a fog node for the current configured scene fog.
  37189. *
  37190. * @param {Scene} scene - The scene.
  37191. * @return {Node} A node representing the current scene fog.
  37192. */
  37193. getFogNode( scene ) {
  37194. this.updateFog( scene );
  37195. return scene.fogNode || this.get( scene ).fogNode || null;
  37196. }
  37197. /**
  37198. * Returns a cache key for the given scene and lights node.
  37199. * This key is used by `RenderObject` as a part of the dynamic
  37200. * cache key (a key that must be checked every time the render
  37201. * objects is drawn).
  37202. *
  37203. * @param {Scene} scene - The scene.
  37204. * @param {LightsNode} lightsNode - The lights node.
  37205. * @return {number} The cache key.
  37206. */
  37207. getCacheKey( scene, lightsNode ) {
  37208. _chainKeys$2[ 0 ] = scene;
  37209. _chainKeys$2[ 1 ] = lightsNode;
  37210. const callId = this.renderer.info.calls;
  37211. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  37212. if ( cacheKeyData.callId !== callId ) {
  37213. const environmentNode = this.getEnvironmentNode( scene );
  37214. const fogNode = this.getFogNode( scene );
  37215. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  37216. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  37217. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  37218. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  37219. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37220. cacheKeyData.callId = callId;
  37221. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  37222. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  37223. _cacheKeyValues.length = 0;
  37224. }
  37225. _chainKeys$2.length = 0;
  37226. return cacheKeyData.cacheKey;
  37227. }
  37228. /**
  37229. * A boolean that indicates whether tone mapping should be enabled
  37230. * or not.
  37231. *
  37232. * @type {boolean}
  37233. */
  37234. get isToneMappingState() {
  37235. return this.renderer.getRenderTarget() ? false : true;
  37236. }
  37237. /**
  37238. * If a scene background is configured, this method makes sure to
  37239. * represent the background with a corresponding node-based implementation.
  37240. *
  37241. * @param {Scene} scene - The scene.
  37242. */
  37243. updateBackground( scene ) {
  37244. const sceneData = this.get( scene );
  37245. const background = scene.background;
  37246. if ( background ) {
  37247. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37248. if ( sceneData.background !== background || forceUpdate ) {
  37249. const backgroundNode = this.getCacheNode( 'background', background, () => {
  37250. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37251. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37252. return pmremTexture( background );
  37253. } else {
  37254. let envMap;
  37255. if ( background.isCubeTexture === true ) {
  37256. envMap = cubeTexture( background );
  37257. } else {
  37258. envMap = texture( background );
  37259. }
  37260. return cubeMapNode( envMap );
  37261. }
  37262. } else if ( background.isTexture === true ) {
  37263. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37264. } else if ( background.isColor !== true ) {
  37265. error( 'WebGPUNodes: Unsupported background configuration.', background );
  37266. }
  37267. }, forceUpdate );
  37268. sceneData.backgroundNode = backgroundNode;
  37269. sceneData.background = background;
  37270. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37271. }
  37272. } else if ( sceneData.backgroundNode ) {
  37273. delete sceneData.backgroundNode;
  37274. delete sceneData.background;
  37275. }
  37276. }
  37277. /**
  37278. * This method is part of the caching of nodes which are used to represents the
  37279. * scene's background, fog or environment.
  37280. *
  37281. * @param {string} type - The type of object to cache.
  37282. * @param {Object} object - The object.
  37283. * @param {Function} callback - A callback that produces a node representation for the given object.
  37284. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  37285. * @return {Node} The node representation.
  37286. */
  37287. getCacheNode( type, object, callback, forceUpdate = false ) {
  37288. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  37289. let node = nodeCache.get( object );
  37290. if ( node === undefined || forceUpdate ) {
  37291. node = callback();
  37292. nodeCache.set( object, node );
  37293. }
  37294. return node;
  37295. }
  37296. /**
  37297. * If a scene fog is configured, this method makes sure to
  37298. * represent the fog with a corresponding node-based implementation.
  37299. *
  37300. * @param {Scene} scene - The scene.
  37301. */
  37302. updateFog( scene ) {
  37303. const sceneData = this.get( scene );
  37304. const sceneFog = scene.fog;
  37305. if ( sceneFog ) {
  37306. if ( sceneData.fog !== sceneFog ) {
  37307. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  37308. if ( sceneFog.isFogExp2 ) {
  37309. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37310. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  37311. return fog( color, densityFogFactor( density ) );
  37312. } else if ( sceneFog.isFog ) {
  37313. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37314. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  37315. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  37316. return fog( color, rangeFogFactor( near, far ) );
  37317. } else {
  37318. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  37319. }
  37320. } );
  37321. sceneData.fogNode = fogNode;
  37322. sceneData.fog = sceneFog;
  37323. }
  37324. } else {
  37325. delete sceneData.fogNode;
  37326. delete sceneData.fog;
  37327. }
  37328. }
  37329. /**
  37330. * If a scene environment is configured, this method makes sure to
  37331. * represent the environment with a corresponding node-based implementation.
  37332. *
  37333. * @param {Scene} scene - The scene.
  37334. */
  37335. updateEnvironment( scene ) {
  37336. const sceneData = this.get( scene );
  37337. const environment = scene.environment;
  37338. if ( environment ) {
  37339. if ( sceneData.environment !== environment ) {
  37340. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  37341. if ( environment.isCubeTexture === true ) {
  37342. return cubeTexture( environment );
  37343. } else if ( environment.isTexture === true ) {
  37344. return texture( environment );
  37345. } else {
  37346. error( 'Nodes: Unsupported environment configuration.', environment );
  37347. }
  37348. } );
  37349. sceneData.environmentNode = environmentNode;
  37350. sceneData.environment = environment;
  37351. }
  37352. } else if ( sceneData.environmentNode ) {
  37353. delete sceneData.environmentNode;
  37354. delete sceneData.environment;
  37355. }
  37356. }
  37357. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37358. const nodeFrame = this.nodeFrame;
  37359. nodeFrame.renderer = renderer;
  37360. nodeFrame.scene = scene;
  37361. nodeFrame.object = object;
  37362. nodeFrame.camera = camera;
  37363. nodeFrame.material = material;
  37364. return nodeFrame;
  37365. }
  37366. getNodeFrameForRender( renderObject ) {
  37367. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37368. }
  37369. /**
  37370. * Returns the current output cache key.
  37371. *
  37372. * @return {string} The output cache key.
  37373. */
  37374. getOutputCacheKey() {
  37375. const renderer = this.renderer;
  37376. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  37377. }
  37378. /**
  37379. * Checks if the output configuration (tone mapping and color space) for
  37380. * the given target has changed.
  37381. *
  37382. * @param {Texture} outputTarget - The output target.
  37383. * @return {boolean} Whether the output configuration has changed or not.
  37384. */
  37385. hasOutputChange( outputTarget ) {
  37386. const cacheKey = _outputNodeMap.get( outputTarget );
  37387. return cacheKey !== this.getOutputCacheKey();
  37388. }
  37389. /**
  37390. * Returns a node that represents the output configuration (tone mapping and
  37391. * color space) for the current target.
  37392. *
  37393. * @param {Texture} outputTarget - The output target.
  37394. * @return {Node} The output node.
  37395. */
  37396. getOutputNode( outputTarget ) {
  37397. const renderer = this.renderer;
  37398. const cacheKey = this.getOutputCacheKey();
  37399. const output = outputTarget.isArrayTexture ?
  37400. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  37401. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37402. _outputNodeMap.set( outputTarget, cacheKey );
  37403. return output;
  37404. }
  37405. /**
  37406. * Triggers the call of `updateBefore()` methods
  37407. * for all nodes of the given render object.
  37408. *
  37409. * @param {RenderObject} renderObject - The render object.
  37410. */
  37411. updateBefore( renderObject ) {
  37412. const nodeBuilder = renderObject.getNodeBuilderState();
  37413. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37414. // update frame state for each node
  37415. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37416. }
  37417. }
  37418. /**
  37419. * Triggers the call of `updateAfter()` methods
  37420. * for all nodes of the given render object.
  37421. *
  37422. * @param {RenderObject} renderObject - The render object.
  37423. */
  37424. updateAfter( renderObject ) {
  37425. const nodeBuilder = renderObject.getNodeBuilderState();
  37426. for ( const node of nodeBuilder.updateAfterNodes ) {
  37427. // update frame state for each node
  37428. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37429. }
  37430. }
  37431. /**
  37432. * Triggers the call of `update()` methods
  37433. * for all nodes of the given compute node.
  37434. *
  37435. * @param {Node} computeNode - The compute node.
  37436. */
  37437. updateForCompute( computeNode ) {
  37438. const nodeFrame = this.getNodeFrame();
  37439. const nodeBuilder = this.getForCompute( computeNode );
  37440. for ( const node of nodeBuilder.updateNodes ) {
  37441. nodeFrame.updateNode( node );
  37442. }
  37443. }
  37444. /**
  37445. * Triggers the call of `update()` methods
  37446. * for all nodes of the given compute node.
  37447. *
  37448. * @param {RenderObject} renderObject - The render object.
  37449. */
  37450. updateForRender( renderObject ) {
  37451. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37452. const nodeBuilder = renderObject.getNodeBuilderState();
  37453. for ( const node of nodeBuilder.updateNodes ) {
  37454. nodeFrame.updateNode( node );
  37455. }
  37456. }
  37457. /**
  37458. * Returns `true` if the given render object requires a refresh.
  37459. *
  37460. * @param {RenderObject} renderObject - The render object.
  37461. * @return {boolean} Whether the given render object requires a refresh or not.
  37462. */
  37463. needsRefresh( renderObject ) {
  37464. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37465. const monitor = renderObject.getMonitor();
  37466. return monitor.needsRefresh( renderObject, nodeFrame );
  37467. }
  37468. /**
  37469. * Frees the internal resources.
  37470. */
  37471. dispose() {
  37472. super.dispose();
  37473. this.nodeFrame = new NodeFrame();
  37474. this.nodeBuilderCache = new Map();
  37475. this.cacheLib = {};
  37476. }
  37477. }
  37478. const _plane = /*@__PURE__*/ new Plane();
  37479. /**
  37480. * Represents the state that is used to perform clipping via clipping planes.
  37481. * There is a default clipping context for each render context. When the
  37482. * scene holds instances of `ClippingGroup`, there will be a context for each
  37483. * group.
  37484. *
  37485. * @private
  37486. */
  37487. class ClippingContext {
  37488. /**
  37489. * Constructs a new clipping context.
  37490. *
  37491. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  37492. */
  37493. constructor( parentContext = null ) {
  37494. /**
  37495. * The clipping context's version.
  37496. *
  37497. * @type {number}
  37498. * @readonly
  37499. */
  37500. this.version = 0;
  37501. /**
  37502. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  37503. *
  37504. * @type {?boolean}
  37505. * @default null
  37506. */
  37507. this.clipIntersection = null;
  37508. /**
  37509. * The clipping context's cache key.
  37510. *
  37511. * @type {string}
  37512. */
  37513. this.cacheKey = '';
  37514. /**
  37515. * Whether the shadow pass is active or not.
  37516. *
  37517. * @type {boolean}
  37518. * @default false
  37519. */
  37520. this.shadowPass = false;
  37521. /**
  37522. * The view normal matrix.
  37523. *
  37524. * @type {Matrix3}
  37525. */
  37526. this.viewNormalMatrix = new Matrix3();
  37527. /**
  37528. * Internal cache for maintaining clipping contexts.
  37529. *
  37530. * @type {WeakMap<ClippingGroup,ClippingContext>}
  37531. */
  37532. this.clippingGroupContexts = new WeakMap();
  37533. /**
  37534. * The intersection planes.
  37535. *
  37536. * @type {Array<Vector4>}
  37537. */
  37538. this.intersectionPlanes = [];
  37539. /**
  37540. * The intersection planes.
  37541. *
  37542. * @type {Array<Vector4>}
  37543. */
  37544. this.unionPlanes = [];
  37545. /**
  37546. * The version of the clipping context's parent context.
  37547. *
  37548. * @type {?number}
  37549. * @readonly
  37550. */
  37551. this.parentVersion = null;
  37552. if ( parentContext !== null ) {
  37553. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  37554. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  37555. this.shadowPass = parentContext.shadowPass;
  37556. this.viewMatrix = parentContext.viewMatrix;
  37557. }
  37558. }
  37559. /**
  37560. * Projects the given source clipping planes and writes the result into the
  37561. * destination array.
  37562. *
  37563. * @param {Array<Plane>} source - The source clipping planes.
  37564. * @param {Array<Vector4>} destination - The destination.
  37565. * @param {number} offset - The offset.
  37566. */
  37567. projectPlanes( source, destination, offset ) {
  37568. const l = source.length;
  37569. for ( let i = 0; i < l; i ++ ) {
  37570. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  37571. const v = destination[ offset + i ];
  37572. const normal = _plane.normal;
  37573. v.x = - normal.x;
  37574. v.y = - normal.y;
  37575. v.z = - normal.z;
  37576. v.w = _plane.constant;
  37577. }
  37578. }
  37579. /**
  37580. * Updates the root clipping context of a scene.
  37581. *
  37582. * @param {Scene} scene - The scene.
  37583. * @param {Camera} camera - The camera that is used to render the scene.
  37584. */
  37585. updateGlobal( scene, camera ) {
  37586. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  37587. this.viewMatrix = camera.matrixWorldInverse;
  37588. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37589. }
  37590. /**
  37591. * Updates the clipping context.
  37592. *
  37593. * @param {ClippingContext} parentContext - The parent context.
  37594. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  37595. */
  37596. update( parentContext, clippingGroup ) {
  37597. let update = false;
  37598. if ( parentContext.version !== this.parentVersion ) {
  37599. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37600. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37601. this.parentVersion = parentContext.version;
  37602. }
  37603. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37604. this.clipIntersection = clippingGroup.clipIntersection;
  37605. if ( this.clipIntersection ) {
  37606. this.unionPlanes.length = parentContext.unionPlanes.length;
  37607. } else {
  37608. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37609. }
  37610. }
  37611. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37612. const l = srcClippingPlanes.length;
  37613. let dstClippingPlanes;
  37614. let offset;
  37615. if ( this.clipIntersection ) {
  37616. dstClippingPlanes = this.intersectionPlanes;
  37617. offset = parentContext.intersectionPlanes.length;
  37618. } else {
  37619. dstClippingPlanes = this.unionPlanes;
  37620. offset = parentContext.unionPlanes.length;
  37621. }
  37622. if ( dstClippingPlanes.length !== offset + l ) {
  37623. dstClippingPlanes.length = offset + l;
  37624. for ( let i = 0; i < l; i ++ ) {
  37625. dstClippingPlanes[ offset + i ] = new Vector4();
  37626. }
  37627. update = true;
  37628. }
  37629. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37630. if ( update ) {
  37631. this.version ++;
  37632. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37633. }
  37634. }
  37635. /**
  37636. * Returns a clipping context for the given clipping group.
  37637. *
  37638. * @param {ClippingGroup} clippingGroup - The clipping group.
  37639. * @return {ClippingContext} The clipping context.
  37640. */
  37641. getGroupContext( clippingGroup ) {
  37642. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37643. let context = this.clippingGroupContexts.get( clippingGroup );
  37644. if ( context === undefined ) {
  37645. context = new ClippingContext( this );
  37646. this.clippingGroupContexts.set( clippingGroup, context );
  37647. }
  37648. context.update( this, clippingGroup );
  37649. return context;
  37650. }
  37651. /**
  37652. * The count of union clipping planes.
  37653. *
  37654. * @type {number}
  37655. * @readonly
  37656. */
  37657. get unionClippingCount() {
  37658. return this.unionPlanes.length;
  37659. }
  37660. }
  37661. /**
  37662. * This module is used to represent render bundles inside the renderer
  37663. * for further processing.
  37664. *
  37665. * @private
  37666. */
  37667. class RenderBundle {
  37668. /**
  37669. * Constructs a new bundle group.
  37670. *
  37671. * @param {BundleGroup} bundleGroup - The bundle group.
  37672. * @param {Camera} camera - The camera the bundle group is rendered with.
  37673. */
  37674. constructor( bundleGroup, camera ) {
  37675. this.bundleGroup = bundleGroup;
  37676. this.camera = camera;
  37677. }
  37678. }
  37679. const _chainKeys$1 = [];
  37680. /**
  37681. * This renderer module manages render bundles.
  37682. *
  37683. * @private
  37684. */
  37685. class RenderBundles {
  37686. /**
  37687. * Constructs a new render bundle management component.
  37688. */
  37689. constructor() {
  37690. /**
  37691. * A chain map for maintaining the render bundles.
  37692. *
  37693. * @type {ChainMap}
  37694. */
  37695. this.bundles = new ChainMap();
  37696. }
  37697. /**
  37698. * Returns a render bundle for the given bundle group and camera.
  37699. *
  37700. * @param {BundleGroup} bundleGroup - The bundle group.
  37701. * @param {Camera} camera - The camera the bundle group is rendered with.
  37702. * @return {RenderBundle} The render bundle.
  37703. */
  37704. get( bundleGroup, camera ) {
  37705. const bundles = this.bundles;
  37706. _chainKeys$1[ 0 ] = bundleGroup;
  37707. _chainKeys$1[ 1 ] = camera;
  37708. let bundle = bundles.get( _chainKeys$1 );
  37709. if ( bundle === undefined ) {
  37710. bundle = new RenderBundle( bundleGroup, camera );
  37711. bundles.set( _chainKeys$1, bundle );
  37712. }
  37713. _chainKeys$1.length = 0;
  37714. return bundle;
  37715. }
  37716. /**
  37717. * Frees all internal resources.
  37718. */
  37719. dispose() {
  37720. this.bundles = new ChainMap();
  37721. }
  37722. }
  37723. /**
  37724. * The purpose of a node library is to assign node implementations
  37725. * to existing library features. In `WebGPURenderer` lights, materials
  37726. * which are not based on `NodeMaterial` as well as tone mapping techniques
  37727. * are implemented with node-based modules.
  37728. *
  37729. * @private
  37730. */
  37731. class NodeLibrary {
  37732. /**
  37733. * Constructs a new node library.
  37734. */
  37735. constructor() {
  37736. /**
  37737. * A weak map that maps lights to light nodes.
  37738. *
  37739. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  37740. */
  37741. this.lightNodes = new WeakMap();
  37742. /**
  37743. * A map that maps materials to node materials.
  37744. *
  37745. * @type {Map<string,NodeMaterial.constructor>}
  37746. */
  37747. this.materialNodes = new Map();
  37748. /**
  37749. * A map that maps tone mapping techniques (constants)
  37750. * to tone mapping node functions.
  37751. *
  37752. * @type {Map<number,Function>}
  37753. */
  37754. this.toneMappingNodes = new Map();
  37755. }
  37756. /**
  37757. * Returns a matching node material instance for the given material object.
  37758. *
  37759. * This method also assigns/copies the properties of the given material object
  37760. * to the node material. This is done to make sure the current material
  37761. * configuration carries over to the node version.
  37762. *
  37763. * @param {Material} material - A material.
  37764. * @return {NodeMaterial} The corresponding node material.
  37765. */
  37766. fromMaterial( material ) {
  37767. if ( material.isNodeMaterial ) return material;
  37768. let nodeMaterial = null;
  37769. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37770. if ( nodeMaterialClass !== null ) {
  37771. nodeMaterial = new nodeMaterialClass();
  37772. for ( const key in material ) {
  37773. nodeMaterial[ key ] = material[ key ];
  37774. }
  37775. }
  37776. return nodeMaterial;
  37777. }
  37778. /**
  37779. * Adds a tone mapping node function for a tone mapping technique (constant).
  37780. *
  37781. * @param {Function} toneMappingNode - The tone mapping node function.
  37782. * @param {number} toneMapping - The tone mapping.
  37783. */
  37784. addToneMapping( toneMappingNode, toneMapping ) {
  37785. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37786. }
  37787. /**
  37788. * Returns a tone mapping node function for a tone mapping technique (constant).
  37789. *
  37790. * @param {number} toneMapping - The tone mapping.
  37791. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  37792. */
  37793. getToneMappingFunction( toneMapping ) {
  37794. return this.toneMappingNodes.get( toneMapping ) || null;
  37795. }
  37796. /**
  37797. * Returns a node material class definition for a material type.
  37798. *
  37799. * @param {string} materialType - The material type.
  37800. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  37801. */
  37802. getMaterialNodeClass( materialType ) {
  37803. return this.materialNodes.get( materialType ) || null;
  37804. }
  37805. /**
  37806. * Adds a node material class definition for a given material type.
  37807. *
  37808. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  37809. * @param {string} materialClassType - The material type.
  37810. */
  37811. addMaterial( materialNodeClass, materialClassType ) {
  37812. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37813. }
  37814. /**
  37815. * Returns a light node class definition for a light class definition.
  37816. *
  37817. * @param {Light.constructor} light - The light class definition.
  37818. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  37819. */
  37820. getLightNodeClass( light ) {
  37821. return this.lightNodes.get( light ) || null;
  37822. }
  37823. /**
  37824. * Adds a light node class definition for a given light class definition.
  37825. *
  37826. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  37827. * @param {Light.constructor} lightClass - The light class definition.
  37828. */
  37829. addLight( lightNodeClass, lightClass ) {
  37830. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37831. }
  37832. /**
  37833. * Adds a node class definition for the given type to the provided type library.
  37834. *
  37835. * @param {Node.constructor} nodeClass - The node class definition.
  37836. * @param {number|string} type - The object type.
  37837. * @param {Map<number|string,Node.constructor>} library - The type library.
  37838. */
  37839. addType( nodeClass, type, library ) {
  37840. if ( library.has( type ) ) {
  37841. warn( `Redefinition of node ${ type }` );
  37842. return;
  37843. }
  37844. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37845. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37846. library.set( type, nodeClass );
  37847. }
  37848. /**
  37849. * Adds a node class definition for the given class definition to the provided type library.
  37850. *
  37851. * @param {Node.constructor} nodeClass - The node class definition.
  37852. * @param {Node.constructor} baseClass - The class definition.
  37853. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  37854. */
  37855. addClass( nodeClass, baseClass, library ) {
  37856. if ( library.has( baseClass ) ) {
  37857. warn( `Redefinition of node ${ baseClass.name }` );
  37858. return;
  37859. }
  37860. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37861. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37862. library.set( baseClass, nodeClass );
  37863. }
  37864. }
  37865. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37866. const _chainKeys = [];
  37867. /**
  37868. * This renderer module manages the lights nodes which are unique
  37869. * per scene and camera combination.
  37870. *
  37871. * The lights node itself is later configured in the render list
  37872. * with the actual lights from the scene.
  37873. *
  37874. * @private
  37875. * @augments ChainMap
  37876. */
  37877. class Lighting extends ChainMap {
  37878. /**
  37879. * Constructs a lighting management component.
  37880. */
  37881. constructor() {
  37882. super();
  37883. }
  37884. /**
  37885. * Creates a new lights node for the given array of lights.
  37886. *
  37887. * @param {Array<Light>} lights - The render object.
  37888. * @return {LightsNode} The lights node.
  37889. */
  37890. createNode( lights = [] ) {
  37891. return new LightsNode().setLights( lights );
  37892. }
  37893. /**
  37894. * Returns a lights node for the given scene and camera.
  37895. *
  37896. * @param {Scene} scene - The scene.
  37897. * @param {Camera} camera - The camera.
  37898. * @return {LightsNode} The lights node.
  37899. */
  37900. getNode( scene, camera ) {
  37901. // ignore post-processing
  37902. if ( scene.isQuadMesh ) return _defaultLights;
  37903. _chainKeys[ 0 ] = scene;
  37904. _chainKeys[ 1 ] = camera;
  37905. let node = this.get( _chainKeys );
  37906. if ( node === undefined ) {
  37907. node = this.createNode();
  37908. this.set( _chainKeys, node );
  37909. }
  37910. _chainKeys.length = 0;
  37911. return node;
  37912. }
  37913. }
  37914. /**
  37915. * A special type of render target that is used when rendering
  37916. * with the WebXR Device API.
  37917. *
  37918. * @private
  37919. * @augments RenderTarget
  37920. */
  37921. class XRRenderTarget extends RenderTarget {
  37922. /**
  37923. * Constructs a new XR render target.
  37924. *
  37925. * @param {number} [width=1] - The width of the render target.
  37926. * @param {number} [height=1] - The height of the render target.
  37927. * @param {Object} [options={}] - The configuration options.
  37928. */
  37929. constructor( width = 1, height = 1, options = {} ) {
  37930. super( width, height, options );
  37931. /**
  37932. * This flag can be used for type testing.
  37933. *
  37934. * @type {boolean}
  37935. * @readonly
  37936. * @default true
  37937. */
  37938. this.isXRRenderTarget = true;
  37939. /**
  37940. * Whether the attachments of the render target
  37941. * are defined by external textures. This flag is
  37942. * set to `true` when using the WebXR Layers API.
  37943. *
  37944. * @private
  37945. * @type {boolean}
  37946. * @default false
  37947. */
  37948. this._hasExternalTextures = false;
  37949. /**
  37950. * Whether a depth buffer should automatically be allocated
  37951. * for this XR render target or not.
  37952. *
  37953. * Allocating a depth buffer is the default behavior of XR render
  37954. * targets. However, when using the WebXR Layers API, this flag
  37955. * must be set to `false` when the `ignoreDepthValues` property of
  37956. * the projection layers evaluates to `false`.
  37957. *
  37958. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37959. *
  37960. * @private
  37961. * @type {boolean}
  37962. * @default true
  37963. */
  37964. this._autoAllocateDepthBuffer = true;
  37965. /**
  37966. * Whether this render target is associated with a XRWebGLLayer.
  37967. *
  37968. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37969. * this means that you don't have access to its bound color,
  37970. * stencil and depth buffers. We need to handle this framebuffer
  37971. * differently since its textures are always bound.
  37972. *
  37973. * @private
  37974. * @type {boolean}
  37975. * @default false
  37976. * */
  37977. this._isOpaqueFramebuffer = false;
  37978. }
  37979. copy( source ) {
  37980. super.copy( source );
  37981. this._hasExternalTextures = source._hasExternalTextures;
  37982. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37983. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37984. return this;
  37985. }
  37986. }
  37987. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37988. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37989. /**
  37990. * The XR manager is built on top of the WebXR Device API to
  37991. * manage XR sessions with `WebGPURenderer`.
  37992. *
  37993. * XR is currently only supported with a WebGL 2 backend.
  37994. *
  37995. * @augments EventDispatcher
  37996. */
  37997. class XRManager extends EventDispatcher {
  37998. /**
  37999. * Constructs a new XR manager.
  38000. *
  38001. * @param {Renderer} renderer - The renderer.
  38002. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  38003. */
  38004. constructor( renderer, multiview = false ) {
  38005. super();
  38006. /**
  38007. * This flag globally enables XR rendering.
  38008. *
  38009. * @type {boolean}
  38010. * @default false
  38011. */
  38012. this.enabled = false;
  38013. /**
  38014. * Whether the XR device is currently presenting or not.
  38015. *
  38016. * @type {boolean}
  38017. * @default false
  38018. * @readonly
  38019. */
  38020. this.isPresenting = false;
  38021. /**
  38022. * Whether the XR camera should automatically be updated or not.
  38023. *
  38024. * @type {boolean}
  38025. * @default true
  38026. */
  38027. this.cameraAutoUpdate = true;
  38028. /**
  38029. * The renderer.
  38030. *
  38031. * @private
  38032. * @type {Renderer}
  38033. */
  38034. this._renderer = renderer;
  38035. // camera
  38036. /**
  38037. * Represents the camera for the left eye.
  38038. *
  38039. * @private
  38040. * @type {PerspectiveCamera}
  38041. */
  38042. this._cameraL = new PerspectiveCamera();
  38043. this._cameraL.viewport = new Vector4();
  38044. /**
  38045. * Represents the camera for the right eye.
  38046. *
  38047. * @private
  38048. * @type {PerspectiveCamera}
  38049. */
  38050. this._cameraR = new PerspectiveCamera();
  38051. this._cameraR.viewport = new Vector4();
  38052. /**
  38053. * A list of cameras used for rendering the XR views.
  38054. *
  38055. * @private
  38056. * @type {Array<Camera>}
  38057. */
  38058. this._cameras = [ this._cameraL, this._cameraR ];
  38059. /**
  38060. * The main XR camera.
  38061. *
  38062. * @private
  38063. * @type {ArrayCamera}
  38064. */
  38065. this._cameraXR = new ArrayCamera();
  38066. /**
  38067. * The current near value of the XR camera.
  38068. *
  38069. * @private
  38070. * @type {?number}
  38071. * @default null
  38072. */
  38073. this._currentDepthNear = null;
  38074. /**
  38075. * The current far value of the XR camera.
  38076. *
  38077. * @private
  38078. * @type {?number}
  38079. * @default null
  38080. */
  38081. this._currentDepthFar = null;
  38082. /**
  38083. * A list of WebXR controllers requested by the application.
  38084. *
  38085. * @private
  38086. * @type {Array<WebXRController>}
  38087. */
  38088. this._controllers = [];
  38089. /**
  38090. * A list of XR input source. Each input source belongs to
  38091. * an instance of WebXRController.
  38092. *
  38093. * @private
  38094. * @type {Array<XRInputSource?>}
  38095. */
  38096. this._controllerInputSources = [];
  38097. /**
  38098. * The XR render target that represents the rendering destination
  38099. * during an active XR session.
  38100. *
  38101. * @private
  38102. * @type {?RenderTarget}
  38103. * @default null
  38104. */
  38105. this._xrRenderTarget = null;
  38106. /**
  38107. * An array holding all the non-projection layers
  38108. *
  38109. * @private
  38110. * @type {Array<Object>}
  38111. * @default []
  38112. */
  38113. this._layers = [];
  38114. /**
  38115. * Whether the XR session uses layers.
  38116. *
  38117. * @type {boolean}
  38118. * @default false
  38119. */
  38120. this._sessionUsesLayers = false;
  38121. /**
  38122. * Whether the device supports binding gl objects.
  38123. *
  38124. * @private
  38125. * @type {boolean}
  38126. * @readonly
  38127. */
  38128. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  38129. this._frameBufferTargets = null;
  38130. /**
  38131. * Helper function to create native WebXR Layer.
  38132. *
  38133. * @private
  38134. * @type {Function}
  38135. */
  38136. this._createXRLayer = createXRLayer.bind( this );
  38137. /**
  38138. * The current WebGL context.
  38139. *
  38140. * @private
  38141. * @type {?WebGL2RenderingContext}
  38142. * @default null
  38143. */
  38144. this._gl = null;
  38145. /**
  38146. * The current animation context.
  38147. *
  38148. * @private
  38149. * @type {?Window}
  38150. * @default null
  38151. */
  38152. this._currentAnimationContext = null;
  38153. /**
  38154. * The current animation loop.
  38155. *
  38156. * @private
  38157. * @type {?Function}
  38158. * @default null
  38159. */
  38160. this._currentAnimationLoop = null;
  38161. /**
  38162. * The current pixel ratio.
  38163. *
  38164. * @private
  38165. * @type {?number}
  38166. * @default null
  38167. */
  38168. this._currentPixelRatio = null;
  38169. /**
  38170. * The current size of the renderer's canvas
  38171. * in logical pixel unit.
  38172. *
  38173. * @private
  38174. * @type {Vector2}
  38175. */
  38176. this._currentSize = new Vector2();
  38177. /**
  38178. * The default event listener for handling events inside a XR session.
  38179. *
  38180. * @private
  38181. * @type {Function}
  38182. */
  38183. this._onSessionEvent = onSessionEvent.bind( this );
  38184. /**
  38185. * The event listener for handling the end of a XR session.
  38186. *
  38187. * @private
  38188. * @type {Function}
  38189. */
  38190. this._onSessionEnd = onSessionEnd.bind( this );
  38191. /**
  38192. * The event listener for handling the `inputsourceschange` event.
  38193. *
  38194. * @private
  38195. * @type {Function}
  38196. */
  38197. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  38198. /**
  38199. * The animation loop which is used as a replacement for the default
  38200. * animation loop of the application. It is only used when a XR session
  38201. * is active.
  38202. *
  38203. * @private
  38204. * @type {Function}
  38205. */
  38206. this._onAnimationFrame = onAnimationFrame.bind( this );
  38207. /**
  38208. * The current XR reference space.
  38209. *
  38210. * @private
  38211. * @type {?XRReferenceSpace}
  38212. * @default null
  38213. */
  38214. this._referenceSpace = null;
  38215. /**
  38216. * The current XR reference space type.
  38217. *
  38218. * @private
  38219. * @type {XRReferenceSpaceType}
  38220. * @default 'local-floor'
  38221. */
  38222. this._referenceSpaceType = 'local-floor';
  38223. /**
  38224. * A custom reference space defined by the application.
  38225. *
  38226. * @private
  38227. * @type {?XRReferenceSpace}
  38228. * @default null
  38229. */
  38230. this._customReferenceSpace = null;
  38231. /**
  38232. * The framebuffer scale factor.
  38233. *
  38234. * @private
  38235. * @type {number}
  38236. * @default 1
  38237. */
  38238. this._framebufferScaleFactor = 1;
  38239. /**
  38240. * The foveation factor.
  38241. *
  38242. * @private
  38243. * @type {number}
  38244. * @default 1
  38245. */
  38246. this._foveation = 1.0;
  38247. /**
  38248. * A reference to the current XR session.
  38249. *
  38250. * @private
  38251. * @type {?XRSession}
  38252. * @default null
  38253. */
  38254. this._session = null;
  38255. /**
  38256. * A reference to the current XR base layer.
  38257. *
  38258. * @private
  38259. * @type {?XRWebGLLayer}
  38260. * @default null
  38261. */
  38262. this._glBaseLayer = null;
  38263. /**
  38264. * A reference to the current XR binding.
  38265. *
  38266. * @private
  38267. * @type {?XRWebGLBinding}
  38268. * @default null
  38269. */
  38270. this._glBinding = null;
  38271. /**
  38272. * A reference to the current XR projection layer.
  38273. *
  38274. * @private
  38275. * @type {?XRProjectionLayer}
  38276. * @default null
  38277. */
  38278. this._glProjLayer = null;
  38279. /**
  38280. * A reference to the current XR frame.
  38281. *
  38282. * @private
  38283. * @type {?XRFrame}
  38284. * @default null
  38285. */
  38286. this._xrFrame = null;
  38287. /**
  38288. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  38289. *
  38290. * Note: this does not represent XRSession explicitly requesting
  38291. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  38292. *
  38293. * @private
  38294. * @type {boolean}
  38295. * @readonly
  38296. */
  38297. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  38298. /**
  38299. * Whether the usage of multiview has been requested by the application or not.
  38300. *
  38301. * @private
  38302. * @type {boolean}
  38303. * @default false
  38304. * @readonly
  38305. */
  38306. this._useMultiviewIfPossible = multiview;
  38307. /**
  38308. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  38309. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  38310. *
  38311. * @private
  38312. * @type {boolean}
  38313. * @readonly
  38314. */
  38315. this._useMultiview = false;
  38316. }
  38317. /**
  38318. * Returns an instance of `THREE.Group` that represents the transformation
  38319. * of a XR controller in target ray space. The requested controller is defined
  38320. * by the given index.
  38321. *
  38322. * @param {number} index - The index of the XR controller.
  38323. * @return {Group} A group that represents the controller's transformation.
  38324. */
  38325. getController( index ) {
  38326. const controller = this._getController( index );
  38327. return controller.getTargetRaySpace();
  38328. }
  38329. /**
  38330. * Returns an instance of `THREE.Group` that represents the transformation
  38331. * of a XR controller in grip space. The requested controller is defined
  38332. * by the given index.
  38333. *
  38334. * @param {number} index - The index of the XR controller.
  38335. * @return {Group} A group that represents the controller's transformation.
  38336. */
  38337. getControllerGrip( index ) {
  38338. const controller = this._getController( index );
  38339. return controller.getGripSpace();
  38340. }
  38341. /**
  38342. * Returns an instance of `THREE.Group` that represents the transformation
  38343. * of a XR controller in hand space. The requested controller is defined
  38344. * by the given index.
  38345. *
  38346. * @param {number} index - The index of the XR controller.
  38347. * @return {Group} A group that represents the controller's transformation.
  38348. */
  38349. getHand( index ) {
  38350. const controller = this._getController( index );
  38351. return controller.getHandSpace();
  38352. }
  38353. /**
  38354. * Returns the foveation value.
  38355. *
  38356. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  38357. */
  38358. getFoveation() {
  38359. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  38360. return undefined;
  38361. }
  38362. return this._foveation;
  38363. }
  38364. /**
  38365. * Sets the foveation value.
  38366. *
  38367. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  38368. * and `1` means maximum foveation (the edges render at lower resolution).
  38369. */
  38370. setFoveation( foveation ) {
  38371. this._foveation = foveation;
  38372. if ( this._glProjLayer !== null ) {
  38373. this._glProjLayer.fixedFoveation = foveation;
  38374. }
  38375. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  38376. this._glBaseLayer.fixedFoveation = foveation;
  38377. }
  38378. }
  38379. /**
  38380. * Returns the framebuffer scale factor.
  38381. *
  38382. * @return {number} The framebuffer scale factor.
  38383. */
  38384. getFramebufferScaleFactor() {
  38385. return this._framebufferScaleFactor;
  38386. }
  38387. /**
  38388. * Sets the framebuffer scale factor.
  38389. *
  38390. * This method can not be used during a XR session.
  38391. *
  38392. * @param {number} factor - The framebuffer scale factor.
  38393. */
  38394. setFramebufferScaleFactor( factor ) {
  38395. this._framebufferScaleFactor = factor;
  38396. if ( this.isPresenting === true ) {
  38397. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  38398. }
  38399. }
  38400. /**
  38401. * Returns the reference space type.
  38402. *
  38403. * @return {XRReferenceSpaceType} The reference space type.
  38404. */
  38405. getReferenceSpaceType() {
  38406. return this._referenceSpaceType;
  38407. }
  38408. /**
  38409. * Sets the reference space type.
  38410. *
  38411. * This method can not be used during a XR session.
  38412. *
  38413. * @param {XRReferenceSpaceType} type - The reference space type.
  38414. */
  38415. setReferenceSpaceType( type ) {
  38416. this._referenceSpaceType = type;
  38417. if ( this.isPresenting === true ) {
  38418. warn( 'XRManager: Cannot change reference space type while presenting.' );
  38419. }
  38420. }
  38421. /**
  38422. * Returns the XR reference space.
  38423. *
  38424. * @return {XRReferenceSpace} The XR reference space.
  38425. */
  38426. getReferenceSpace() {
  38427. return this._customReferenceSpace || this._referenceSpace;
  38428. }
  38429. /**
  38430. * Sets a custom XR reference space.
  38431. *
  38432. * @param {XRReferenceSpace} space - The XR reference space.
  38433. */
  38434. setReferenceSpace( space ) {
  38435. this._customReferenceSpace = space;
  38436. }
  38437. /**
  38438. * Returns the XR camera.
  38439. *
  38440. * @return {ArrayCamera} The XR camera.
  38441. */
  38442. getCamera() {
  38443. return this._cameraXR;
  38444. }
  38445. /**
  38446. * Returns the environment blend mode from the current XR session.
  38447. *
  38448. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  38449. */
  38450. getEnvironmentBlendMode() {
  38451. if ( this._session !== null ) {
  38452. return this._session.environmentBlendMode;
  38453. }
  38454. }
  38455. /**
  38456. * Returns the current XR binding.
  38457. *
  38458. * Creates a new binding if needed and the browser is
  38459. * capable of doing so.
  38460. *
  38461. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  38462. */
  38463. getBinding() {
  38464. if ( this._glBinding === null && this._supportsGlBinding ) {
  38465. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  38466. }
  38467. return this._glBinding;
  38468. }
  38469. /**
  38470. * Returns the current XR frame.
  38471. *
  38472. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  38473. */
  38474. getFrame() {
  38475. return this._xrFrame;
  38476. }
  38477. /**
  38478. * Returns `true` if the engine renders to a multiview target.
  38479. *
  38480. * @return {boolean} Whether the engine renders to a multiview render target or not.
  38481. */
  38482. useMultiview() {
  38483. return this._useMultiview;
  38484. }
  38485. /**
  38486. * This method can be used in XR applications to create a quadratic layer that presents a separate
  38487. * rendered scene.
  38488. *
  38489. * @param {number} width - The width of the layer plane in world units.
  38490. * @param {number} height - The height of the layer plane in world units.
  38491. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38492. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38493. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38494. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38495. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38496. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38497. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38498. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  38499. */
  38500. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38501. const geometry = new PlaneGeometry( width, height );
  38502. const renderTarget = new XRRenderTarget(
  38503. pixelwidth,
  38504. pixelheight,
  38505. {
  38506. format: RGBAFormat,
  38507. type: UnsignedByteType,
  38508. depthTexture: new DepthTexture(
  38509. pixelwidth,
  38510. pixelheight,
  38511. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38512. undefined,
  38513. undefined,
  38514. undefined,
  38515. undefined,
  38516. undefined,
  38517. undefined,
  38518. attributes.stencil ? DepthStencilFormat : DepthFormat
  38519. ),
  38520. stencilBuffer: attributes.stencil,
  38521. resolveDepthBuffer: false,
  38522. resolveStencilBuffer: false
  38523. } );
  38524. renderTarget._autoAllocateDepthBuffer = true;
  38525. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38526. material.map = renderTarget.texture;
  38527. material.map.offset.y = 1;
  38528. material.map.repeat.y = -1;
  38529. const plane = new Mesh( geometry, material );
  38530. plane.position.copy( translation );
  38531. plane.quaternion.copy( quaternion );
  38532. const layer = {
  38533. type: 'quad',
  38534. width: width,
  38535. height: height,
  38536. translation: translation,
  38537. quaternion: quaternion,
  38538. pixelwidth: pixelwidth,
  38539. pixelheight: pixelheight,
  38540. plane: plane,
  38541. material: material,
  38542. rendercall: rendercall,
  38543. renderTarget: renderTarget };
  38544. this._layers.push( layer );
  38545. if ( this._session !== null ) {
  38546. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38547. layer.plane.material.blending = CustomBlending;
  38548. layer.plane.material.blendEquation = AddEquation;
  38549. layer.plane.material.blendSrc = ZeroFactor;
  38550. layer.plane.material.blendDst = ZeroFactor;
  38551. layer.xrlayer = this._createXRLayer( layer );
  38552. const xrlayers = this._session.renderState.layers;
  38553. xrlayers.unshift( layer.xrlayer );
  38554. this._session.updateRenderState( { layers: xrlayers } );
  38555. } else {
  38556. renderTarget.isXRRenderTarget = false;
  38557. }
  38558. return plane;
  38559. }
  38560. /**
  38561. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  38562. * rendered scene.
  38563. *
  38564. * @param {number} radius - The radius of the cylinder in world units.
  38565. * @param {number} centralAngle - The central angle of the cylinder in radians.
  38566. * @param {number} aspectratio - The aspect ratio.
  38567. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38568. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38569. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38570. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38571. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38572. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38573. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38574. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  38575. */
  38576. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38577. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  38578. const renderTarget = new XRRenderTarget(
  38579. pixelwidth,
  38580. pixelheight,
  38581. {
  38582. format: RGBAFormat,
  38583. type: UnsignedByteType,
  38584. depthTexture: new DepthTexture(
  38585. pixelwidth,
  38586. pixelheight,
  38587. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38588. undefined,
  38589. undefined,
  38590. undefined,
  38591. undefined,
  38592. undefined,
  38593. undefined,
  38594. attributes.stencil ? DepthStencilFormat : DepthFormat
  38595. ),
  38596. stencilBuffer: attributes.stencil,
  38597. resolveDepthBuffer: false,
  38598. resolveStencilBuffer: false
  38599. } );
  38600. renderTarget._autoAllocateDepthBuffer = true;
  38601. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38602. material.map = renderTarget.texture;
  38603. material.map.offset.y = 1;
  38604. material.map.repeat.y = -1;
  38605. const plane = new Mesh( geometry, material );
  38606. plane.position.copy( translation );
  38607. plane.quaternion.copy( quaternion );
  38608. const layer = {
  38609. type: 'cylinder',
  38610. radius: radius,
  38611. centralAngle: centralAngle,
  38612. aspectratio: aspectratio,
  38613. translation: translation,
  38614. quaternion: quaternion,
  38615. pixelwidth: pixelwidth,
  38616. pixelheight: pixelheight,
  38617. plane: plane,
  38618. material: material,
  38619. rendercall: rendercall,
  38620. renderTarget: renderTarget };
  38621. this._layers.push( layer );
  38622. if ( this._session !== null ) {
  38623. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38624. layer.plane.material.blending = CustomBlending;
  38625. layer.plane.material.blendEquation = AddEquation;
  38626. layer.plane.material.blendSrc = ZeroFactor;
  38627. layer.plane.material.blendDst = ZeroFactor;
  38628. layer.xrlayer = this._createXRLayer( layer );
  38629. const xrlayers = this._session.renderState.layers;
  38630. xrlayers.unshift( layer.xrlayer );
  38631. this._session.updateRenderState( { layers: xrlayers } );
  38632. } else {
  38633. renderTarget.isXRRenderTarget = false;
  38634. }
  38635. return plane;
  38636. }
  38637. /**
  38638. * Renders the XR layers that have been previously added to the scene.
  38639. *
  38640. * This method is usually called in your animation loop before rendering
  38641. * the actual scene via `renderer.render( scene, camera );`.
  38642. */
  38643. renderLayers( ) {
  38644. const translationObject = new Vector3();
  38645. const quaternionObject = new Quaternion();
  38646. const renderer = this._renderer;
  38647. const wasPresenting = this.isPresenting;
  38648. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38649. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38650. this.isPresenting = false;
  38651. const rendererSize = new Vector2();
  38652. renderer.getSize( rendererSize );
  38653. const rendererQuad = renderer._quad;
  38654. for ( const layer of this._layers ) {
  38655. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38656. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38657. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38658. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38659. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38660. renderer.backend.setXRRenderTargetTextures(
  38661. layer.renderTarget,
  38662. glSubImage.colorTexture,
  38663. undefined );
  38664. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38665. renderer.setOutputRenderTarget( layer.renderTarget );
  38666. renderer.setRenderTarget( null );
  38667. renderer._frameBufferTarget = null;
  38668. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38669. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38670. if ( ! frameBufferTarget ) {
  38671. renderer._quad = new QuadMesh( new NodeMaterial() );
  38672. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38673. } else {
  38674. renderer._frameBufferTarget = frameBufferTarget;
  38675. renderer._quad = quad;
  38676. }
  38677. layer.rendercall();
  38678. renderer._frameBufferTarget = null;
  38679. } else {
  38680. renderer.setRenderTarget( layer.renderTarget );
  38681. layer.rendercall();
  38682. }
  38683. }
  38684. renderer.setRenderTarget( null );
  38685. renderer.setOutputRenderTarget( rendererOutputTarget );
  38686. renderer._frameBufferTarget = rendererFramebufferTarget;
  38687. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38688. renderer._quad = rendererQuad;
  38689. this.isPresenting = wasPresenting;
  38690. }
  38691. /**
  38692. * Returns the current XR session.
  38693. *
  38694. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38695. */
  38696. getSession() {
  38697. return this._session;
  38698. }
  38699. /**
  38700. * After a XR session has been requested usually with one of the `*Button` modules, it
  38701. * is injected into the renderer with this method. This method triggers the start of
  38702. * the actual XR rendering.
  38703. *
  38704. * @async
  38705. * @param {XRSession} session - The XR session to set.
  38706. * @return {Promise} A Promise that resolves when the session has been set.
  38707. */
  38708. async setSession( session ) {
  38709. const renderer = this._renderer;
  38710. const backend = renderer.backend;
  38711. this._gl = renderer.getContext();
  38712. const gl = this._gl;
  38713. const attributes = gl.getContextAttributes();
  38714. this._session = session;
  38715. if ( session !== null ) {
  38716. 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.' );
  38717. session.addEventListener( 'select', this._onSessionEvent );
  38718. session.addEventListener( 'selectstart', this._onSessionEvent );
  38719. session.addEventListener( 'selectend', this._onSessionEvent );
  38720. session.addEventListener( 'squeeze', this._onSessionEvent );
  38721. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38722. session.addEventListener( 'squeezeend', this._onSessionEvent );
  38723. session.addEventListener( 'end', this._onSessionEnd );
  38724. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38725. await backend.makeXRCompatible();
  38726. this._currentPixelRatio = renderer.getPixelRatio();
  38727. renderer.getSize( this._currentSize );
  38728. this._currentAnimationContext = renderer._animation.getContext();
  38729. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  38730. renderer._animation.stop();
  38731. //
  38732. if ( this._supportsLayers === true ) {
  38733. // default path using XRProjectionLayer
  38734. let depthFormat = null;
  38735. let depthType = null;
  38736. let glDepthFormat = null;
  38737. if ( renderer.depth ) {
  38738. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38739. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  38740. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  38741. }
  38742. const projectionlayerInit = {
  38743. colorFormat: gl.RGBA8,
  38744. depthFormat: glDepthFormat,
  38745. scaleFactor: this._framebufferScaleFactor,
  38746. clearOnAccess: false
  38747. };
  38748. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  38749. projectionlayerInit.textureType = 'texture-array';
  38750. this._useMultiview = true;
  38751. }
  38752. this._glBinding = this.getBinding();
  38753. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  38754. const layersArray = [ glProjLayer ];
  38755. this._glProjLayer = glProjLayer;
  38756. renderer.setPixelRatio( 1 );
  38757. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  38758. const depth = this._useMultiview ? 2 : 1;
  38759. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  38760. this._xrRenderTarget = new XRRenderTarget(
  38761. glProjLayer.textureWidth,
  38762. glProjLayer.textureHeight,
  38763. {
  38764. format: RGBAFormat,
  38765. type: UnsignedByteType,
  38766. colorSpace: renderer.outputColorSpace,
  38767. depthTexture: depthTexture,
  38768. stencilBuffer: renderer.stencil,
  38769. samples: attributes.antialias ? 4 : 0,
  38770. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38771. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38772. depth: this._useMultiview ? 2 : 1,
  38773. multiview: this._useMultiview
  38774. } );
  38775. this._xrRenderTarget._hasExternalTextures = true;
  38776. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  38777. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  38778. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38779. if ( this._sessionUsesLayers ) {
  38780. // switch layers to native
  38781. for ( const layer of this._layers ) {
  38782. // change material so it "punches" out a hole to show the XR Layer.
  38783. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  38784. layer.plane.material.blending = CustomBlending;
  38785. layer.plane.material.blendEquation = AddEquation;
  38786. layer.plane.material.blendSrc = ZeroFactor;
  38787. layer.plane.material.blendDst = ZeroFactor;
  38788. layer.xrlayer = this._createXRLayer( layer );
  38789. layersArray.unshift( layer.xrlayer );
  38790. }
  38791. }
  38792. session.updateRenderState( { layers: layersArray } );
  38793. } else {
  38794. // fallback to XRWebGLLayer
  38795. const layerInit = {
  38796. antialias: renderer.currentSamples > 0,
  38797. alpha: true,
  38798. depth: renderer.depth,
  38799. stencil: renderer.stencil,
  38800. framebufferScaleFactor: this.getFramebufferScaleFactor()
  38801. };
  38802. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38803. this._glBaseLayer = glBaseLayer;
  38804. session.updateRenderState( { baseLayer: glBaseLayer } );
  38805. renderer.setPixelRatio( 1 );
  38806. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  38807. this._xrRenderTarget = new XRRenderTarget(
  38808. glBaseLayer.framebufferWidth,
  38809. glBaseLayer.framebufferHeight,
  38810. {
  38811. format: RGBAFormat,
  38812. type: UnsignedByteType,
  38813. colorSpace: renderer.outputColorSpace,
  38814. stencilBuffer: renderer.stencil,
  38815. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38816. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38817. }
  38818. );
  38819. this._xrRenderTarget._isOpaqueFramebuffer = true;
  38820. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38821. }
  38822. //
  38823. this.setFoveation( this.getFoveation() );
  38824. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  38825. renderer._animation.setContext( session );
  38826. renderer._animation.start();
  38827. this.isPresenting = true;
  38828. this.dispatchEvent( { type: 'sessionstart' } );
  38829. }
  38830. }
  38831. /**
  38832. * This method is called by the renderer per frame and updates the XR camera
  38833. * and it sub cameras based on the given camera. The given camera is the "user"
  38834. * camera created on application level and used for non-XR rendering.
  38835. *
  38836. * @param {PerspectiveCamera} camera - The camera.
  38837. */
  38838. updateCamera( camera ) {
  38839. const session = this._session;
  38840. if ( session === null ) return;
  38841. const depthNear = camera.near;
  38842. const depthFar = camera.far;
  38843. const cameraXR = this._cameraXR;
  38844. const cameraL = this._cameraL;
  38845. const cameraR = this._cameraR;
  38846. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38847. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38848. cameraXR.isMultiViewCamera = this._useMultiview;
  38849. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  38850. // Note that the new renderState won't apply until the next frame. See #18320
  38851. session.updateRenderState( {
  38852. depthNear: cameraXR.near,
  38853. depthFar: cameraXR.far
  38854. } );
  38855. this._currentDepthNear = cameraXR.near;
  38856. this._currentDepthFar = cameraXR.far;
  38857. }
  38858. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  38859. cameraXR.layers.mask = camera.layers.mask | 0b110;
  38860. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  38861. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  38862. const parent = camera.parent;
  38863. const cameras = cameraXR.cameras;
  38864. updateCamera( cameraXR, parent );
  38865. for ( let i = 0; i < cameras.length; i ++ ) {
  38866. updateCamera( cameras[ i ], parent );
  38867. }
  38868. // update projection matrix for proper view frustum culling
  38869. if ( cameras.length === 2 ) {
  38870. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38871. } else {
  38872. // assume single camera setup (AR)
  38873. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38874. }
  38875. // update user camera and its children
  38876. updateUserCamera( camera, cameraXR, parent );
  38877. }
  38878. /**
  38879. * Returns a WebXR controller for the given controller index.
  38880. *
  38881. * @private
  38882. * @param {number} index - The controller index.
  38883. * @return {WebXRController} The XR controller.
  38884. */
  38885. _getController( index ) {
  38886. let controller = this._controllers[ index ];
  38887. if ( controller === undefined ) {
  38888. controller = new WebXRController();
  38889. this._controllers[ index ] = controller;
  38890. }
  38891. return controller;
  38892. }
  38893. }
  38894. /**
  38895. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38896. * the cameras' projection and world matrices have already been set.
  38897. * And that near and far planes are identical for both cameras.
  38898. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38899. *
  38900. * @param {ArrayCamera} camera - The camera to update.
  38901. * @param {PerspectiveCamera} cameraL - The left camera.
  38902. * @param {PerspectiveCamera} cameraR - The right camera.
  38903. */
  38904. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38905. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38906. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38907. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  38908. const projL = cameraL.projectionMatrix.elements;
  38909. const projR = cameraR.projectionMatrix.elements;
  38910. // VR systems will have identical far and near planes, and
  38911. // most likely identical top and bottom frustum extents.
  38912. // Use the left camera for these values.
  38913. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38914. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38915. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38916. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38917. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38918. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38919. const left = near * leftFov;
  38920. const right = near * rightFov;
  38921. // Calculate the new camera's position offset from the
  38922. // left camera. xOffset should be roughly half `ipd`.
  38923. const zOffset = ipd / ( - leftFov + rightFov );
  38924. const xOffset = zOffset * - leftFov;
  38925. // TODO: Better way to apply this offset?
  38926. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38927. camera.translateX( xOffset );
  38928. camera.translateZ( zOffset );
  38929. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38930. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38931. // Check if the projection uses an infinite far plane.
  38932. if ( projL[ 10 ] === -1 ) {
  38933. // Use the projection matrix from the left eye.
  38934. // The camera offset is sufficient to include the view volumes
  38935. // of both eyes (assuming symmetric projections).
  38936. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38937. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38938. } else {
  38939. // Find the union of the frustum values of the cameras and scale
  38940. // the values so that the near plane's position does not change in world space,
  38941. // although must now be relative to the new union camera.
  38942. const near2 = near + zOffset;
  38943. const far2 = far + zOffset;
  38944. const left2 = left - xOffset;
  38945. const right2 = right + ( ipd - xOffset );
  38946. const top2 = topFov * far / far2 * near2;
  38947. const bottom2 = bottomFov * far / far2 * near2;
  38948. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38949. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38950. }
  38951. }
  38952. /**
  38953. * Updates the world matrices for the given camera based on the parent 3D object.
  38954. *
  38955. * @inner
  38956. * @param {Camera} camera - The camera to update.
  38957. * @param {Object3D} parent - The parent 3D object.
  38958. */
  38959. function updateCamera( camera, parent ) {
  38960. if ( parent === null ) {
  38961. camera.matrixWorld.copy( camera.matrix );
  38962. } else {
  38963. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38964. }
  38965. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38966. }
  38967. /**
  38968. * Updates the given camera with the transformation of the XR camera and parent object.
  38969. *
  38970. * @inner
  38971. * @param {Camera} camera - The camera to update.
  38972. * @param {ArrayCamera} cameraXR - The XR camera.
  38973. * @param {Object3D} parent - The parent 3D object.
  38974. */
  38975. function updateUserCamera( camera, cameraXR, parent ) {
  38976. if ( parent === null ) {
  38977. camera.matrix.copy( cameraXR.matrixWorld );
  38978. } else {
  38979. camera.matrix.copy( parent.matrixWorld );
  38980. camera.matrix.invert();
  38981. camera.matrix.multiply( cameraXR.matrixWorld );
  38982. }
  38983. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38984. camera.updateMatrixWorld( true );
  38985. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38986. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38987. if ( camera.isPerspectiveCamera ) {
  38988. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38989. camera.zoom = 1;
  38990. }
  38991. }
  38992. function onSessionEvent( event ) {
  38993. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38994. if ( controllerIndex === -1 ) {
  38995. return;
  38996. }
  38997. const controller = this._controllers[ controllerIndex ];
  38998. if ( controller !== undefined ) {
  38999. const referenceSpace = this.getReferenceSpace();
  39000. controller.update( event.inputSource, event.frame, referenceSpace );
  39001. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  39002. }
  39003. }
  39004. function onSessionEnd() {
  39005. const session = this._session;
  39006. const renderer = this._renderer;
  39007. session.removeEventListener( 'select', this._onSessionEvent );
  39008. session.removeEventListener( 'selectstart', this._onSessionEvent );
  39009. session.removeEventListener( 'selectend', this._onSessionEvent );
  39010. session.removeEventListener( 'squeeze', this._onSessionEvent );
  39011. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  39012. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  39013. session.removeEventListener( 'end', this._onSessionEnd );
  39014. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39015. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39016. const inputSource = this._controllerInputSources[ i ];
  39017. if ( inputSource === null ) continue;
  39018. this._controllerInputSources[ i ] = null;
  39019. this._controllers[ i ].disconnect( inputSource );
  39020. }
  39021. this._currentDepthNear = null;
  39022. this._currentDepthFar = null;
  39023. // restore framebuffer/rendering state
  39024. renderer._resetXRState();
  39025. this._session = null;
  39026. this._xrRenderTarget = null;
  39027. this._glBinding = null;
  39028. this._glBaseLayer = null;
  39029. this._glProjLayer = null;
  39030. // switch layers back to emulated
  39031. if ( this._sessionUsesLayers === true ) {
  39032. for ( const layer of this._layers ) {
  39033. // Recreate layer render target to reset state
  39034. layer.renderTarget = new XRRenderTarget(
  39035. layer.pixelwidth,
  39036. layer.pixelheight,
  39037. {
  39038. format: RGBAFormat,
  39039. type: UnsignedByteType,
  39040. depthTexture: new DepthTexture(
  39041. layer.pixelwidth,
  39042. layer.pixelheight,
  39043. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  39044. undefined,
  39045. undefined,
  39046. undefined,
  39047. undefined,
  39048. undefined,
  39049. undefined,
  39050. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  39051. ),
  39052. stencilBuffer: layer.stencilBuffer,
  39053. resolveDepthBuffer: false,
  39054. resolveStencilBuffer: false
  39055. } );
  39056. layer.renderTarget.isXRRenderTarget = false;
  39057. layer.plane.material = layer.material;
  39058. layer.material.map = layer.renderTarget.texture;
  39059. layer.material.map.offset.y = 1;
  39060. layer.material.map.repeat.y = -1;
  39061. delete layer.xrlayer;
  39062. }
  39063. }
  39064. //
  39065. this.isPresenting = false;
  39066. this._useMultiview = false;
  39067. renderer._animation.stop();
  39068. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  39069. renderer._animation.setContext( this._currentAnimationContext );
  39070. renderer._animation.start();
  39071. renderer.setPixelRatio( this._currentPixelRatio );
  39072. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  39073. this.dispatchEvent( { type: 'sessionend' } );
  39074. }
  39075. function onInputSourcesChange( event ) {
  39076. const controllers = this._controllers;
  39077. const controllerInputSources = this._controllerInputSources;
  39078. // Notify disconnected
  39079. for ( let i = 0; i < event.removed.length; i ++ ) {
  39080. const inputSource = event.removed[ i ];
  39081. const index = controllerInputSources.indexOf( inputSource );
  39082. if ( index >= 0 ) {
  39083. controllerInputSources[ index ] = null;
  39084. controllers[ index ].disconnect( inputSource );
  39085. }
  39086. }
  39087. // Notify connected
  39088. for ( let i = 0; i < event.added.length; i ++ ) {
  39089. const inputSource = event.added[ i ];
  39090. let controllerIndex = controllerInputSources.indexOf( inputSource );
  39091. if ( controllerIndex === -1 ) {
  39092. // Assign input source a controller that currently has no input source
  39093. for ( let i = 0; i < controllers.length; i ++ ) {
  39094. if ( i >= controllerInputSources.length ) {
  39095. controllerInputSources.push( inputSource );
  39096. controllerIndex = i;
  39097. break;
  39098. } else if ( controllerInputSources[ i ] === null ) {
  39099. controllerInputSources[ i ] = inputSource;
  39100. controllerIndex = i;
  39101. break;
  39102. }
  39103. }
  39104. // If all controllers do currently receive input we ignore new ones
  39105. if ( controllerIndex === -1 ) break;
  39106. }
  39107. const controller = controllers[ controllerIndex ];
  39108. if ( controller ) {
  39109. controller.connect( inputSource );
  39110. }
  39111. }
  39112. }
  39113. // Creation method for native WebXR layers
  39114. function createXRLayer( layer ) {
  39115. if ( layer.type === 'quad' ) {
  39116. return this._glBinding.createQuadLayer( {
  39117. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39118. width: layer.width / 2,
  39119. height: layer.height / 2,
  39120. space: this._referenceSpace,
  39121. viewPixelWidth: layer.pixelwidth,
  39122. viewPixelHeight: layer.pixelheight,
  39123. clearOnAccess: false
  39124. } );
  39125. } else {
  39126. return this._glBinding.createCylinderLayer( {
  39127. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39128. radius: layer.radius,
  39129. centralAngle: layer.centralAngle,
  39130. aspectRatio: layer.aspectRatio,
  39131. space: this._referenceSpace,
  39132. viewPixelWidth: layer.pixelwidth,
  39133. viewPixelHeight: layer.pixelheight,
  39134. clearOnAccess: false
  39135. } );
  39136. }
  39137. }
  39138. // Animation Loop
  39139. function onAnimationFrame( time, frame ) {
  39140. if ( frame === undefined ) return;
  39141. const cameraXR = this._cameraXR;
  39142. const renderer = this._renderer;
  39143. const backend = renderer.backend;
  39144. const glBaseLayer = this._glBaseLayer;
  39145. const referenceSpace = this.getReferenceSpace();
  39146. const pose = frame.getViewerPose( referenceSpace );
  39147. this._xrFrame = frame;
  39148. if ( pose !== null ) {
  39149. const views = pose.views;
  39150. if ( this._glBaseLayer !== null ) {
  39151. backend.setXRTarget( glBaseLayer.framebuffer );
  39152. }
  39153. let cameraXRNeedsUpdate = false;
  39154. // check if it's necessary to rebuild cameraXR's camera list
  39155. if ( views.length !== cameraXR.cameras.length ) {
  39156. cameraXR.cameras.length = 0;
  39157. cameraXRNeedsUpdate = true;
  39158. }
  39159. for ( let i = 0; i < views.length; i ++ ) {
  39160. const view = views[ i ];
  39161. let viewport;
  39162. if ( this._supportsLayers === true ) {
  39163. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  39164. viewport = glSubImage.viewport;
  39165. // For side-by-side projection, we only produce a single texture for both eyes.
  39166. if ( i === 0 ) {
  39167. backend.setXRRenderTargetTextures(
  39168. this._xrRenderTarget,
  39169. glSubImage.colorTexture,
  39170. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  39171. );
  39172. }
  39173. } else {
  39174. viewport = glBaseLayer.getViewport( view );
  39175. }
  39176. let camera = this._cameras[ i ];
  39177. if ( camera === undefined ) {
  39178. camera = new PerspectiveCamera();
  39179. camera.layers.enable( i );
  39180. camera.viewport = new Vector4();
  39181. this._cameras[ i ] = camera;
  39182. }
  39183. camera.matrix.fromArray( view.transform.matrix );
  39184. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39185. camera.projectionMatrix.fromArray( view.projectionMatrix );
  39186. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39187. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  39188. if ( i === 0 ) {
  39189. cameraXR.matrix.copy( camera.matrix );
  39190. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  39191. }
  39192. if ( cameraXRNeedsUpdate === true ) {
  39193. cameraXR.cameras.push( camera );
  39194. }
  39195. }
  39196. renderer.setOutputRenderTarget( this._xrRenderTarget );
  39197. }
  39198. //
  39199. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39200. const inputSource = this._controllerInputSources[ i ];
  39201. const controller = this._controllers[ i ];
  39202. if ( inputSource !== null && controller !== undefined ) {
  39203. controller.update( inputSource, frame, referenceSpace );
  39204. }
  39205. }
  39206. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  39207. if ( frame.detectedPlanes ) {
  39208. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  39209. }
  39210. this._xrFrame = null;
  39211. }
  39212. /**
  39213. * CanvasTarget is a class that represents the final output destination of the renderer.
  39214. *
  39215. * @augments EventDispatcher
  39216. */
  39217. class CanvasTarget extends EventDispatcher {
  39218. /**
  39219. * Constructs a new CanvasTarget.
  39220. *
  39221. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  39222. */
  39223. constructor( domElement ) {
  39224. super();
  39225. /**
  39226. * A reference to the canvas element the renderer is drawing to.
  39227. * This value of this property will automatically be created by
  39228. * the renderer.
  39229. *
  39230. * @type {HTMLCanvasElement|OffscreenCanvas}
  39231. */
  39232. this.domElement = domElement;
  39233. /**
  39234. * The renderer's pixel ratio.
  39235. *
  39236. * @private
  39237. * @type {number}
  39238. * @default 1
  39239. */
  39240. this._pixelRatio = 1;
  39241. /**
  39242. * The width of the renderer's default framebuffer in logical pixel unit.
  39243. *
  39244. * @private
  39245. * @type {number}
  39246. */
  39247. this._width = this.domElement.width;
  39248. /**
  39249. * The height of the renderer's default framebuffer in logical pixel unit.
  39250. *
  39251. * @private
  39252. * @type {number}
  39253. */
  39254. this._height = this.domElement.height;
  39255. /**
  39256. * The viewport of the renderer in logical pixel unit.
  39257. *
  39258. * @private
  39259. * @type {Vector4}
  39260. */
  39261. this._viewport = new Vector4( 0, 0, this._width, this._height );
  39262. /**
  39263. * The scissor rectangle of the renderer in logical pixel unit.
  39264. *
  39265. * @private
  39266. * @type {Vector4}
  39267. */
  39268. this._scissor = new Vector4( 0, 0, this._width, this._height );
  39269. /**
  39270. * Whether the scissor test should be enabled or not.
  39271. *
  39272. * @private
  39273. * @type {boolean}
  39274. */
  39275. this._scissorTest = false;
  39276. /**
  39277. * The color texture of the default framebuffer.
  39278. *
  39279. * @type {FramebufferTexture}
  39280. */
  39281. this.colorTexture = new FramebufferTexture();
  39282. /**
  39283. * The depth texture of the default framebuffer.
  39284. *
  39285. * @type {DepthTexture}
  39286. */
  39287. this.depthTexture = new DepthTexture();
  39288. }
  39289. /**
  39290. * Returns the pixel ratio.
  39291. *
  39292. * @return {number} The pixel ratio.
  39293. */
  39294. getPixelRatio() {
  39295. return this._pixelRatio;
  39296. }
  39297. /**
  39298. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39299. *
  39300. * @param {Vector2} target - The method writes the result in this target object.
  39301. * @return {Vector2} The drawing buffer size.
  39302. */
  39303. getDrawingBufferSize( target ) {
  39304. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39305. }
  39306. /**
  39307. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39308. *
  39309. * @param {Vector2} target - The method writes the result in this target object.
  39310. * @return {Vector2} The renderer's size in logical pixels.
  39311. */
  39312. getSize( target ) {
  39313. return target.set( this._width, this._height );
  39314. }
  39315. /**
  39316. * Sets the given pixel ratio and resizes the canvas if necessary.
  39317. *
  39318. * @param {number} [value=1] - The pixel ratio.
  39319. */
  39320. setPixelRatio( value = 1 ) {
  39321. if ( this._pixelRatio === value ) return;
  39322. this._pixelRatio = value;
  39323. this.setSize( this._width, this._height, false );
  39324. }
  39325. /**
  39326. * This method allows to define the drawing buffer size by specifying
  39327. * width, height and pixel ratio all at once. The size of the drawing
  39328. * buffer is computed with this formula:
  39329. * ```js
  39330. * size.x = width * pixelRatio;
  39331. * size.y = height * pixelRatio;
  39332. * ```
  39333. *
  39334. * @param {number} width - The width in logical pixels.
  39335. * @param {number} height - The height in logical pixels.
  39336. * @param {number} pixelRatio - The pixel ratio.
  39337. */
  39338. setDrawingBufferSize( width, height, pixelRatio ) {
  39339. // Renderer can't be resized while presenting in XR.
  39340. if ( this.xr && this.xr.isPresenting ) return;
  39341. this._width = width;
  39342. this._height = height;
  39343. this._pixelRatio = pixelRatio;
  39344. this.domElement.width = Math.floor( width * pixelRatio );
  39345. this.domElement.height = Math.floor( height * pixelRatio );
  39346. this.setViewport( 0, 0, width, height );
  39347. this._dispatchResize();
  39348. }
  39349. /**
  39350. * Sets the size of the renderer.
  39351. *
  39352. * @param {number} width - The width in logical pixels.
  39353. * @param {number} height - The height in logical pixels.
  39354. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39355. */
  39356. setSize( width, height, updateStyle = true ) {
  39357. // Renderer can't be resized while presenting in XR.
  39358. if ( this.xr && this.xr.isPresenting ) return;
  39359. this._width = width;
  39360. this._height = height;
  39361. this.domElement.width = Math.floor( width * this._pixelRatio );
  39362. this.domElement.height = Math.floor( height * this._pixelRatio );
  39363. if ( updateStyle === true ) {
  39364. this.domElement.style.width = width + 'px';
  39365. this.domElement.style.height = height + 'px';
  39366. }
  39367. this.setViewport( 0, 0, width, height );
  39368. this._dispatchResize();
  39369. }
  39370. /**
  39371. * Returns the scissor rectangle.
  39372. *
  39373. * @param {Vector4} target - The method writes the result in this target object.
  39374. * @return {Vector4} The scissor rectangle.
  39375. */
  39376. getScissor( target ) {
  39377. const scissor = this._scissor;
  39378. target.x = scissor.x;
  39379. target.y = scissor.y;
  39380. target.width = scissor.width;
  39381. target.height = scissor.height;
  39382. return target;
  39383. }
  39384. /**
  39385. * Defines the scissor rectangle.
  39386. *
  39387. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39388. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39389. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39390. * @param {number} width - The width of the scissor box in logical pixel unit.
  39391. * @param {number} height - The height of the scissor box in logical pixel unit.
  39392. */
  39393. setScissor( x, y, width, height ) {
  39394. const scissor = this._scissor;
  39395. if ( x.isVector4 ) {
  39396. scissor.copy( x );
  39397. } else {
  39398. scissor.set( x, y, width, height );
  39399. }
  39400. }
  39401. /**
  39402. * Returns the scissor test value.
  39403. *
  39404. * @return {boolean} Whether the scissor test should be enabled or not.
  39405. */
  39406. getScissorTest() {
  39407. return this._scissorTest;
  39408. }
  39409. /**
  39410. * Defines the scissor test.
  39411. *
  39412. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39413. */
  39414. setScissorTest( boolean ) {
  39415. this._scissorTest = boolean;
  39416. }
  39417. /**
  39418. * Returns the viewport definition.
  39419. *
  39420. * @param {Vector4} target - The method writes the result in this target object.
  39421. * @return {Vector4} The viewport definition.
  39422. */
  39423. getViewport( target ) {
  39424. return target.copy( this._viewport );
  39425. }
  39426. /**
  39427. * Defines the viewport.
  39428. *
  39429. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39430. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39431. * @param {number} width - The width of the viewport in logical pixel unit.
  39432. * @param {number} height - The height of the viewport in logical pixel unit.
  39433. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39434. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39435. */
  39436. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39437. const viewport = this._viewport;
  39438. if ( x.isVector4 ) {
  39439. viewport.copy( x );
  39440. } else {
  39441. viewport.set( x, y, width, height );
  39442. }
  39443. viewport.minDepth = minDepth;
  39444. viewport.maxDepth = maxDepth;
  39445. }
  39446. /**
  39447. * Dispatches the resize event.
  39448. *
  39449. * @private
  39450. */
  39451. _dispatchResize() {
  39452. this.dispatchEvent( { type: 'resize' } );
  39453. }
  39454. /**
  39455. * Frees the GPU-related resources allocated by this instance. Call this
  39456. * method whenever this instance is no longer used in your app.
  39457. *
  39458. * @fires RenderTarget#dispose
  39459. */
  39460. dispose() {
  39461. this.dispatchEvent( { type: 'dispose' } );
  39462. }
  39463. }
  39464. const _scene = /*@__PURE__*/ new Scene();
  39465. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  39466. const _screen = /*@__PURE__*/ new Vector4();
  39467. const _frustum = /*@__PURE__*/ new Frustum();
  39468. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  39469. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  39470. const _vector4 = /*@__PURE__*/ new Vector4();
  39471. /**
  39472. * Base class for renderers.
  39473. */
  39474. class Renderer {
  39475. /**
  39476. * Renderer options.
  39477. *
  39478. * @typedef {Object} Renderer~Options
  39479. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  39480. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  39481. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  39482. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  39483. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  39484. * @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
  39485. * to overwrite the default.
  39486. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39487. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  39488. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  39489. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  39490. */
  39491. /**
  39492. * Constructs a new renderer.
  39493. *
  39494. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  39495. * @param {Renderer~Options} [parameters] - The configuration parameter.
  39496. */
  39497. constructor( backend, parameters = {} ) {
  39498. /**
  39499. * This flag can be used for type testing.
  39500. *
  39501. * @type {boolean}
  39502. * @readonly
  39503. * @default true
  39504. */
  39505. this.isRenderer = true;
  39506. //
  39507. const {
  39508. logarithmicDepthBuffer = false,
  39509. alpha = true,
  39510. depth = true,
  39511. stencil = false,
  39512. antialias = false,
  39513. samples = 0,
  39514. getFallback = null,
  39515. colorBufferType = HalfFloatType,
  39516. multiview = false
  39517. } = parameters;
  39518. /**
  39519. * A reference to the current backend.
  39520. *
  39521. * @type {Backend}
  39522. */
  39523. this.backend = backend;
  39524. /**
  39525. * Whether the renderer should automatically clear the current rendering target
  39526. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  39527. * or the current bound render target (custom framebuffer).
  39528. *
  39529. * @type {boolean}
  39530. * @default true
  39531. */
  39532. this.autoClear = true;
  39533. /**
  39534. * When `autoClear` is set to `true`, this property defines whether the renderer
  39535. * should clear the color buffer.
  39536. *
  39537. * @type {boolean}
  39538. * @default true
  39539. */
  39540. this.autoClearColor = true;
  39541. /**
  39542. * When `autoClear` is set to `true`, this property defines whether the renderer
  39543. * should clear the depth buffer.
  39544. *
  39545. * @type {boolean}
  39546. * @default true
  39547. */
  39548. this.autoClearDepth = true;
  39549. /**
  39550. * When `autoClear` is set to `true`, this property defines whether the renderer
  39551. * should clear the stencil buffer.
  39552. *
  39553. * @type {boolean}
  39554. * @default true
  39555. */
  39556. this.autoClearStencil = true;
  39557. /**
  39558. * Whether the default framebuffer should be transparent or opaque.
  39559. *
  39560. * @type {boolean}
  39561. * @default true
  39562. */
  39563. this.alpha = alpha;
  39564. /**
  39565. * Whether logarithmic depth buffer is enabled or not.
  39566. *
  39567. * @type {boolean}
  39568. * @default false
  39569. */
  39570. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  39571. /**
  39572. * Defines the output color space of the renderer.
  39573. *
  39574. * @type {string}
  39575. * @default SRGBColorSpace
  39576. */
  39577. this.outputColorSpace = SRGBColorSpace;
  39578. /**
  39579. * Defines the tone mapping of the renderer.
  39580. *
  39581. * @type {number}
  39582. * @default NoToneMapping
  39583. */
  39584. this.toneMapping = NoToneMapping;
  39585. /**
  39586. * Defines the tone mapping exposure.
  39587. *
  39588. * @type {number}
  39589. * @default 1
  39590. */
  39591. this.toneMappingExposure = 1.0;
  39592. /**
  39593. * Whether the renderer should sort its render lists or not.
  39594. *
  39595. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  39596. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  39597. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  39598. * e.g. manually determining each object's rendering order.
  39599. *
  39600. * @type {boolean}
  39601. * @default true
  39602. */
  39603. this.sortObjects = true;
  39604. /**
  39605. * Whether the default framebuffer should have a depth buffer or not.
  39606. *
  39607. * @type {boolean}
  39608. * @default true
  39609. */
  39610. this.depth = depth;
  39611. /**
  39612. * Whether the default framebuffer should have a stencil buffer or not.
  39613. *
  39614. * @type {boolean}
  39615. * @default false
  39616. */
  39617. this.stencil = stencil;
  39618. /**
  39619. * Holds a series of statistical information about the GPU memory
  39620. * and the rendering process. Useful for debugging and monitoring.
  39621. *
  39622. * @type {Info}
  39623. */
  39624. this.info = new Info();
  39625. /**
  39626. * Stores override nodes for specific transformations or calculations.
  39627. * These nodes can be used to replace default behavior in the rendering pipeline.
  39628. *
  39629. * @type {Object}
  39630. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  39631. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  39632. */
  39633. this.overrideNodes = {
  39634. modelViewMatrix: null,
  39635. modelNormalViewMatrix: null
  39636. };
  39637. /**
  39638. * The node library defines how certain library objects like materials, lights
  39639. * or tone mapping functions are mapped to node types. This is required since
  39640. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  39641. * be part of the scene graph, they are internally represented as nodes for
  39642. * further processing.
  39643. *
  39644. * @type {NodeLibrary}
  39645. */
  39646. this.library = new NodeLibrary();
  39647. /**
  39648. * A map-like data structure for managing lights.
  39649. *
  39650. * @type {Lighting}
  39651. */
  39652. this.lighting = new Lighting();
  39653. // internals
  39654. /**
  39655. * The number of MSAA samples.
  39656. *
  39657. * @private
  39658. * @type {number}
  39659. * @default 0
  39660. */
  39661. this._samples = samples || ( antialias === true ) ? 4 : 0;
  39662. /**
  39663. * OnCanvasTargetResize callback function.
  39664. *
  39665. * @private
  39666. * @type {Function}
  39667. */
  39668. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  39669. /**
  39670. * The canvas target for rendering.
  39671. *
  39672. * @private
  39673. * @type {CanvasTarget}
  39674. */
  39675. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  39676. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  39677. this._canvasTarget.isDefaultCanvasTarget = true;
  39678. /**
  39679. * The inspector provides information about the internal renderer state.
  39680. *
  39681. * @private
  39682. * @type {InspectorBase}
  39683. */
  39684. this._inspector = new InspectorBase();
  39685. this._inspector.setRenderer( this );
  39686. /**
  39687. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39688. *
  39689. * @private
  39690. * @type {?Function}
  39691. */
  39692. this._getFallback = getFallback;
  39693. /**
  39694. * A reference to a renderer module for managing shader attributes.
  39695. *
  39696. * @private
  39697. * @type {?Attributes}
  39698. * @default null
  39699. */
  39700. this._attributes = null;
  39701. /**
  39702. * A reference to a renderer module for managing geometries.
  39703. *
  39704. * @private
  39705. * @type {?Geometries}
  39706. * @default null
  39707. */
  39708. this._geometries = null;
  39709. /**
  39710. * A reference to a renderer module for managing node related logic.
  39711. *
  39712. * @private
  39713. * @type {?Nodes}
  39714. * @default null
  39715. */
  39716. this._nodes = null;
  39717. /**
  39718. * A reference to a renderer module for managing the internal animation loop.
  39719. *
  39720. * @private
  39721. * @type {?Animation}
  39722. * @default null
  39723. */
  39724. this._animation = null;
  39725. /**
  39726. * A reference to a renderer module for managing shader program bindings.
  39727. *
  39728. * @private
  39729. * @type {?Bindings}
  39730. * @default null
  39731. */
  39732. this._bindings = null;
  39733. /**
  39734. * A reference to a renderer module for managing render objects.
  39735. *
  39736. * @private
  39737. * @type {?RenderObjects}
  39738. * @default null
  39739. */
  39740. this._objects = null;
  39741. /**
  39742. * A reference to a renderer module for managing render and compute pipelines.
  39743. *
  39744. * @private
  39745. * @type {?Pipelines}
  39746. * @default null
  39747. */
  39748. this._pipelines = null;
  39749. /**
  39750. * A reference to a renderer module for managing render bundles.
  39751. *
  39752. * @private
  39753. * @type {?RenderBundles}
  39754. * @default null
  39755. */
  39756. this._bundles = null;
  39757. /**
  39758. * A reference to a renderer module for managing render lists.
  39759. *
  39760. * @private
  39761. * @type {?RenderLists}
  39762. * @default null
  39763. */
  39764. this._renderLists = null;
  39765. /**
  39766. * A reference to a renderer module for managing render contexts.
  39767. *
  39768. * @private
  39769. * @type {?RenderContexts}
  39770. * @default null
  39771. */
  39772. this._renderContexts = null;
  39773. /**
  39774. * A reference to a renderer module for managing textures.
  39775. *
  39776. * @private
  39777. * @type {?Textures}
  39778. * @default null
  39779. */
  39780. this._textures = null;
  39781. /**
  39782. * A reference to a renderer module for backgrounds.
  39783. *
  39784. * @private
  39785. * @type {?Background}
  39786. * @default null
  39787. */
  39788. this._background = null;
  39789. /**
  39790. * This fullscreen quad is used for internal render passes
  39791. * like the tone mapping and color space output pass.
  39792. *
  39793. * @private
  39794. * @type {QuadMesh}
  39795. */
  39796. this._quad = new QuadMesh( new NodeMaterial() );
  39797. this._quad.name = 'Output Color Transform';
  39798. this._quad.material.name = 'outputColorTransform';
  39799. /**
  39800. * A reference to the current render context.
  39801. *
  39802. * @private
  39803. * @type {?RenderContext}
  39804. * @default null
  39805. */
  39806. this._currentRenderContext = null;
  39807. /**
  39808. * A custom sort function for the opaque render list.
  39809. *
  39810. * @private
  39811. * @type {?Function}
  39812. * @default null
  39813. */
  39814. this._opaqueSort = null;
  39815. /**
  39816. * A custom sort function for the transparent render list.
  39817. *
  39818. * @private
  39819. * @type {?Function}
  39820. * @default null
  39821. */
  39822. this._transparentSort = null;
  39823. /**
  39824. * The framebuffer target.
  39825. *
  39826. * @private
  39827. * @type {?RenderTarget}
  39828. * @default null
  39829. */
  39830. this._frameBufferTarget = null;
  39831. const alphaClear = this.alpha === true ? 0 : 1;
  39832. /**
  39833. * The clear color value.
  39834. *
  39835. * @private
  39836. * @type {Color4}
  39837. */
  39838. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  39839. /**
  39840. * The clear depth value.
  39841. *
  39842. * @private
  39843. * @type {number}
  39844. * @default 1
  39845. */
  39846. this._clearDepth = 1;
  39847. /**
  39848. * The clear stencil value.
  39849. *
  39850. * @private
  39851. * @type {number}
  39852. * @default 0
  39853. */
  39854. this._clearStencil = 0;
  39855. /**
  39856. * The current render target.
  39857. *
  39858. * @private
  39859. * @type {?RenderTarget}
  39860. * @default null
  39861. */
  39862. this._renderTarget = null;
  39863. /**
  39864. * The active cube face.
  39865. *
  39866. * @private
  39867. * @type {number}
  39868. * @default 0
  39869. */
  39870. this._activeCubeFace = 0;
  39871. /**
  39872. * The active mipmap level.
  39873. *
  39874. * @private
  39875. * @type {number}
  39876. * @default 0
  39877. */
  39878. this._activeMipmapLevel = 0;
  39879. /**
  39880. * The current output render target.
  39881. *
  39882. * @private
  39883. * @type {?RenderTarget}
  39884. * @default null
  39885. */
  39886. this._outputRenderTarget = null;
  39887. /**
  39888. * The MRT setting.
  39889. *
  39890. * @private
  39891. * @type {?MRTNode}
  39892. * @default null
  39893. */
  39894. this._mrt = null;
  39895. /**
  39896. * This function defines how a render object is going
  39897. * to be rendered.
  39898. *
  39899. * @private
  39900. * @type {?Function}
  39901. * @default null
  39902. */
  39903. this._renderObjectFunction = null;
  39904. /**
  39905. * Used to keep track of the current render object function.
  39906. *
  39907. * @private
  39908. * @type {?Function}
  39909. * @default null
  39910. */
  39911. this._currentRenderObjectFunction = null;
  39912. /**
  39913. * Used to keep track of the current render bundle.
  39914. *
  39915. * @private
  39916. * @type {?RenderBundle}
  39917. * @default null
  39918. */
  39919. this._currentRenderBundle = null;
  39920. /**
  39921. * Next to `_renderObjectFunction()`, this function provides another hook
  39922. * for influencing the render process of a render object. It is meant for internal
  39923. * use and only relevant for `compileAsync()` right now. Instead of using
  39924. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  39925. * a different function might be used which performs no draw but just the node
  39926. * and pipeline updates.
  39927. *
  39928. * @private
  39929. * @type {?Function}
  39930. * @default null
  39931. */
  39932. this._handleObjectFunction = this._renderObjectDirect;
  39933. /**
  39934. * Indicates whether the device has been lost or not. In WebGL terms, the device
  39935. * lost is considered as a context lost. When this is set to `true`, rendering
  39936. * isn't possible anymore.
  39937. *
  39938. * @private
  39939. * @type {boolean}
  39940. * @default false
  39941. */
  39942. this._isDeviceLost = false;
  39943. /**
  39944. * A callback function that defines what should happen when a device/context lost occurs.
  39945. *
  39946. * @type {Function}
  39947. */
  39948. this.onDeviceLost = this._onDeviceLost;
  39949. /**
  39950. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  39951. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  39952. * This will reduce rendering quality though.
  39953. *
  39954. * @private
  39955. * @type {number}
  39956. * @default HalfFloatType
  39957. */
  39958. this._colorBufferType = colorBufferType;
  39959. /**
  39960. * A cache for shadow nodes per material
  39961. *
  39962. * @private
  39963. * @type {WeakMap<Material, Object>}
  39964. */
  39965. this._cacheShadowNodes = new WeakMap();
  39966. /**
  39967. * Whether the renderer has been initialized or not.
  39968. *
  39969. * @private
  39970. * @type {boolean}
  39971. * @default false
  39972. */
  39973. this._initialized = false;
  39974. /**
  39975. * A reference to the promise which initializes the renderer.
  39976. *
  39977. * @private
  39978. * @type {?Promise<this>}
  39979. * @default null
  39980. */
  39981. this._initPromise = null;
  39982. /**
  39983. * An array of compilation promises which are used in `compileAsync()`.
  39984. *
  39985. * @private
  39986. * @type {?Array<Promise>}
  39987. * @default null
  39988. */
  39989. this._compilationPromises = null;
  39990. /**
  39991. * Whether the renderer should render transparent render objects or not.
  39992. *
  39993. * @type {boolean}
  39994. * @default true
  39995. */
  39996. this.transparent = true;
  39997. /**
  39998. * Whether the renderer should render opaque render objects or not.
  39999. *
  40000. * @type {boolean}
  40001. * @default true
  40002. */
  40003. this.opaque = true;
  40004. /**
  40005. * Shadow map configuration
  40006. * @typedef {Object} ShadowMapConfig
  40007. * @property {boolean} enabled - Whether to globally enable shadows or not.
  40008. * @property {number} type - The shadow map type.
  40009. */
  40010. /**
  40011. * The renderer's shadow configuration.
  40012. *
  40013. * @type {ShadowMapConfig}
  40014. */
  40015. this.shadowMap = {
  40016. enabled: false,
  40017. type: PCFShadowMap
  40018. };
  40019. /**
  40020. * XR configuration.
  40021. * @typedef {Object} XRConfig
  40022. * @property {boolean} enabled - Whether to globally enable XR or not.
  40023. */
  40024. /**
  40025. * The renderer's XR manager.
  40026. *
  40027. * @type {XRManager}
  40028. */
  40029. this.xr = new XRManager( this, multiview );
  40030. /**
  40031. * Debug configuration.
  40032. * @typedef {Object} DebugConfig
  40033. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  40034. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  40035. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  40036. */
  40037. /**
  40038. * The renderer's debug configuration.
  40039. *
  40040. * @type {DebugConfig}
  40041. */
  40042. this.debug = {
  40043. checkShaderErrors: true,
  40044. onShaderError: null,
  40045. getShaderAsync: async ( scene, camera, object ) => {
  40046. await this.compileAsync( scene, camera );
  40047. const renderList = this._renderLists.get( scene, camera );
  40048. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  40049. const material = scene.overrideMaterial || object.material;
  40050. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  40051. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  40052. return { fragmentShader, vertexShader };
  40053. }
  40054. };
  40055. }
  40056. /**
  40057. * Initializes the renderer so it is ready for usage.
  40058. *
  40059. * @async
  40060. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  40061. */
  40062. async init() {
  40063. if ( this._initPromise !== null ) {
  40064. return this._initPromise;
  40065. }
  40066. this._initPromise = new Promise( async ( resolve, reject ) => {
  40067. let backend = this.backend;
  40068. try {
  40069. await backend.init( this );
  40070. } catch ( error ) {
  40071. if ( this._getFallback !== null ) {
  40072. // try the fallback
  40073. try {
  40074. this.backend = backend = this._getFallback( error );
  40075. await backend.init( this );
  40076. } catch ( error ) {
  40077. reject( error );
  40078. return;
  40079. }
  40080. } else {
  40081. reject( error );
  40082. return;
  40083. }
  40084. }
  40085. this._nodes = new Nodes( this, backend );
  40086. this._animation = new Animation( this, this._nodes, this.info );
  40087. this._attributes = new Attributes( backend );
  40088. this._background = new Background( this, this._nodes );
  40089. this._geometries = new Geometries( this._attributes, this.info );
  40090. this._textures = new Textures( this, backend, this.info );
  40091. this._pipelines = new Pipelines( backend, this._nodes );
  40092. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  40093. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  40094. this._renderLists = new RenderLists( this.lighting );
  40095. this._bundles = new RenderBundles();
  40096. this._renderContexts = new RenderContexts();
  40097. //
  40098. this._animation.start();
  40099. this._initialized = true;
  40100. //
  40101. this._inspector.init();
  40102. //
  40103. resolve( this );
  40104. } );
  40105. return this._initPromise;
  40106. }
  40107. /**
  40108. * A reference to the canvas element the renderer is drawing to.
  40109. * This value of this property will automatically be created by
  40110. * the renderer.
  40111. *
  40112. * @type {HTMLCanvasElement|OffscreenCanvas}
  40113. */
  40114. get domElement() {
  40115. return this._canvasTarget.domElement;
  40116. }
  40117. /**
  40118. * The coordinate system of the renderer. The value of this property
  40119. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  40120. * `THREE.WebGPUCoordinateSystem`.
  40121. *
  40122. * @readonly
  40123. * @type {number}
  40124. */
  40125. get coordinateSystem() {
  40126. return this.backend.coordinateSystem;
  40127. }
  40128. /**
  40129. * Compiles all materials in the given scene. This can be useful to avoid a
  40130. * phenomenon which is called "shader compilation stutter", which occurs when
  40131. * rendering an object with a new shader for the first time.
  40132. *
  40133. * If you want to add a 3D object to an existing scene, use the third optional
  40134. * parameter for applying the target scene. Note that the (target) scene's lighting
  40135. * and environment must be configured before calling this method.
  40136. *
  40137. * @async
  40138. * @param {Object3D} scene - The scene or 3D object to precompile.
  40139. * @param {Camera} camera - The camera that is used to render the scene.
  40140. * @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.
  40141. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  40142. */
  40143. async compileAsync( scene, camera, targetScene = null ) {
  40144. if ( this._isDeviceLost === true ) return;
  40145. if ( this._initialized === false ) await this.init();
  40146. // preserve render tree
  40147. const nodeFrame = this._nodes.nodeFrame;
  40148. const previousRenderId = nodeFrame.renderId;
  40149. const previousRenderContext = this._currentRenderContext;
  40150. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40151. const previousCompilationPromises = this._compilationPromises;
  40152. //
  40153. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40154. if ( targetScene === null ) targetScene = scene;
  40155. const renderTarget = this._renderTarget;
  40156. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  40157. const activeMipmapLevel = this._activeMipmapLevel;
  40158. const compilationPromises = [];
  40159. this._currentRenderContext = renderContext;
  40160. this._currentRenderObjectFunction = this.renderObject;
  40161. this._handleObjectFunction = this._createObjectPipeline;
  40162. this._compilationPromises = compilationPromises;
  40163. nodeFrame.renderId ++;
  40164. //
  40165. nodeFrame.update();
  40166. //
  40167. renderContext.depth = this.depth;
  40168. renderContext.stencil = this.stencil;
  40169. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40170. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40171. //
  40172. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40173. //
  40174. const renderList = this._renderLists.get( scene, camera );
  40175. renderList.begin();
  40176. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40177. // include lights from target scene
  40178. if ( targetScene !== scene ) {
  40179. targetScene.traverseVisible( function ( object ) {
  40180. if ( object.isLight && object.layers.test( camera.layers ) ) {
  40181. renderList.pushLight( object );
  40182. }
  40183. } );
  40184. }
  40185. renderList.finish();
  40186. //
  40187. if ( renderTarget !== null ) {
  40188. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40189. const renderTargetData = this._textures.get( renderTarget );
  40190. renderContext.textures = renderTargetData.textures;
  40191. renderContext.depthTexture = renderTargetData.depthTexture;
  40192. } else {
  40193. renderContext.textures = null;
  40194. renderContext.depthTexture = null;
  40195. }
  40196. //
  40197. this._background.update( sceneRef, renderList, renderContext );
  40198. // process render lists
  40199. const opaqueObjects = renderList.opaque;
  40200. const transparentObjects = renderList.transparent;
  40201. const transparentDoublePassObjects = renderList.transparentDoublePass;
  40202. const lightsNode = renderList.lightsNode;
  40203. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40204. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40205. // restore render tree
  40206. nodeFrame.renderId = previousRenderId;
  40207. this._currentRenderContext = previousRenderContext;
  40208. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40209. this._compilationPromises = previousCompilationPromises;
  40210. this._handleObjectFunction = this._renderObjectDirect;
  40211. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  40212. await Promise.all( compilationPromises );
  40213. }
  40214. /**
  40215. * Renders the scene in an async fashion.
  40216. *
  40217. * @async
  40218. * @deprecated
  40219. * @param {Object3D} scene - The scene or 3D object to render.
  40220. * @param {Camera} camera - The camera.
  40221. * @return {Promise} A Promise that resolves when the render has been finished.
  40222. */
  40223. async renderAsync( scene, camera ) {
  40224. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40225. await this.init();
  40226. this.render( scene, camera );
  40227. }
  40228. /**
  40229. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40230. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40231. *
  40232. * @async
  40233. * @deprecated
  40234. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40235. */
  40236. async waitForGPU() {
  40237. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  40238. }
  40239. //
  40240. /**
  40241. * Sets the inspector instance. The inspector can be any class that extends from `InspectorBase`.
  40242. *
  40243. * @param {InspectorBase} value - The new inspector.
  40244. */
  40245. set inspector( value ) {
  40246. if ( this._inspector !== null ) {
  40247. this._inspector.setRenderer( null );
  40248. }
  40249. this._inspector = value;
  40250. this._inspector.setRenderer( this );
  40251. }
  40252. get inspector() {
  40253. return this._inspector;
  40254. }
  40255. /**
  40256. * Enables or disables high precision for model-view and normal-view matrices.
  40257. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  40258. *
  40259. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  40260. *
  40261. * @param {boolean} value - Whether to enable or disable high precision.
  40262. * @type {boolean}
  40263. */
  40264. set highPrecision( value ) {
  40265. if ( value === true ) {
  40266. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  40267. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  40268. } else if ( this.highPrecision ) {
  40269. this.overrideNodes.modelViewMatrix = null;
  40270. this.overrideNodes.modelNormalViewMatrix = null;
  40271. }
  40272. }
  40273. /**
  40274. * Returns whether high precision is enabled or not.
  40275. *
  40276. * @return {boolean} Whether high precision is enabled or not.
  40277. * @type {boolean}
  40278. */
  40279. get highPrecision() {
  40280. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  40281. }
  40282. /**
  40283. * Sets the given MRT configuration.
  40284. *
  40285. * @param {MRTNode} mrt - The MRT node to set.
  40286. * @return {Renderer} A reference to this renderer.
  40287. */
  40288. setMRT( mrt ) {
  40289. this._mrt = mrt;
  40290. return this;
  40291. }
  40292. /**
  40293. * Returns the MRT configuration.
  40294. *
  40295. * @return {MRTNode} The MRT configuration.
  40296. */
  40297. getMRT() {
  40298. return this._mrt;
  40299. }
  40300. /**
  40301. * Returns the color buffer type.
  40302. *
  40303. * @return {number} The color buffer type.
  40304. */
  40305. getColorBufferType() {
  40306. return this._colorBufferType;
  40307. }
  40308. /**
  40309. * Default implementation of the device lost callback.
  40310. *
  40311. * @private
  40312. * @param {Object} info - Information about the context lost.
  40313. */
  40314. _onDeviceLost( info ) {
  40315. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  40316. if ( info.reason ) {
  40317. errorMessage += `\nReason: ${info.reason}`;
  40318. }
  40319. error( errorMessage );
  40320. this._isDeviceLost = true;
  40321. }
  40322. /**
  40323. * Renders the given render bundle.
  40324. *
  40325. * @private
  40326. * @param {Object} bundle - Render bundle data.
  40327. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  40328. * @param {LightsNode} lightsNode - The lights node.
  40329. */
  40330. _renderBundle( bundle, sceneRef, lightsNode ) {
  40331. const { bundleGroup, camera, renderList } = bundle;
  40332. const renderContext = this._currentRenderContext;
  40333. //
  40334. const renderBundle = this._bundles.get( bundleGroup, camera );
  40335. const renderBundleData = this.backend.get( renderBundle );
  40336. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  40337. //
  40338. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  40339. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  40340. renderBundleData.renderContexts.add( renderContext );
  40341. if ( renderBundleNeedsUpdate ) {
  40342. this.backend.beginBundle( renderContext );
  40343. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  40344. renderBundleData.renderObjects = [];
  40345. }
  40346. this._currentRenderBundle = renderBundle;
  40347. const {
  40348. transparentDoublePass: transparentDoublePassObjects,
  40349. transparent: transparentObjects,
  40350. opaque: opaqueObjects
  40351. } = renderList;
  40352. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40353. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40354. this._currentRenderBundle = null;
  40355. //
  40356. this.backend.finishBundle( renderContext, renderBundle );
  40357. renderBundleData.version = bundleGroup.version;
  40358. } else {
  40359. const { renderObjects } = renderBundleData;
  40360. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  40361. const renderObject = renderObjects[ i ];
  40362. if ( this._nodes.needsRefresh( renderObject ) ) {
  40363. this._nodes.updateBefore( renderObject );
  40364. this._nodes.updateForRender( renderObject );
  40365. this._bindings.updateForRender( renderObject );
  40366. this._nodes.updateAfter( renderObject );
  40367. }
  40368. }
  40369. }
  40370. this.backend.addBundle( renderContext, renderBundle );
  40371. }
  40372. /**
  40373. * Renders the scene or 3D object with the given camera. This method can only be called
  40374. * if the renderer has been initialized. When using `render()` inside an animation loop,
  40375. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  40376. * with {@link Renderer#setAnimationLoop} though.
  40377. *
  40378. * For all other use cases (like when using on-demand rendering), you must call
  40379. * {@link Renderer#init} before rendering.
  40380. *
  40381. * The target of the method is the default framebuffer (meaning the canvas)
  40382. * or alternatively a render target when specified via `setRenderTarget()`.
  40383. *
  40384. * @param {Object3D} scene - The scene or 3D object to render.
  40385. * @param {Camera} camera - The camera to render the scene with.
  40386. */
  40387. render( scene, camera ) {
  40388. if ( this._initialized === false ) {
  40389. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  40390. }
  40391. this._renderScene( scene, camera );
  40392. }
  40393. /**
  40394. * Returns whether the renderer has been initialized or not.
  40395. *
  40396. * @readonly
  40397. * @return {boolean} Whether the renderer has been initialized or not.
  40398. */
  40399. get initialized() {
  40400. return this._initialized;
  40401. }
  40402. /**
  40403. * Returns an internal render target which is used when computing the output tone mapping
  40404. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  40405. * pass and not inline to achieve more correct results.
  40406. *
  40407. * @private
  40408. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  40409. */
  40410. _getFrameBufferTarget() {
  40411. const { currentToneMapping, currentColorSpace } = this;
  40412. const useToneMapping = currentToneMapping !== NoToneMapping;
  40413. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  40414. if ( useToneMapping === false && useColorSpace === false ) return null;
  40415. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  40416. const { depth, stencil } = this;
  40417. let frameBufferTarget = this._frameBufferTarget;
  40418. if ( frameBufferTarget === null ) {
  40419. frameBufferTarget = new RenderTarget( width, height, {
  40420. depthBuffer: depth,
  40421. stencilBuffer: stencil,
  40422. type: this._colorBufferType,
  40423. format: RGBAFormat,
  40424. colorSpace: ColorManagement.workingColorSpace,
  40425. generateMipmaps: false,
  40426. minFilter: LinearFilter,
  40427. magFilter: LinearFilter,
  40428. samples: this.samples
  40429. } );
  40430. frameBufferTarget.isPostProcessingRenderTarget = true;
  40431. this._frameBufferTarget = frameBufferTarget;
  40432. }
  40433. const outputRenderTarget = this.getOutputRenderTarget();
  40434. frameBufferTarget.depthBuffer = depth;
  40435. frameBufferTarget.stencilBuffer = stencil;
  40436. if ( outputRenderTarget !== null ) {
  40437. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  40438. } else {
  40439. frameBufferTarget.setSize( width, height, 1 );
  40440. }
  40441. const canvasTarget = this._canvasTarget;
  40442. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  40443. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  40444. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  40445. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  40446. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  40447. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  40448. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  40449. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  40450. return frameBufferTarget;
  40451. }
  40452. /**
  40453. * Renders the scene or 3D object with the given camera.
  40454. *
  40455. * @private
  40456. * @param {Object3D} scene - The scene or 3D object to render.
  40457. * @param {Camera} camera - The camera to render the scene with.
  40458. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  40459. * @return {RenderContext} The current render context.
  40460. */
  40461. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  40462. if ( this._isDeviceLost === true ) return;
  40463. //
  40464. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  40465. // preserve render tree
  40466. const nodeFrame = this._nodes.nodeFrame;
  40467. const previousRenderId = nodeFrame.renderId;
  40468. const previousRenderContext = this._currentRenderContext;
  40469. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40470. //
  40471. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40472. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  40473. const activeCubeFace = this._activeCubeFace;
  40474. const activeMipmapLevel = this._activeMipmapLevel;
  40475. //
  40476. let renderTarget;
  40477. if ( frameBufferTarget !== null ) {
  40478. renderTarget = frameBufferTarget;
  40479. this.setRenderTarget( renderTarget );
  40480. } else {
  40481. renderTarget = outputRenderTarget;
  40482. }
  40483. //
  40484. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  40485. this._currentRenderContext = renderContext;
  40486. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  40487. //
  40488. this.info.calls ++;
  40489. this.info.render.calls ++;
  40490. this.info.render.frameCalls ++;
  40491. nodeFrame.renderId = this.info.calls;
  40492. //
  40493. this.backend.updateTimeStampUID( renderContext );
  40494. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  40495. //
  40496. const coordinateSystem = this.coordinateSystem;
  40497. const xr = this.xr;
  40498. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  40499. camera.coordinateSystem = coordinateSystem;
  40500. camera.updateProjectionMatrix();
  40501. if ( camera.isArrayCamera ) {
  40502. for ( const subCamera of camera.cameras ) {
  40503. subCamera.coordinateSystem = coordinateSystem;
  40504. subCamera.updateProjectionMatrix();
  40505. }
  40506. }
  40507. }
  40508. //
  40509. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  40510. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  40511. if ( xr.enabled === true && xr.isPresenting === true ) {
  40512. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  40513. camera = xr.getCamera(); // use XR camera for rendering
  40514. }
  40515. //
  40516. const canvasTarget = this._canvasTarget;
  40517. let viewport = canvasTarget._viewport;
  40518. let scissor = canvasTarget._scissor;
  40519. let pixelRatio = canvasTarget._pixelRatio;
  40520. if ( renderTarget !== null ) {
  40521. viewport = renderTarget.viewport;
  40522. scissor = renderTarget.scissor;
  40523. pixelRatio = 1;
  40524. }
  40525. this.getDrawingBufferSize( _drawingBufferSize );
  40526. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  40527. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  40528. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  40529. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  40530. renderContext.viewportValue.width >>= activeMipmapLevel;
  40531. renderContext.viewportValue.height >>= activeMipmapLevel;
  40532. renderContext.viewportValue.minDepth = minDepth;
  40533. renderContext.viewportValue.maxDepth = maxDepth;
  40534. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  40535. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  40536. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  40537. renderContext.scissorValue.width >>= activeMipmapLevel;
  40538. renderContext.scissorValue.height >>= activeMipmapLevel;
  40539. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40540. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40541. //
  40542. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40543. //
  40544. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40545. if ( ! camera.isArrayCamera ) {
  40546. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  40547. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  40548. }
  40549. const renderList = this._renderLists.get( scene, camera );
  40550. renderList.begin();
  40551. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40552. renderList.finish();
  40553. if ( this.sortObjects === true ) {
  40554. renderList.sort( this._opaqueSort, this._transparentSort );
  40555. }
  40556. //
  40557. if ( renderTarget !== null ) {
  40558. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40559. const renderTargetData = this._textures.get( renderTarget );
  40560. renderContext.textures = renderTargetData.textures;
  40561. renderContext.depthTexture = renderTargetData.depthTexture;
  40562. renderContext.width = renderTargetData.width;
  40563. renderContext.height = renderTargetData.height;
  40564. renderContext.renderTarget = renderTarget;
  40565. renderContext.depth = renderTarget.depthBuffer;
  40566. renderContext.stencil = renderTarget.stencilBuffer;
  40567. } else {
  40568. renderContext.textures = null;
  40569. renderContext.depthTexture = null;
  40570. renderContext.width = _drawingBufferSize.width;
  40571. renderContext.height = _drawingBufferSize.height;
  40572. renderContext.depth = this.depth;
  40573. renderContext.stencil = this.stencil;
  40574. }
  40575. renderContext.width >>= activeMipmapLevel;
  40576. renderContext.height >>= activeMipmapLevel;
  40577. renderContext.activeCubeFace = activeCubeFace;
  40578. renderContext.activeMipmapLevel = activeMipmapLevel;
  40579. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  40580. //
  40581. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  40582. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  40583. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  40584. }
  40585. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  40586. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  40587. }
  40588. //
  40589. this._background.update( sceneRef, renderList, renderContext );
  40590. //
  40591. renderContext.camera = camera;
  40592. this.backend.beginRender( renderContext );
  40593. // process render lists
  40594. const {
  40595. bundles,
  40596. lightsNode,
  40597. transparentDoublePass: transparentDoublePassObjects,
  40598. transparent: transparentObjects,
  40599. opaque: opaqueObjects
  40600. } = renderList;
  40601. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  40602. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40603. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40604. // finish render pass
  40605. this.backend.finishRender( renderContext );
  40606. // restore render tree
  40607. nodeFrame.renderId = previousRenderId;
  40608. this._currentRenderContext = previousRenderContext;
  40609. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40610. //
  40611. if ( frameBufferTarget !== null ) {
  40612. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  40613. this._renderOutput( renderTarget );
  40614. }
  40615. //
  40616. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  40617. //
  40618. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  40619. //
  40620. return renderContext;
  40621. }
  40622. _setXRLayerSize( width, height ) {
  40623. // TODO: Find a better solution to resize the canvas when in XR.
  40624. this._canvasTarget._width = width;
  40625. this._canvasTarget._height = height;
  40626. this.setViewport( 0, 0, width, height );
  40627. }
  40628. /**
  40629. * The output pass performs tone mapping and color space conversion.
  40630. *
  40631. * @private
  40632. * @param {RenderTarget} renderTarget - The current render target.
  40633. */
  40634. _renderOutput( renderTarget ) {
  40635. const quad = this._quad;
  40636. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  40637. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  40638. quad.material.needsUpdate = true;
  40639. }
  40640. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  40641. const currentAutoClear = this.autoClear;
  40642. const currentXR = this.xr.enabled;
  40643. this.autoClear = false;
  40644. this.xr.enabled = false;
  40645. this._renderScene( quad, quad.camera, false );
  40646. this.autoClear = currentAutoClear;
  40647. this.xr.enabled = currentXR;
  40648. }
  40649. /**
  40650. * Returns the maximum available anisotropy for texture filtering.
  40651. *
  40652. * @return {number} The maximum available anisotropy.
  40653. */
  40654. getMaxAnisotropy() {
  40655. return this.backend.getMaxAnisotropy();
  40656. }
  40657. /**
  40658. * Returns the active cube face.
  40659. *
  40660. * @return {number} The active cube face.
  40661. */
  40662. getActiveCubeFace() {
  40663. return this._activeCubeFace;
  40664. }
  40665. /**
  40666. * Returns the active mipmap level.
  40667. *
  40668. * @return {number} The active mipmap level.
  40669. */
  40670. getActiveMipmapLevel() {
  40671. return this._activeMipmapLevel;
  40672. }
  40673. /**
  40674. * Applications are advised to always define the animation loop
  40675. * with this method and not manually with `requestAnimationFrame()`
  40676. * for best compatibility.
  40677. *
  40678. * @async
  40679. * @param {?onAnimationCallback} callback - The application's animation loop.
  40680. * @return {Promise} A Promise that resolves when the set has been executed.
  40681. */
  40682. async setAnimationLoop( callback ) {
  40683. if ( this._initialized === false ) await this.init();
  40684. this._animation.setAnimationLoop( callback );
  40685. }
  40686. /**
  40687. * Returns the current animation loop callback.
  40688. *
  40689. * @return {?Function} The current animation loop callback.
  40690. */
  40691. getAnimationLoop() {
  40692. return this._animation.getAnimationLoop();
  40693. }
  40694. /**
  40695. * Can be used to transfer buffer data from a storage buffer attribute
  40696. * from the GPU to the CPU in context of compute shaders.
  40697. *
  40698. * @async
  40699. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40700. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40701. */
  40702. async getArrayBufferAsync( attribute ) {
  40703. return await this.backend.getArrayBufferAsync( attribute );
  40704. }
  40705. /**
  40706. * Returns the rendering context.
  40707. *
  40708. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  40709. */
  40710. getContext() {
  40711. return this.backend.getContext();
  40712. }
  40713. /**
  40714. * Returns the pixel ratio.
  40715. *
  40716. * @return {number} The pixel ratio.
  40717. */
  40718. getPixelRatio() {
  40719. return this._canvasTarget.getPixelRatio();
  40720. }
  40721. /**
  40722. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40723. *
  40724. * @param {Vector2} target - The method writes the result in this target object.
  40725. * @return {Vector2} The drawing buffer size.
  40726. */
  40727. getDrawingBufferSize( target ) {
  40728. return this._canvasTarget.getDrawingBufferSize( target );
  40729. }
  40730. /**
  40731. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40732. *
  40733. * @param {Vector2} target - The method writes the result in this target object.
  40734. * @return {Vector2} The renderer's size in logical pixels.
  40735. */
  40736. getSize( target ) {
  40737. return this._canvasTarget.getSize( target );
  40738. }
  40739. /**
  40740. * Sets the given pixel ratio and resizes the canvas if necessary.
  40741. *
  40742. * @param {number} [value=1] - The pixel ratio.
  40743. */
  40744. setPixelRatio( value = 1 ) {
  40745. this._canvasTarget.setPixelRatio( value );
  40746. }
  40747. /**
  40748. * This method allows to define the drawing buffer size by specifying
  40749. * width, height and pixel ratio all at once. The size of the drawing
  40750. * buffer is computed with this formula:
  40751. * ```js
  40752. * size.x = width * pixelRatio;
  40753. * size.y = height * pixelRatio;
  40754. * ```
  40755. *
  40756. * @param {number} width - The width in logical pixels.
  40757. * @param {number} height - The height in logical pixels.
  40758. * @param {number} pixelRatio - The pixel ratio.
  40759. */
  40760. setDrawingBufferSize( width, height, pixelRatio ) {
  40761. // Renderer can't be resized while presenting in XR.
  40762. if ( this.xr && this.xr.isPresenting ) return;
  40763. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  40764. }
  40765. /**
  40766. * Sets the size of the renderer.
  40767. *
  40768. * @param {number} width - The width in logical pixels.
  40769. * @param {number} height - The height in logical pixels.
  40770. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40771. */
  40772. setSize( width, height, updateStyle = true ) {
  40773. // Renderer can't be resized while presenting in XR.
  40774. if ( this.xr && this.xr.isPresenting ) return;
  40775. this._canvasTarget.setSize( width, height, updateStyle );
  40776. }
  40777. /**
  40778. * Defines a manual sort function for the opaque render list.
  40779. * Pass `null` to use the default sort.
  40780. *
  40781. * @param {Function} method - The sort function.
  40782. */
  40783. setOpaqueSort( method ) {
  40784. this._opaqueSort = method;
  40785. }
  40786. /**
  40787. * Defines a manual sort function for the transparent render list.
  40788. * Pass `null` to use the default sort.
  40789. *
  40790. * @param {Function} method - The sort function.
  40791. */
  40792. setTransparentSort( method ) {
  40793. this._transparentSort = method;
  40794. }
  40795. /**
  40796. * Returns the scissor rectangle.
  40797. *
  40798. * @param {Vector4} target - The method writes the result in this target object.
  40799. * @return {Vector4} The scissor rectangle.
  40800. */
  40801. getScissor( target ) {
  40802. return this._canvasTarget.getScissor( target );
  40803. }
  40804. /**
  40805. * Defines the scissor rectangle.
  40806. *
  40807. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40808. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40809. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40810. * @param {number} width - The width of the scissor box in logical pixel unit.
  40811. * @param {number} height - The height of the scissor box in logical pixel unit.
  40812. */
  40813. setScissor( x, y, width, height ) {
  40814. this._canvasTarget.setScissor( x, y, width, height );
  40815. }
  40816. /**
  40817. * Returns the scissor test value.
  40818. *
  40819. * @return {boolean} Whether the scissor test should be enabled or not.
  40820. */
  40821. getScissorTest() {
  40822. return this._canvasTarget.getScissorTest();
  40823. }
  40824. /**
  40825. * Defines the scissor test.
  40826. *
  40827. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40828. */
  40829. setScissorTest( boolean ) {
  40830. this._canvasTarget.setScissorTest( boolean );
  40831. // TODO: Move it to CanvasTarget event listener.
  40832. this.backend.setScissorTest( boolean );
  40833. }
  40834. /**
  40835. * Returns the viewport definition.
  40836. *
  40837. * @param {Vector4} target - The method writes the result in this target object.
  40838. * @return {Vector4} The viewport definition.
  40839. */
  40840. getViewport( target ) {
  40841. return this._canvasTarget.getViewport( target );
  40842. }
  40843. /**
  40844. * Defines the viewport.
  40845. *
  40846. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40847. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40848. * @param {number} width - The width of the viewport in logical pixel unit.
  40849. * @param {number} height - The height of the viewport in logical pixel unit.
  40850. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40851. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40852. */
  40853. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40854. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  40855. }
  40856. /**
  40857. * Returns the clear color.
  40858. *
  40859. * @param {Color} target - The method writes the result in this target object.
  40860. * @return {Color} The clear color.
  40861. */
  40862. getClearColor( target ) {
  40863. return target.copy( this._clearColor );
  40864. }
  40865. /**
  40866. * Defines the clear color and optionally the clear alpha.
  40867. *
  40868. * @param {Color} color - The clear color.
  40869. * @param {number} [alpha=1] - The clear alpha.
  40870. */
  40871. setClearColor( color, alpha = 1 ) {
  40872. this._clearColor.set( color );
  40873. this._clearColor.a = alpha;
  40874. }
  40875. /**
  40876. * Returns the clear alpha.
  40877. *
  40878. * @return {number} The clear alpha.
  40879. */
  40880. getClearAlpha() {
  40881. return this._clearColor.a;
  40882. }
  40883. /**
  40884. * Defines the clear alpha.
  40885. *
  40886. * @param {number} alpha - The clear alpha.
  40887. */
  40888. setClearAlpha( alpha ) {
  40889. this._clearColor.a = alpha;
  40890. }
  40891. /**
  40892. * Returns the clear depth.
  40893. *
  40894. * @return {number} The clear depth.
  40895. */
  40896. getClearDepth() {
  40897. return this._clearDepth;
  40898. }
  40899. /**
  40900. * Defines the clear depth.
  40901. *
  40902. * @param {number} depth - The clear depth.
  40903. */
  40904. setClearDepth( depth ) {
  40905. this._clearDepth = depth;
  40906. }
  40907. /**
  40908. * Returns the clear stencil.
  40909. *
  40910. * @return {number} The clear stencil.
  40911. */
  40912. getClearStencil() {
  40913. return this._clearStencil;
  40914. }
  40915. /**
  40916. * Defines the clear stencil.
  40917. *
  40918. * @param {number} stencil - The clear stencil.
  40919. */
  40920. setClearStencil( stencil ) {
  40921. this._clearStencil = stencil;
  40922. }
  40923. /**
  40924. * This method performs an occlusion query for the given 3D object.
  40925. * It returns `true` if the given 3D object is fully occluded by other
  40926. * 3D objects in the scene.
  40927. *
  40928. * @param {Object3D} object - The 3D object to test.
  40929. * @return {boolean} Whether the 3D object is fully occluded or not.
  40930. */
  40931. isOccluded( object ) {
  40932. const renderContext = this._currentRenderContext;
  40933. return renderContext && this.backend.isOccluded( renderContext, object );
  40934. }
  40935. /**
  40936. * Performs a manual clear operation. This method ignores `autoClear` properties.
  40937. *
  40938. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40939. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40940. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40941. */
  40942. clear( color = true, depth = true, stencil = true ) {
  40943. if ( this._initialized === false ) {
  40944. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  40945. }
  40946. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40947. let renderContext = null;
  40948. if ( renderTarget !== null ) {
  40949. this._textures.updateRenderTarget( renderTarget );
  40950. const renderTargetData = this._textures.get( renderTarget );
  40951. renderContext = this._renderContexts.getForClear( renderTarget );
  40952. renderContext.textures = renderTargetData.textures;
  40953. renderContext.depthTexture = renderTargetData.depthTexture;
  40954. renderContext.width = renderTargetData.width;
  40955. renderContext.height = renderTargetData.height;
  40956. renderContext.renderTarget = renderTarget;
  40957. renderContext.depth = renderTarget.depthBuffer;
  40958. renderContext.stencil = renderTarget.stencilBuffer;
  40959. // #30329
  40960. renderContext.clearColorValue = this.backend.getClearColor();
  40961. renderContext.activeCubeFace = this.getActiveCubeFace();
  40962. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  40963. }
  40964. this.backend.clear( color, depth, stencil, renderContext );
  40965. if ( renderTarget !== null && this._renderTarget === null ) {
  40966. this._renderOutput( renderTarget );
  40967. }
  40968. }
  40969. /**
  40970. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  40971. */
  40972. clearColor() {
  40973. this.clear( true, false, false );
  40974. }
  40975. /**
  40976. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  40977. */
  40978. clearDepth() {
  40979. this.clear( false, true, false );
  40980. }
  40981. /**
  40982. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  40983. */
  40984. clearStencil() {
  40985. this.clear( false, false, true );
  40986. }
  40987. /**
  40988. * Async version of {@link Renderer#clear}.
  40989. *
  40990. * @async
  40991. * @deprecated
  40992. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40993. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40994. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40995. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40996. */
  40997. async clearAsync( color = true, depth = true, stencil = true ) {
  40998. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40999. await this.init();
  41000. this.clear( color, depth, stencil );
  41001. }
  41002. /**
  41003. * Async version of {@link Renderer#clearColor}.
  41004. *
  41005. * @async
  41006. * @deprecated
  41007. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41008. */
  41009. async clearColorAsync() {
  41010. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41011. this.clear( true, false, false );
  41012. }
  41013. /**
  41014. * Async version of {@link Renderer#clearDepth}.
  41015. *
  41016. * @async
  41017. * @deprecated
  41018. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41019. */
  41020. async clearDepthAsync() {
  41021. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41022. this.clear( false, true, false );
  41023. }
  41024. /**
  41025. * Async version of {@link Renderer#clearStencil}.
  41026. *
  41027. * @async
  41028. * @deprecated
  41029. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41030. */
  41031. async clearStencilAsync() {
  41032. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41033. this.clear( false, false, true );
  41034. }
  41035. /**
  41036. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  41037. * If this is the case, the renderer allocates an internal render target for that purpose.
  41038. *
  41039. */
  41040. get needsFrameBufferTarget() {
  41041. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  41042. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  41043. return useToneMapping || useColorSpace;
  41044. }
  41045. /**
  41046. * The number of samples used for multi-sample anti-aliasing (MSAA).
  41047. *
  41048. * @type {number}
  41049. * @default 0
  41050. */
  41051. get samples() {
  41052. return this._samples;
  41053. }
  41054. /**
  41055. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  41056. *
  41057. * When rendering to a custom render target, the number of samples of that render target is used.
  41058. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  41059. * the number of samples is set to 0.
  41060. *
  41061. * @type {number}
  41062. */
  41063. get currentSamples() {
  41064. let samples = this._samples;
  41065. if ( this._renderTarget !== null ) {
  41066. samples = this._renderTarget.samples;
  41067. } else if ( this.needsFrameBufferTarget ) {
  41068. samples = 0;
  41069. }
  41070. return samples;
  41071. }
  41072. /**
  41073. * The current tone mapping of the renderer. When not producing screen output,
  41074. * the tone mapping is always `NoToneMapping`.
  41075. *
  41076. * @type {number}
  41077. */
  41078. get currentToneMapping() {
  41079. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  41080. }
  41081. /**
  41082. * The current color space of the renderer. When not producing screen output,
  41083. * the color space is always the working color space.
  41084. *
  41085. * @type {string}
  41086. */
  41087. get currentColorSpace() {
  41088. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  41089. }
  41090. /**
  41091. * Returns `true` if the rendering settings are set to screen output.
  41092. *
  41093. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  41094. */
  41095. get isOutputTarget() {
  41096. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  41097. }
  41098. /**
  41099. * Frees all internal resources of the renderer. Call this method if the renderer
  41100. * is no longer in use by your app.
  41101. */
  41102. dispose() {
  41103. if ( this._initialized === true ) {
  41104. this.info.dispose();
  41105. this.backend.dispose();
  41106. this._animation.dispose();
  41107. this._objects.dispose();
  41108. this._geometries.dispose();
  41109. this._pipelines.dispose();
  41110. this._nodes.dispose();
  41111. this._bindings.dispose();
  41112. this._renderLists.dispose();
  41113. this._renderContexts.dispose();
  41114. this._textures.dispose();
  41115. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  41116. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  41117. if ( queryPool !== null ) queryPool.dispose();
  41118. } );
  41119. }
  41120. this.setRenderTarget( null );
  41121. this.setAnimationLoop( null );
  41122. }
  41123. /**
  41124. * Sets the given render target. Calling this method means the renderer does not
  41125. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  41126. * Use `null` as the first argument to reset the state.
  41127. *
  41128. * @param {?RenderTarget} renderTarget - The render target to set.
  41129. * @param {number} [activeCubeFace=0] - The active cube face.
  41130. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  41131. */
  41132. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  41133. this._renderTarget = renderTarget;
  41134. this._activeCubeFace = activeCubeFace;
  41135. this._activeMipmapLevel = activeMipmapLevel;
  41136. }
  41137. /**
  41138. * Returns the current render target.
  41139. *
  41140. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  41141. */
  41142. getRenderTarget() {
  41143. return this._renderTarget;
  41144. }
  41145. /**
  41146. * Sets the output render target for the renderer.
  41147. *
  41148. * @param {Object} renderTarget - The render target to set as the output target.
  41149. */
  41150. setOutputRenderTarget( renderTarget ) {
  41151. this._outputRenderTarget = renderTarget;
  41152. }
  41153. /**
  41154. * Returns the current output target.
  41155. *
  41156. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  41157. */
  41158. getOutputRenderTarget() {
  41159. return this._outputRenderTarget;
  41160. }
  41161. /**
  41162. * Sets the canvas target. The canvas target manages the HTML canvas
  41163. * or the offscreen canvas the renderer draws into.
  41164. *
  41165. * @param {CanvasTarget} canvasTarget - The canvas target.
  41166. */
  41167. setCanvasTarget( canvasTarget ) {
  41168. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  41169. this._canvasTarget = canvasTarget;
  41170. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41171. }
  41172. /**
  41173. * Returns the current canvas target.
  41174. *
  41175. * @return {CanvasTarget} The current canvas target.
  41176. */
  41177. getCanvasTarget() {
  41178. return this._canvasTarget;
  41179. }
  41180. /**
  41181. * Resets the renderer to the initial state before WebXR started.
  41182. *
  41183. */
  41184. _resetXRState() {
  41185. this.backend.setXRTarget( null );
  41186. this.setOutputRenderTarget( null );
  41187. this.setRenderTarget( null );
  41188. this._frameBufferTarget.dispose();
  41189. this._frameBufferTarget = null;
  41190. }
  41191. /**
  41192. * Callback for {@link Renderer#setRenderObjectFunction}.
  41193. *
  41194. * @callback renderObjectFunction
  41195. * @param {Object3D} object - The 3D object.
  41196. * @param {Scene} scene - The scene the 3D object belongs to.
  41197. * @param {Camera} camera - The camera the object should be rendered with.
  41198. * @param {BufferGeometry} geometry - The object's geometry.
  41199. * @param {Material} material - The object's material.
  41200. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41201. * @param {LightsNode} lightsNode - The current lights node.
  41202. * @param {ClippingContext} clippingContext - The clipping context.
  41203. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41204. */
  41205. /**
  41206. * Sets the given render object function. Calling this method overwrites the default implementation
  41207. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  41208. * if you want to modify the way objects are rendered. For example you can define things like "every
  41209. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  41210. * The custom function must always call `renderObject()` in its implementation.
  41211. *
  41212. * Use `null` as the first argument to reset the state.
  41213. *
  41214. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  41215. */
  41216. setRenderObjectFunction( renderObjectFunction ) {
  41217. this._renderObjectFunction = renderObjectFunction;
  41218. }
  41219. /**
  41220. * Returns the current render object function.
  41221. *
  41222. * @return {?Function} The current render object function. Returns `null` if no function is set.
  41223. */
  41224. getRenderObjectFunction() {
  41225. return this._renderObjectFunction;
  41226. }
  41227. /**
  41228. * Execute a single or an array of compute nodes. This method can only be called
  41229. * if the renderer has been initialized.
  41230. *
  41231. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41232. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41233. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  41234. */
  41235. compute( computeNodes, dispatchSizeOrCount = null ) {
  41236. if ( this._isDeviceLost === true ) return;
  41237. if ( this._initialized === false ) {
  41238. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  41239. return this.computeAsync( computeNodes );
  41240. }
  41241. //
  41242. const nodeFrame = this._nodes.nodeFrame;
  41243. const previousRenderId = nodeFrame.renderId;
  41244. //
  41245. this.info.calls ++;
  41246. this.info.compute.calls ++;
  41247. this.info.compute.frameCalls ++;
  41248. nodeFrame.renderId = this.info.calls;
  41249. //
  41250. this.backend.updateTimeStampUID( computeNodes );
  41251. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  41252. //
  41253. const backend = this.backend;
  41254. const pipelines = this._pipelines;
  41255. const bindings = this._bindings;
  41256. const nodes = this._nodes;
  41257. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  41258. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  41259. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  41260. }
  41261. backend.beginCompute( computeNodes );
  41262. for ( const computeNode of computeList ) {
  41263. // onInit
  41264. if ( pipelines.has( computeNode ) === false ) {
  41265. const dispose = () => {
  41266. computeNode.removeEventListener( 'dispose', dispose );
  41267. pipelines.delete( computeNode );
  41268. bindings.deleteForCompute( computeNode );
  41269. nodes.delete( computeNode );
  41270. };
  41271. computeNode.addEventListener( 'dispose', dispose );
  41272. //
  41273. const onInitFn = computeNode.onInitFunction;
  41274. if ( onInitFn !== null ) {
  41275. onInitFn.call( computeNode, { renderer: this } );
  41276. }
  41277. }
  41278. nodes.updateForCompute( computeNode );
  41279. bindings.updateForCompute( computeNode );
  41280. const computeBindings = bindings.getForCompute( computeNode );
  41281. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  41282. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  41283. }
  41284. backend.finishCompute( computeNodes );
  41285. //
  41286. nodeFrame.renderId = previousRenderId;
  41287. //
  41288. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  41289. }
  41290. /**
  41291. * Execute a single or an array of compute nodes.
  41292. *
  41293. * @async
  41294. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41295. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41296. * @return {Promise} A Promise that resolve when the compute has finished.
  41297. */
  41298. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  41299. warnOnce( 'Renderer: "computeAsync()" has been deprecated. Use "compute()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41300. await this.init();
  41301. this.compute( computeNodes, dispatchSizeOrCount );
  41302. }
  41303. /**
  41304. * Checks if the given feature is supported by the selected backend.
  41305. *
  41306. * @async
  41307. * @deprecated
  41308. * @param {string} name - The feature's name.
  41309. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41310. */
  41311. async hasFeatureAsync( name ) {
  41312. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41313. await this.init();
  41314. return this.hasFeature( name );
  41315. }
  41316. async resolveTimestampsAsync( type = 'render' ) {
  41317. if ( this._initialized === false ) await this.init();
  41318. return this.backend.resolveTimestampsAsync( type );
  41319. }
  41320. /**
  41321. * Checks if the given feature is supported by the selected backend. If the
  41322. * renderer has not been initialized, this method always returns `false`.
  41323. *
  41324. * @param {string} name - The feature's name.
  41325. * @return {boolean} Whether the feature is supported or not.
  41326. */
  41327. hasFeature( name ) {
  41328. if ( this._initialized === false ) {
  41329. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41330. }
  41331. return this.backend.hasFeature( name );
  41332. }
  41333. /**
  41334. * Returns `true` when the renderer has been initialized.
  41335. *
  41336. * @return {boolean} Whether the renderer has been initialized or not.
  41337. */
  41338. hasInitialized() {
  41339. return this._initialized;
  41340. }
  41341. /**
  41342. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  41343. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41344. *
  41345. * @async
  41346. * @deprecated
  41347. * @param {Texture} texture - The texture.
  41348. * @return {Promise} A Promise that resolves when the texture has been initialized.
  41349. */
  41350. async initTextureAsync( texture ) {
  41351. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41352. await this.init();
  41353. this.initTexture( texture );
  41354. }
  41355. /**
  41356. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  41357. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41358. *
  41359. * This method can only be used if the renderer has been initialized.
  41360. *
  41361. * @param {Texture} texture - The texture.
  41362. */
  41363. initTexture( texture ) {
  41364. if ( this._initialized === false ) {
  41365. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41366. }
  41367. this._textures.updateTexture( texture );
  41368. }
  41369. /**
  41370. * Copies the current bound framebuffer into the given texture.
  41371. *
  41372. * @param {FramebufferTexture} framebufferTexture - The texture.
  41373. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  41374. */
  41375. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  41376. if ( rectangle !== null ) {
  41377. if ( rectangle.isVector2 ) {
  41378. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  41379. } else if ( rectangle.isVector4 ) {
  41380. rectangle = _vector4.copy( rectangle ).floor();
  41381. } else {
  41382. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  41383. return;
  41384. }
  41385. } else {
  41386. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  41387. }
  41388. //
  41389. let renderContext = this._currentRenderContext;
  41390. let renderTarget;
  41391. if ( renderContext !== null ) {
  41392. renderTarget = renderContext.renderTarget;
  41393. } else {
  41394. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41395. if ( renderTarget !== null ) {
  41396. this._textures.updateRenderTarget( renderTarget );
  41397. renderContext = this._textures.get( renderTarget );
  41398. }
  41399. }
  41400. //
  41401. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  41402. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  41403. this._inspector.copyFramebufferToTexture( framebufferTexture );
  41404. }
  41405. /**
  41406. * Copies data of the given source texture into a destination texture.
  41407. *
  41408. * @param {Texture} srcTexture - The source texture.
  41409. * @param {Texture} dstTexture - The destination texture.
  41410. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  41411. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  41412. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41413. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41414. */
  41415. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41416. this._textures.updateTexture( srcTexture );
  41417. this._textures.updateTexture( dstTexture );
  41418. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  41419. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  41420. }
  41421. /**
  41422. * Reads pixel data from the given render target.
  41423. *
  41424. * @async
  41425. * @param {RenderTarget} renderTarget - The render target to read from.
  41426. * @param {number} x - The `x` coordinate of the copy region's origin.
  41427. * @param {number} y - The `y` coordinate of the copy region's origin.
  41428. * @param {number} width - The width of the copy region.
  41429. * @param {number} height - The height of the copy region.
  41430. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  41431. * @param {number} [faceIndex=0] - The active cube face index.
  41432. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  41433. */
  41434. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  41435. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  41436. }
  41437. /**
  41438. * Analyzes the given 3D object's hierarchy and builds render lists from the
  41439. * processed hierarchy.
  41440. *
  41441. * @param {Object3D} object - The 3D object to process (usually a scene).
  41442. * @param {Camera} camera - The camera the object is rendered with.
  41443. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  41444. * @param {RenderList} renderList - The current render list.
  41445. * @param {ClippingContext} clippingContext - The current clipping context.
  41446. */
  41447. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  41448. if ( object.visible === false ) return;
  41449. const visible = object.layers.test( camera.layers );
  41450. if ( visible ) {
  41451. if ( object.isGroup ) {
  41452. groupOrder = object.renderOrder;
  41453. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  41454. } else if ( object.isLOD ) {
  41455. if ( object.autoUpdate === true ) object.update( camera );
  41456. } else if ( object.isLight ) {
  41457. renderList.pushLight( object );
  41458. } else if ( object.isSprite ) {
  41459. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41460. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  41461. if ( this.sortObjects === true ) {
  41462. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  41463. }
  41464. const { geometry, material } = object;
  41465. if ( material.visible ) {
  41466. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41467. }
  41468. }
  41469. } else if ( object.isLineLoop ) {
  41470. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  41471. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  41472. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41473. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  41474. const { geometry, material } = object;
  41475. if ( this.sortObjects === true ) {
  41476. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  41477. _vector4
  41478. .copy( geometry.boundingSphere.center )
  41479. .applyMatrix4( object.matrixWorld )
  41480. .applyMatrix4( _projScreenMatrix );
  41481. }
  41482. if ( Array.isArray( material ) ) {
  41483. const groups = geometry.groups;
  41484. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  41485. const group = groups[ i ];
  41486. const groupMaterial = material[ group.materialIndex ];
  41487. if ( groupMaterial && groupMaterial.visible ) {
  41488. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  41489. }
  41490. }
  41491. } else if ( material.visible ) {
  41492. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41493. }
  41494. }
  41495. }
  41496. }
  41497. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  41498. const baseRenderList = renderList;
  41499. // replace render list
  41500. renderList = this._renderLists.get( object, camera );
  41501. renderList.begin();
  41502. baseRenderList.pushBundle( {
  41503. bundleGroup: object,
  41504. camera,
  41505. renderList,
  41506. } );
  41507. renderList.finish();
  41508. }
  41509. const children = object.children;
  41510. for ( let i = 0, l = children.length; i < l; i ++ ) {
  41511. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  41512. }
  41513. }
  41514. /**
  41515. * Renders the given render bundles.
  41516. *
  41517. * @private
  41518. * @param {Array<Object>} bundles - Array with render bundle data.
  41519. * @param {Scene} sceneRef - The scene the render bundles belong to.
  41520. * @param {LightsNode} lightsNode - The current lights node.
  41521. */
  41522. _renderBundles( bundles, sceneRef, lightsNode ) {
  41523. for ( const bundle of bundles ) {
  41524. this._renderBundle( bundle, sceneRef, lightsNode );
  41525. }
  41526. }
  41527. /**
  41528. * Renders the transparent objects from the given render lists.
  41529. *
  41530. * @private
  41531. * @param {Array<Object>} renderList - The transparent render list.
  41532. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  41533. * @param {Camera} camera - The camera the render list should be rendered with.
  41534. * @param {Scene} scene - The scene the render list belongs to.
  41535. * @param {LightsNode} lightsNode - The current lights node.
  41536. */
  41537. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  41538. if ( doublePassList.length > 0 ) {
  41539. // render back side
  41540. for ( const { material } of doublePassList ) {
  41541. material.side = BackSide;
  41542. }
  41543. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  41544. // render front side
  41545. for ( const { material } of doublePassList ) {
  41546. material.side = FrontSide;
  41547. }
  41548. this._renderObjects( renderList, camera, scene, lightsNode );
  41549. // restore
  41550. for ( const { material } of doublePassList ) {
  41551. material.side = DoubleSide;
  41552. }
  41553. } else {
  41554. this._renderObjects( renderList, camera, scene, lightsNode );
  41555. }
  41556. }
  41557. /**
  41558. * Renders the objects from the given render list.
  41559. *
  41560. * @private
  41561. * @param {Array<Object>} renderList - The render list.
  41562. * @param {Camera} camera - The camera the render list should be rendered with.
  41563. * @param {Scene} scene - The scene the render list belongs to.
  41564. * @param {LightsNode} lightsNode - The current lights node.
  41565. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41566. */
  41567. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  41568. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  41569. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  41570. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  41571. }
  41572. }
  41573. /**
  41574. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  41575. * The result is cached per material and updated when the material's version changes.
  41576. *
  41577. * @param {Material} material
  41578. * @returns {Object} - The shadow nodes for the material.
  41579. */
  41580. _getShadowNodes( material ) {
  41581. const version = material.version;
  41582. let cache = this._cacheShadowNodes.get( material );
  41583. if ( cache === undefined || cache.version !== version ) {
  41584. const hasMap = material.map !== null;
  41585. const hasColorNode = material.colorNode && material.colorNode.isNode;
  41586. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  41587. let positionNode = null;
  41588. let colorNode = null;
  41589. let depthNode = null;
  41590. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  41591. let shadowRGB;
  41592. let shadowAlpha;
  41593. if ( hasCastShadowNode ) {
  41594. shadowRGB = material.castShadowNode.rgb;
  41595. shadowAlpha = material.castShadowNode.a;
  41596. } else {
  41597. shadowRGB = vec3( 0 );
  41598. shadowAlpha = float( 1 );
  41599. }
  41600. if ( hasMap ) {
  41601. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  41602. }
  41603. if ( hasColorNode ) {
  41604. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  41605. }
  41606. colorNode = vec4( shadowRGB, shadowAlpha );
  41607. }
  41608. if ( material.depthNode && material.depthNode.isNode ) {
  41609. depthNode = material.depthNode;
  41610. }
  41611. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  41612. positionNode = material.castShadowPositionNode;
  41613. } else if ( material.positionNode && material.positionNode.isNode ) {
  41614. positionNode = material.positionNode;
  41615. }
  41616. cache = {
  41617. version,
  41618. colorNode,
  41619. depthNode,
  41620. positionNode
  41621. };
  41622. this._cacheShadowNodes.set( material, cache );
  41623. }
  41624. return cache;
  41625. }
  41626. /**
  41627. * This method represents the default render object function that manages the render lifecycle
  41628. * of the object.
  41629. *
  41630. * @param {Object3D} object - The 3D object.
  41631. * @param {Scene} scene - The scene the 3D object belongs to.
  41632. * @param {Camera} camera - The camera the object should be rendered with.
  41633. * @param {BufferGeometry} geometry - The object's geometry.
  41634. * @param {Material} material - The object's material.
  41635. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41636. * @param {LightsNode} lightsNode - The current lights node.
  41637. * @param {?ClippingContext} clippingContext - The clipping context.
  41638. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41639. */
  41640. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  41641. let materialOverride = false;
  41642. let materialColorNode;
  41643. let materialDepthNode;
  41644. let materialPositionNode;
  41645. let materialSide;
  41646. //
  41647. object.onBeforeRender( this, scene, camera, geometry, material, group );
  41648. //
  41649. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  41650. const overrideMaterial = scene.overrideMaterial;
  41651. materialOverride = true;
  41652. // store original nodes
  41653. materialColorNode = scene.overrideMaterial.colorNode;
  41654. materialDepthNode = scene.overrideMaterial.depthNode;
  41655. materialPositionNode = scene.overrideMaterial.positionNode;
  41656. materialSide = scene.overrideMaterial.side;
  41657. if ( material.positionNode && material.positionNode.isNode ) {
  41658. overrideMaterial.positionNode = material.positionNode;
  41659. }
  41660. overrideMaterial.alphaTest = material.alphaTest;
  41661. overrideMaterial.alphaMap = material.alphaMap;
  41662. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  41663. if ( overrideMaterial.isShadowPassMaterial ) {
  41664. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  41665. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  41666. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  41667. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  41668. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  41669. }
  41670. material = overrideMaterial;
  41671. }
  41672. //
  41673. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  41674. material.side = BackSide;
  41675. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  41676. material.side = FrontSide;
  41677. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  41678. material.side = DoubleSide;
  41679. } else {
  41680. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  41681. }
  41682. //
  41683. if ( materialOverride ) {
  41684. scene.overrideMaterial.colorNode = materialColorNode;
  41685. scene.overrideMaterial.depthNode = materialDepthNode;
  41686. scene.overrideMaterial.positionNode = materialPositionNode;
  41687. scene.overrideMaterial.side = materialSide;
  41688. }
  41689. //
  41690. object.onAfterRender( this, scene, camera, geometry, material, group );
  41691. }
  41692. /**
  41693. * This method represents the default `_handleObjectFunction` implementation which creates
  41694. * a render object from the given data and performs the draw command with the selected backend.
  41695. *
  41696. * @private
  41697. * @param {Object3D} object - The 3D object.
  41698. * @param {Material} material - The object's material.
  41699. * @param {Scene} scene - The scene the 3D object belongs to.
  41700. * @param {Camera} camera - The camera the object should be rendered with.
  41701. * @param {LightsNode} lightsNode - The current lights node.
  41702. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41703. * @param {ClippingContext} clippingContext - The clipping context.
  41704. * @param {string} [passId] - An optional ID for identifying the pass.
  41705. */
  41706. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41707. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41708. renderObject.drawRange = object.geometry.drawRange;
  41709. renderObject.group = group;
  41710. //
  41711. const needsRefresh = this._nodes.needsRefresh( renderObject );
  41712. if ( needsRefresh ) {
  41713. this._nodes.updateBefore( renderObject );
  41714. this._geometries.updateForRender( renderObject );
  41715. this._nodes.updateForRender( renderObject );
  41716. this._bindings.updateForRender( renderObject );
  41717. }
  41718. this._pipelines.updateForRender( renderObject );
  41719. //
  41720. if ( this._currentRenderBundle !== null ) {
  41721. const renderBundleData = this.backend.get( this._currentRenderBundle );
  41722. renderBundleData.renderObjects.push( renderObject );
  41723. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  41724. }
  41725. this.backend.draw( renderObject, this.info );
  41726. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  41727. }
  41728. /**
  41729. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  41730. * Used in `compileAsync()`.
  41731. *
  41732. * @private
  41733. * @param {Object3D} object - The 3D object.
  41734. * @param {Material} material - The object's material.
  41735. * @param {Scene} scene - The scene the 3D object belongs to.
  41736. * @param {Camera} camera - The camera the object should be rendered with.
  41737. * @param {LightsNode} lightsNode - The current lights node.
  41738. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41739. * @param {ClippingContext} clippingContext - The clipping context.
  41740. * @param {string} [passId] - An optional ID for identifying the pass.
  41741. */
  41742. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41743. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41744. renderObject.drawRange = object.geometry.drawRange;
  41745. renderObject.group = group;
  41746. //
  41747. this._nodes.updateBefore( renderObject );
  41748. this._geometries.updateForRender( renderObject );
  41749. this._nodes.updateForRender( renderObject );
  41750. this._bindings.updateForRender( renderObject );
  41751. this._pipelines.getForRender( renderObject, this._compilationPromises );
  41752. this._nodes.updateAfter( renderObject );
  41753. }
  41754. /**
  41755. * Callback when the canvas has been resized.
  41756. *
  41757. * @private
  41758. */
  41759. _onCanvasTargetResize() {
  41760. if ( this._initialized ) this.backend.updateSize();
  41761. }
  41762. /**
  41763. * Alias for `compileAsync()`.
  41764. *
  41765. * @method
  41766. * @param {Object3D} scene - The scene or 3D object to precompile.
  41767. * @param {Camera} camera - The camera that is used to render the scene.
  41768. * @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.
  41769. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  41770. */
  41771. get compile() {
  41772. return this.compileAsync;
  41773. }
  41774. }
  41775. /**
  41776. * A binding represents the connection between a resource (like a texture, sampler
  41777. * or uniform buffer) and the resource definition in a shader stage.
  41778. *
  41779. * This module is an abstract base class for all concrete bindings types.
  41780. *
  41781. * @abstract
  41782. * @private
  41783. */
  41784. class Binding {
  41785. /**
  41786. * Constructs a new binding.
  41787. *
  41788. * @param {string} [name=''] - The binding's name.
  41789. */
  41790. constructor( name = '' ) {
  41791. /**
  41792. * The binding's name.
  41793. *
  41794. * @type {string}
  41795. */
  41796. this.name = name;
  41797. /**
  41798. * A bitmask that defines in what shader stages the
  41799. * binding's resource is accessible.
  41800. *
  41801. * @type {number}
  41802. */
  41803. this.visibility = 0;
  41804. }
  41805. /**
  41806. * Makes sure binding's resource is visible for the given shader stage.
  41807. *
  41808. * @param {number} visibility - The shader stage.
  41809. */
  41810. setVisibility( visibility ) {
  41811. this.visibility |= visibility;
  41812. }
  41813. /**
  41814. * Clones the binding.
  41815. *
  41816. * @return {Binding} The cloned binding.
  41817. */
  41818. clone() {
  41819. return Object.assign( new this.constructor(), this );
  41820. }
  41821. }
  41822. /**
  41823. * This function is usually called with the length in bytes of an array buffer.
  41824. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  41825. *
  41826. * @function
  41827. * @param {number} floatLength - The buffer length.
  41828. * @return {number} The padded length.
  41829. */
  41830. function getFloatLength( floatLength ) {
  41831. // ensure chunk size alignment (STD140 layout)
  41832. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  41833. }
  41834. /**
  41835. * Represents a buffer binding type.
  41836. *
  41837. * @private
  41838. * @abstract
  41839. * @augments Binding
  41840. */
  41841. class Buffer extends Binding {
  41842. /**
  41843. * Constructs a new buffer.
  41844. *
  41845. * @param {string} name - The buffer's name.
  41846. * @param {TypedArray} [buffer=null] - The buffer.
  41847. */
  41848. constructor( name, buffer = null ) {
  41849. super( name );
  41850. /**
  41851. * This flag can be used for type testing.
  41852. *
  41853. * @type {boolean}
  41854. * @readonly
  41855. * @default true
  41856. */
  41857. this.isBuffer = true;
  41858. /**
  41859. * The bytes per element.
  41860. *
  41861. * @type {number}
  41862. */
  41863. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  41864. /**
  41865. * A reference to the internal buffer.
  41866. *
  41867. * @private
  41868. * @type {TypedArray}
  41869. */
  41870. this._buffer = buffer;
  41871. }
  41872. /**
  41873. * The buffer's byte length.
  41874. *
  41875. * @type {number}
  41876. * @readonly
  41877. */
  41878. get byteLength() {
  41879. return getFloatLength( this._buffer.byteLength );
  41880. }
  41881. /**
  41882. * A reference to the internal buffer.
  41883. *
  41884. * @type {Float32Array}
  41885. * @readonly
  41886. */
  41887. get buffer() {
  41888. return this._buffer;
  41889. }
  41890. /**
  41891. * Updates the binding.
  41892. *
  41893. * @return {boolean} Whether the buffer has been updated and must be
  41894. * uploaded to the GPU.
  41895. */
  41896. update() {
  41897. return true;
  41898. }
  41899. }
  41900. /**
  41901. * Represents a uniform buffer binding type.
  41902. *
  41903. * @private
  41904. * @augments Buffer
  41905. */
  41906. class UniformBuffer extends Buffer {
  41907. /**
  41908. * Constructs a new uniform buffer.
  41909. *
  41910. * @param {string} name - The buffer's name.
  41911. * @param {TypedArray} [buffer=null] - The buffer.
  41912. */
  41913. constructor( name, buffer = null ) {
  41914. super( name, buffer );
  41915. /**
  41916. * This flag can be used for type testing.
  41917. *
  41918. * @type {boolean}
  41919. * @readonly
  41920. * @default true
  41921. */
  41922. this.isUniformBuffer = true;
  41923. }
  41924. }
  41925. let _id$4 = 0;
  41926. /**
  41927. * A special form of uniform buffer binding type.
  41928. * It's buffer value is managed by a node object.
  41929. *
  41930. * @private
  41931. * @augments UniformBuffer
  41932. */
  41933. class NodeUniformBuffer extends UniformBuffer {
  41934. /**
  41935. * Constructs a new node-based uniform buffer.
  41936. *
  41937. * @param {BufferNode} nodeUniform - The uniform buffer node.
  41938. * @param {UniformGroupNode} groupNode - The uniform group node.
  41939. */
  41940. constructor( nodeUniform, groupNode ) {
  41941. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  41942. /**
  41943. * The uniform buffer node.
  41944. *
  41945. * @type {BufferNode}
  41946. */
  41947. this.nodeUniform = nodeUniform;
  41948. /**
  41949. * The uniform group node.
  41950. *
  41951. * @type {UniformGroupNode}
  41952. */
  41953. this.groupNode = groupNode;
  41954. }
  41955. /**
  41956. * The uniform buffer.
  41957. *
  41958. * @type {Float32Array}
  41959. */
  41960. get buffer() {
  41961. return this.nodeUniform.value;
  41962. }
  41963. }
  41964. /**
  41965. * This class represents a uniform buffer binding but with
  41966. * an API that allows to maintain individual uniform objects.
  41967. *
  41968. * @private
  41969. * @augments UniformBuffer
  41970. */
  41971. class UniformsGroup extends UniformBuffer {
  41972. /**
  41973. * Constructs a new uniforms group.
  41974. *
  41975. * @param {string} name - The group's name.
  41976. */
  41977. constructor( name ) {
  41978. super( name );
  41979. /**
  41980. * This flag can be used for type testing.
  41981. *
  41982. * @type {boolean}
  41983. * @readonly
  41984. * @default true
  41985. */
  41986. this.isUniformsGroup = true;
  41987. /**
  41988. * An array with the raw uniform values.
  41989. *
  41990. * @private
  41991. * @type {?Array<number>}
  41992. * @default null
  41993. */
  41994. this._values = null;
  41995. /**
  41996. * An array of uniform objects.
  41997. *
  41998. * The order of uniforms in this array must match the order of uniforms in the shader.
  41999. *
  42000. * @type {Array<Uniform>}
  42001. */
  42002. this.uniforms = [];
  42003. }
  42004. /**
  42005. * Adds a uniform to this group.
  42006. *
  42007. * @param {Uniform} uniform - The uniform to add.
  42008. * @return {UniformsGroup} A reference to this group.
  42009. */
  42010. addUniform( uniform ) {
  42011. this.uniforms.push( uniform );
  42012. return this;
  42013. }
  42014. /**
  42015. * Removes a uniform from this group.
  42016. *
  42017. * @param {Uniform} uniform - The uniform to remove.
  42018. * @return {UniformsGroup} A reference to this group.
  42019. */
  42020. removeUniform( uniform ) {
  42021. const index = this.uniforms.indexOf( uniform );
  42022. if ( index !== -1 ) {
  42023. this.uniforms.splice( index, 1 );
  42024. }
  42025. return this;
  42026. }
  42027. /**
  42028. * An array with the raw uniform values.
  42029. *
  42030. * @type {Array<number>}
  42031. */
  42032. get values() {
  42033. if ( this._values === null ) {
  42034. this._values = Array.from( this.buffer );
  42035. }
  42036. return this._values;
  42037. }
  42038. /**
  42039. * A Float32 array buffer with the uniform values.
  42040. *
  42041. * @type {Float32Array}
  42042. */
  42043. get buffer() {
  42044. let buffer = this._buffer;
  42045. if ( buffer === null ) {
  42046. const byteLength = this.byteLength;
  42047. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  42048. this._buffer = buffer;
  42049. }
  42050. return buffer;
  42051. }
  42052. /**
  42053. * The byte length of the buffer with correct buffer alignment.
  42054. *
  42055. * @type {number}
  42056. */
  42057. get byteLength() {
  42058. const bytesPerElement = this.bytesPerElement;
  42059. let offset = 0; // global buffer offset in bytes
  42060. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  42061. const uniform = this.uniforms[ i ];
  42062. const boundary = uniform.boundary;
  42063. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  42064. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  42065. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  42066. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  42067. offset += chunkPadding;
  42068. // Check for chunk overflow
  42069. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  42070. // Add padding to the end of the chunk
  42071. offset += ( GPU_CHUNK_BYTES - chunkStart );
  42072. }
  42073. uniform.offset = offset / bytesPerElement;
  42074. offset += itemSize;
  42075. }
  42076. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  42077. }
  42078. /**
  42079. * Updates this group by updating each uniform object of
  42080. * the internal uniform list. The uniform objects check if their
  42081. * values has actually changed so this method only returns
  42082. * `true` if there is a real value change.
  42083. *
  42084. * @return {boolean} Whether the uniforms have been updated and
  42085. * must be uploaded to the GPU.
  42086. */
  42087. update() {
  42088. let updated = false;
  42089. for ( const uniform of this.uniforms ) {
  42090. if ( this.updateByType( uniform ) === true ) {
  42091. updated = true;
  42092. }
  42093. }
  42094. return updated;
  42095. }
  42096. /**
  42097. * Updates a given uniform by calling an update method matching
  42098. * the uniforms type.
  42099. *
  42100. * @param {Uniform} uniform - The uniform to update.
  42101. * @return {boolean} Whether the uniform has been updated or not.
  42102. */
  42103. updateByType( uniform ) {
  42104. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  42105. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  42106. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  42107. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  42108. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  42109. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  42110. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  42111. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  42112. }
  42113. /**
  42114. * Updates a given Number uniform.
  42115. *
  42116. * @param {NumberUniform} uniform - The Number uniform.
  42117. * @return {boolean} Whether the uniform has been updated or not.
  42118. */
  42119. updateNumber( uniform ) {
  42120. let updated = false;
  42121. const a = this.values;
  42122. const v = uniform.getValue();
  42123. const offset = uniform.offset;
  42124. const type = uniform.getType();
  42125. if ( a[ offset ] !== v ) {
  42126. const b = this._getBufferForType( type );
  42127. b[ offset ] = a[ offset ] = v;
  42128. updated = true;
  42129. }
  42130. return updated;
  42131. }
  42132. /**
  42133. * Updates a given Vector2 uniform.
  42134. *
  42135. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  42136. * @return {boolean} Whether the uniform has been updated or not.
  42137. */
  42138. updateVector2( uniform ) {
  42139. let updated = false;
  42140. const a = this.values;
  42141. const v = uniform.getValue();
  42142. const offset = uniform.offset;
  42143. const type = uniform.getType();
  42144. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  42145. const b = this._getBufferForType( type );
  42146. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42147. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42148. updated = true;
  42149. }
  42150. return updated;
  42151. }
  42152. /**
  42153. * Updates a given Vector3 uniform.
  42154. *
  42155. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  42156. * @return {boolean} Whether the uniform has been updated or not.
  42157. */
  42158. updateVector3( uniform ) {
  42159. let updated = false;
  42160. const a = this.values;
  42161. const v = uniform.getValue();
  42162. const offset = uniform.offset;
  42163. const type = uniform.getType();
  42164. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  42165. const b = this._getBufferForType( type );
  42166. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42167. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42168. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42169. updated = true;
  42170. }
  42171. return updated;
  42172. }
  42173. /**
  42174. * Updates a given Vector4 uniform.
  42175. *
  42176. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  42177. * @return {boolean} Whether the uniform has been updated or not.
  42178. */
  42179. updateVector4( uniform ) {
  42180. let updated = false;
  42181. const a = this.values;
  42182. const v = uniform.getValue();
  42183. const offset = uniform.offset;
  42184. const type = uniform.getType();
  42185. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  42186. const b = this._getBufferForType( type );
  42187. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42188. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42189. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42190. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  42191. updated = true;
  42192. }
  42193. return updated;
  42194. }
  42195. /**
  42196. * Updates a given Color uniform.
  42197. *
  42198. * @param {ColorUniform} uniform - The Color uniform.
  42199. * @return {boolean} Whether the uniform has been updated or not.
  42200. */
  42201. updateColor( uniform ) {
  42202. let updated = false;
  42203. const a = this.values;
  42204. const c = uniform.getValue();
  42205. const offset = uniform.offset;
  42206. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  42207. const b = this.buffer;
  42208. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  42209. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  42210. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  42211. updated = true;
  42212. }
  42213. return updated;
  42214. }
  42215. /**
  42216. * Updates a given Matrix3 uniform.
  42217. *
  42218. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  42219. * @return {boolean} Whether the uniform has been updated or not.
  42220. */
  42221. updateMatrix3( uniform ) {
  42222. let updated = false;
  42223. const a = this.values;
  42224. const e = uniform.getValue().elements;
  42225. const offset = uniform.offset;
  42226. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  42227. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  42228. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  42229. const b = this.buffer;
  42230. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  42231. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  42232. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  42233. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  42234. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  42235. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  42236. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  42237. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  42238. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  42239. updated = true;
  42240. }
  42241. return updated;
  42242. }
  42243. /**
  42244. * Updates a given Matrix4 uniform.
  42245. *
  42246. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  42247. * @return {boolean} Whether the uniform has been updated or not.
  42248. */
  42249. updateMatrix4( uniform ) {
  42250. let updated = false;
  42251. const a = this.values;
  42252. const e = uniform.getValue().elements;
  42253. const offset = uniform.offset;
  42254. if ( arraysEqual( a, e, offset ) === false ) {
  42255. const b = this.buffer;
  42256. b.set( e, offset );
  42257. setArray( a, e, offset );
  42258. updated = true;
  42259. }
  42260. return updated;
  42261. }
  42262. /**
  42263. * Returns a typed array that matches the given data type.
  42264. *
  42265. * @param {string} type - The data type.
  42266. * @return {TypedArray} The typed array.
  42267. */
  42268. _getBufferForType( type ) {
  42269. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  42270. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  42271. return this.buffer;
  42272. }
  42273. }
  42274. /**
  42275. * Sets the values of the second array to the first array.
  42276. *
  42277. * @private
  42278. * @param {TypedArray} a - The first array.
  42279. * @param {TypedArray} b - The second array.
  42280. * @param {number} offset - An index offset for the first array.
  42281. */
  42282. function setArray( a, b, offset ) {
  42283. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42284. a[ offset + i ] = b[ i ];
  42285. }
  42286. }
  42287. /**
  42288. * Returns `true` if the given arrays are equal.
  42289. *
  42290. * @private
  42291. * @param {TypedArray} a - The first array.
  42292. * @param {TypedArray} b - The second array.
  42293. * @param {number} offset - An index offset for the first array.
  42294. * @return {boolean} Whether the given arrays are equal or not.
  42295. */
  42296. function arraysEqual( a, b, offset ) {
  42297. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42298. if ( a[ offset + i ] !== b[ i ] ) return false;
  42299. }
  42300. return true;
  42301. }
  42302. let _id$3 = 0;
  42303. /**
  42304. * A special form of uniforms group that represents
  42305. * the individual uniforms as node-based uniforms.
  42306. *
  42307. * @private
  42308. * @augments UniformsGroup
  42309. */
  42310. class NodeUniformsGroup extends UniformsGroup {
  42311. /**
  42312. * Constructs a new node-based uniforms group.
  42313. *
  42314. * @param {string} name - The group's name.
  42315. * @param {UniformGroupNode} groupNode - The uniform group node.
  42316. */
  42317. constructor( name, groupNode ) {
  42318. super( name );
  42319. /**
  42320. * The group's ID.
  42321. *
  42322. * @type {number}
  42323. */
  42324. this.id = _id$3 ++;
  42325. /**
  42326. * The uniform group node.
  42327. *
  42328. * @type {UniformGroupNode}
  42329. */
  42330. this.groupNode = groupNode;
  42331. /**
  42332. * This flag can be used for type testing.
  42333. *
  42334. * @type {boolean}
  42335. * @readonly
  42336. * @default true
  42337. */
  42338. this.isNodeUniformsGroup = true;
  42339. }
  42340. }
  42341. /**
  42342. * Represents a sampler binding type.
  42343. *
  42344. * @private
  42345. * @augments Binding
  42346. */
  42347. class Sampler extends Binding {
  42348. /**
  42349. * Constructs a new sampler.
  42350. *
  42351. * @param {string} name - The samplers's name.
  42352. * @param {?Texture} texture - The texture this binding is referring to.
  42353. */
  42354. constructor( name, texture ) {
  42355. super( name );
  42356. /**
  42357. * The texture the sampler is referring to.
  42358. *
  42359. * @private
  42360. * @type {?Texture}
  42361. */
  42362. this._texture = null;
  42363. /**
  42364. * An event listener which is added to {@link texture}'s dispose event.
  42365. *
  42366. * @private
  42367. * @type {Function}
  42368. */
  42369. this._onTextureDispose = () => {
  42370. this.generation = null;
  42371. this.version = 0;
  42372. };
  42373. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  42374. this.texture = texture;
  42375. /**
  42376. * The binding's version.
  42377. *
  42378. * @type {number}
  42379. */
  42380. this.version = texture ? texture.version : 0;
  42381. /**
  42382. * The binding's generation which is an additional version
  42383. * qualifier.
  42384. *
  42385. * @type {?number}
  42386. * @default null
  42387. */
  42388. this.generation = null;
  42389. /**
  42390. * The binding's sampler key.
  42391. *
  42392. * @type {string}
  42393. * @default ''
  42394. */
  42395. this.samplerKey = '';
  42396. /**
  42397. * This flag can be used for type testing.
  42398. *
  42399. * @type {boolean}
  42400. * @readonly
  42401. * @default true
  42402. */
  42403. this.isSampler = true;
  42404. }
  42405. /**
  42406. * Sets the texture of this sampler.
  42407. *
  42408. * @param {Texture} value - The texture to set.
  42409. */
  42410. set texture( value ) {
  42411. if ( this._texture === value ) return;
  42412. if ( this._texture ) {
  42413. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  42414. }
  42415. this._texture = value;
  42416. this.generation = null;
  42417. this.version = 0;
  42418. if ( this._texture ) {
  42419. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  42420. }
  42421. }
  42422. /**
  42423. * Gets the texture of this sampler.
  42424. * @return {?Texture} The texture.
  42425. */
  42426. get texture() {
  42427. return this._texture;
  42428. }
  42429. /**
  42430. * Updates the binding.
  42431. *
  42432. * @return {boolean} Whether the texture has been updated and must be
  42433. * uploaded to the GPU.
  42434. */
  42435. update() {
  42436. const { texture, version } = this;
  42437. if ( version !== texture.version ) {
  42438. this.version = texture.version;
  42439. return true;
  42440. }
  42441. return false;
  42442. }
  42443. clone() {
  42444. const clonedSampler = super.clone();
  42445. // fix dispose handler for cloned instances
  42446. // TODO: Find better solution, see #31747
  42447. clonedSampler._texture = null;
  42448. clonedSampler._onTextureDispose = () => {
  42449. clonedSampler.generation = null;
  42450. clonedSampler.version = 0;
  42451. };
  42452. clonedSampler.texture = this.texture;
  42453. return clonedSampler;
  42454. }
  42455. }
  42456. let _id$2 = 0;
  42457. /**
  42458. * Represents a sampled texture binding type.
  42459. *
  42460. * @private
  42461. * @augments Sampler
  42462. */
  42463. class SampledTexture extends Sampler {
  42464. /**
  42465. * Constructs a new sampled texture.
  42466. *
  42467. * @param {string} name - The sampled texture's name.
  42468. * @param {?Texture} texture - The texture this binding is referring to.
  42469. */
  42470. constructor( name, texture ) {
  42471. super( name, texture );
  42472. /**
  42473. * This identifier.
  42474. *
  42475. * @type {number}
  42476. */
  42477. this.id = _id$2 ++;
  42478. /**
  42479. * Whether the texture is a storage texture or not.
  42480. *
  42481. * @type {boolean}
  42482. * @default false
  42483. */
  42484. this.store = false;
  42485. /**
  42486. * The mip level to bind for storage textures.
  42487. *
  42488. * @type {number}
  42489. * @default 0
  42490. */
  42491. this.mipLevel = 0;
  42492. /**
  42493. * This flag can be used for type testing.
  42494. *
  42495. * @type {boolean}
  42496. * @readonly
  42497. * @default true
  42498. */
  42499. this.isSampledTexture = true;
  42500. }
  42501. }
  42502. /**
  42503. * A special form of sampled texture binding type.
  42504. * It's texture value is managed by a node object.
  42505. *
  42506. * @private
  42507. * @augments SampledTexture
  42508. */
  42509. class NodeSampledTexture extends SampledTexture {
  42510. /**
  42511. * Constructs a new node-based sampled texture.
  42512. *
  42513. * @param {string} name - The textures's name.
  42514. * @param {TextureNode} textureNode - The texture node.
  42515. * @param {UniformGroupNode} groupNode - The uniform group node.
  42516. * @param {?string} [access=null] - The access type.
  42517. */
  42518. constructor( name, textureNode, groupNode, access = null ) {
  42519. super( name, textureNode ? textureNode.value : null );
  42520. /**
  42521. * The texture node.
  42522. *
  42523. * @type {TextureNode}
  42524. */
  42525. this.textureNode = textureNode;
  42526. /**
  42527. * The uniform group node.
  42528. *
  42529. * @type {UniformGroupNode}
  42530. */
  42531. this.groupNode = groupNode;
  42532. /**
  42533. * The access type.
  42534. *
  42535. * @type {?string}
  42536. * @default null
  42537. */
  42538. this.access = access;
  42539. }
  42540. /**
  42541. * Updates the binding.
  42542. *
  42543. * @return {boolean} Whether the texture has been updated and must be
  42544. * uploaded to the GPU.
  42545. */
  42546. update() {
  42547. const { textureNode } = this;
  42548. if ( this.texture !== textureNode.value ) {
  42549. this.texture = textureNode.value;
  42550. return true;
  42551. }
  42552. return super.update();
  42553. }
  42554. }
  42555. /**
  42556. * A special form of sampled cube texture binding type.
  42557. * It's texture value is managed by a node object.
  42558. *
  42559. * @private
  42560. * @augments NodeSampledTexture
  42561. */
  42562. class NodeSampledCubeTexture extends NodeSampledTexture {
  42563. /**
  42564. * Constructs a new node-based sampled cube texture.
  42565. *
  42566. * @param {string} name - The textures's name.
  42567. * @param {TextureNode} textureNode - The texture node.
  42568. * @param {UniformGroupNode} groupNode - The uniform group node.
  42569. * @param {?string} [access=null] - The access type.
  42570. */
  42571. constructor( name, textureNode, groupNode, access = null ) {
  42572. super( name, textureNode, groupNode, access );
  42573. /**
  42574. * This flag can be used for type testing.
  42575. *
  42576. * @type {boolean}
  42577. * @readonly
  42578. * @default true
  42579. */
  42580. this.isSampledCubeTexture = true;
  42581. }
  42582. }
  42583. /**
  42584. * A special form of sampled 3D texture binding type.
  42585. * It's texture value is managed by a node object.
  42586. *
  42587. * @private
  42588. * @augments NodeSampledTexture
  42589. */
  42590. class NodeSampledTexture3D extends NodeSampledTexture {
  42591. /**
  42592. * Constructs a new node-based sampled 3D texture.
  42593. *
  42594. * @param {string} name - The textures's name.
  42595. * @param {TextureNode} textureNode - The texture node.
  42596. * @param {UniformGroupNode} groupNode - The uniform group node.
  42597. * @param {?string} [access=null] - The access type.
  42598. */
  42599. constructor( name, textureNode, groupNode, access = null ) {
  42600. super( name, textureNode, groupNode, access );
  42601. /**
  42602. * This flag can be used for type testing.
  42603. *
  42604. * @type {boolean}
  42605. * @readonly
  42606. * @default true
  42607. */
  42608. this.isSampledTexture3D = true;
  42609. }
  42610. }
  42611. const glslPolyfills = {
  42612. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( int x ) { return floatBitsToInt( uintBitsToFloat( x ) ); }' ),
  42613. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' )
  42614. };
  42615. const glslMethods = {
  42616. textureDimensions: 'textureSize',
  42617. equals: 'equal',
  42618. bitcast_float_int: 'floatBitsToInt',
  42619. bitcast_int_float: 'intBitsToFloat',
  42620. bitcast_uint_float: 'uintBitsToFloat',
  42621. bitcast_float_uint: 'floatBitsToUint',
  42622. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  42623. bitcast_int_uint: 'tsl_bitcast_int_to_uint'
  42624. };
  42625. const precisionLib = {
  42626. low: 'lowp',
  42627. medium: 'mediump',
  42628. high: 'highp'
  42629. };
  42630. const supports$1 = {
  42631. swizzleAssign: true,
  42632. storageBuffer: false
  42633. };
  42634. const interpolationTypeMap = {
  42635. perspective: 'smooth',
  42636. linear: 'noperspective'
  42637. };
  42638. const interpolationModeMap = {
  42639. 'centroid': 'centroid'
  42640. };
  42641. const defaultPrecisions = `
  42642. precision highp float;
  42643. precision highp int;
  42644. precision highp sampler2D;
  42645. precision highp sampler3D;
  42646. precision highp samplerCube;
  42647. precision highp sampler2DArray;
  42648. precision highp usampler2D;
  42649. precision highp usampler3D;
  42650. precision highp usamplerCube;
  42651. precision highp usampler2DArray;
  42652. precision highp isampler2D;
  42653. precision highp isampler3D;
  42654. precision highp isamplerCube;
  42655. precision highp isampler2DArray;
  42656. precision lowp sampler2DShadow;
  42657. precision lowp sampler2DArrayShadow;
  42658. precision lowp samplerCubeShadow;
  42659. `;
  42660. /**
  42661. * A node builder targeting GLSL.
  42662. *
  42663. * This module generates GLSL shader code from node materials and also
  42664. * generates the respective bindings and vertex buffer definitions. These
  42665. * data are later used by the renderer to create render and compute pipelines
  42666. * for render objects.
  42667. *
  42668. * @augments NodeBuilder
  42669. */
  42670. class GLSLNodeBuilder extends NodeBuilder {
  42671. /**
  42672. * Constructs a new GLSL node builder renderer.
  42673. *
  42674. * @param {Object3D} object - The 3D object.
  42675. * @param {Renderer} renderer - The renderer.
  42676. */
  42677. constructor( object, renderer ) {
  42678. super( object, renderer, new GLSLNodeParser() );
  42679. /**
  42680. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  42681. * another dictionary which manages UBOs per group ('render','frame','object').
  42682. *
  42683. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  42684. */
  42685. this.uniformGroups = {};
  42686. /**
  42687. * An array that holds objects defining the varying and attribute data in
  42688. * context of Transform Feedback.
  42689. *
  42690. * @type {Array<Object<string,AttributeNode|string>>}
  42691. */
  42692. this.transforms = [];
  42693. /**
  42694. * A dictionary that holds for each shader stage a Map of used extensions.
  42695. *
  42696. * @type {Object<string,Map<string,Object>>}
  42697. */
  42698. this.extensions = {};
  42699. /**
  42700. * A dictionary that holds for each shader stage an Array of used builtins.
  42701. *
  42702. * @type {Object<string,Array<string>>}
  42703. */
  42704. this.builtins = { vertex: [], fragment: [], compute: [] };
  42705. }
  42706. /**
  42707. * Checks if the given texture requires a manual conversion to the working color space.
  42708. *
  42709. * @param {Texture} texture - The texture to check.
  42710. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  42711. */
  42712. needsToWorkingColorSpace( texture ) {
  42713. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42714. }
  42715. /**
  42716. * Includes the given method name into the current
  42717. * function node.
  42718. *
  42719. * @private
  42720. * @param {string} name - The method name to include.
  42721. * @return {CodeNode} The respective code node.
  42722. */
  42723. _include( name ) {
  42724. const codeNode = glslPolyfills[ name ];
  42725. codeNode.build( this );
  42726. this.addInclude( codeNode );
  42727. return codeNode;
  42728. }
  42729. /**
  42730. * Returns the native shader method name for a given generic name.
  42731. *
  42732. * @param {string} method - The method name to resolve.
  42733. * @return {string} The resolved GLSL method name.
  42734. */
  42735. getMethod( method ) {
  42736. if ( glslPolyfills[ method ] !== undefined ) {
  42737. this._include( method );
  42738. }
  42739. return glslMethods[ method ] || method;
  42740. }
  42741. /**
  42742. * Returns the bitcast method name for a given input and outputType.
  42743. *
  42744. * @param {string} type - The output type to bitcast to.
  42745. * @param {string} inputType - The input type of the.
  42746. * @return {string} The resolved WGSL bitcast invocation.
  42747. */
  42748. getBitcastMethod( type, inputType ) {
  42749. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  42750. }
  42751. /**
  42752. * Returns the native snippet for a ternary operation.
  42753. *
  42754. * @param {string} condSnippet - The condition determining which expression gets resolved.
  42755. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  42756. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  42757. * @return {string} The resolved method name.
  42758. */
  42759. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  42760. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  42761. }
  42762. /**
  42763. * Returns the output struct name. Not relevant for GLSL.
  42764. *
  42765. * @return {string}
  42766. */
  42767. getOutputStructName() {
  42768. return '';
  42769. }
  42770. /**
  42771. * Builds the given shader node.
  42772. *
  42773. * @param {ShaderNodeInternal} shaderNode - The shader node.
  42774. * @return {string} The GLSL function code.
  42775. */
  42776. buildFunctionCode( shaderNode ) {
  42777. const layout = shaderNode.layout;
  42778. const flowData = this.flowShaderNode( shaderNode );
  42779. const parameters = [];
  42780. for ( const input of layout.inputs ) {
  42781. parameters.push( this.getType( input.type ) + ' ' + input.name );
  42782. }
  42783. //
  42784. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  42785. ${ flowData.vars }
  42786. ${ flowData.code }
  42787. return ${ flowData.result };
  42788. }`;
  42789. //
  42790. return code;
  42791. }
  42792. /**
  42793. * Setups the Pixel Buffer Object (PBO) for the given storage
  42794. * buffer node.
  42795. *
  42796. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  42797. */
  42798. setupPBO( storageBufferNode ) {
  42799. const attribute = storageBufferNode.value;
  42800. if ( attribute.pbo === undefined ) {
  42801. const originalArray = attribute.array;
  42802. const numElements = attribute.count * attribute.itemSize;
  42803. const { itemSize } = attribute;
  42804. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  42805. let format = isInteger ? RedIntegerFormat : RedFormat;
  42806. if ( itemSize === 2 ) {
  42807. format = isInteger ? RGIntegerFormat : RGFormat;
  42808. } else if ( itemSize === 3 ) {
  42809. format = isInteger ? RGBIntegerFormat : RGBFormat;
  42810. } else if ( itemSize === 4 ) {
  42811. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  42812. }
  42813. const typeMap = {
  42814. Float32Array: FloatType,
  42815. Uint8Array: UnsignedByteType,
  42816. Uint16Array: UnsignedShortType,
  42817. Uint32Array: UnsignedIntType,
  42818. Int8Array: ByteType,
  42819. Int16Array: ShortType,
  42820. Int32Array: IntType,
  42821. Uint8ClampedArray: UnsignedByteType,
  42822. };
  42823. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  42824. let height = Math.ceil( ( numElements / itemSize ) / width );
  42825. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  42826. const newSize = width * height * itemSize;
  42827. const newArray = new originalArray.constructor( newSize );
  42828. newArray.set( originalArray, 0 );
  42829. attribute.array = newArray;
  42830. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  42831. pboTexture.needsUpdate = true;
  42832. pboTexture.isPBOTexture = true;
  42833. const pbo = new TextureNode( pboTexture, null, null );
  42834. pbo.setPrecision( 'high' );
  42835. attribute.pboNode = pbo;
  42836. attribute.pbo = pbo.value;
  42837. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42838. }
  42839. }
  42840. /**
  42841. * Returns a GLSL snippet that represents the property name of the given node.
  42842. *
  42843. * @param {Node} node - The node.
  42844. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42845. * @return {string} The property name.
  42846. */
  42847. getPropertyName( node, shaderStage = this.shaderStage ) {
  42848. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  42849. return shaderStage.charAt( 0 ) + '_' + node.name;
  42850. }
  42851. return super.getPropertyName( node, shaderStage );
  42852. }
  42853. /**
  42854. * Setups the Pixel Buffer Object (PBO) for the given storage
  42855. * buffer node.
  42856. *
  42857. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  42858. * @return {string} The property name.
  42859. */
  42860. generatePBO( storageArrayElementNode ) {
  42861. const { node, indexNode } = storageArrayElementNode;
  42862. const attribute = node.value;
  42863. if ( this.renderer.backend.has( attribute ) ) {
  42864. const attributeData = this.renderer.backend.get( attribute );
  42865. attributeData.pbo = attribute.pbo;
  42866. }
  42867. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42868. const textureName = this.getPropertyName( nodeUniform );
  42869. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  42870. const indexSnippet = indexNode.build( this, 'uint' );
  42871. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  42872. let propertyName = elementNodeData.propertyName;
  42873. if ( propertyName === undefined ) {
  42874. // property element
  42875. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  42876. propertyName = this.getPropertyName( nodeVar );
  42877. // property size
  42878. const bufferNodeData = this.getDataFromNode( node );
  42879. let propertySizeName = bufferNodeData.propertySizeName;
  42880. if ( propertySizeName === undefined ) {
  42881. propertySizeName = propertyName + 'Size';
  42882. this.getVarFromNode( node, propertySizeName, 'uint' );
  42883. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  42884. bufferNodeData.propertySizeName = propertySizeName;
  42885. }
  42886. //
  42887. const { itemSize } = attribute;
  42888. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  42889. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  42890. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  42891. //
  42892. let prefix = 'vec4';
  42893. if ( attribute.pbo.type === UnsignedIntType ) {
  42894. prefix = 'uvec4';
  42895. } else if ( attribute.pbo.type === IntType ) {
  42896. prefix = 'ivec4';
  42897. }
  42898. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  42899. elementNodeData.propertyName = propertyName;
  42900. }
  42901. return propertyName;
  42902. }
  42903. /**
  42904. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  42905. *
  42906. * @param {?Texture} texture - The texture.
  42907. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42908. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42909. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42910. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42911. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42912. * @return {string} The GLSL snippet.
  42913. */
  42914. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  42915. if ( levelSnippet === null ) levelSnippet = '0';
  42916. let snippet;
  42917. if ( depthSnippet ) {
  42918. if ( offsetSnippet ) {
  42919. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  42920. } else {
  42921. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  42922. }
  42923. } else {
  42924. if ( offsetSnippet ) {
  42925. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42926. } else {
  42927. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42928. }
  42929. }
  42930. if ( texture !== null && texture.isDepthTexture ) {
  42931. snippet += '.x';
  42932. }
  42933. return snippet;
  42934. }
  42935. /**
  42936. * Generates the GLSL snippet for sampling/loading the given texture.
  42937. *
  42938. * @param {Texture} texture - The texture.
  42939. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42940. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42941. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42942. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42943. * @return {string} The GLSL snippet.
  42944. */
  42945. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  42946. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  42947. if ( texture.isDepthTexture ) {
  42948. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  42949. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  42950. }
  42951. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  42952. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  42953. }
  42954. /**
  42955. * Generates the GLSL snippet when sampling textures with explicit mip level.
  42956. *
  42957. * @param {Texture} texture - The texture.
  42958. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42959. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42960. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42961. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42962. * @return {string} The GLSL snippet.
  42963. */
  42964. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  42965. if ( offsetSnippet ) {
  42966. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42967. }
  42968. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  42969. }
  42970. /**
  42971. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  42972. *
  42973. * @param {Texture} texture - The texture.
  42974. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42975. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42976. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  42977. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42978. * @return {string} The GLSL snippet.
  42979. */
  42980. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  42981. if ( offsetSnippet ) {
  42982. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  42983. }
  42984. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  42985. }
  42986. /**
  42987. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  42988. *
  42989. * @param {Texture} texture - The texture.
  42990. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42991. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42992. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  42993. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42994. * @return {string} The GLSL snippet.
  42995. */
  42996. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  42997. if ( offsetSnippet ) {
  42998. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  42999. }
  43000. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43001. }
  43002. /**
  43003. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  43004. * against a reference value.
  43005. *
  43006. * @param {Texture} texture - The texture.
  43007. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43008. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43009. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  43010. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  43011. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43012. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43013. * @return {string} The GLSL snippet.
  43014. */
  43015. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  43016. if ( shaderStage === 'fragment' ) {
  43017. if ( depthSnippet ) {
  43018. if ( offsetSnippet ) {
  43019. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  43020. }
  43021. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  43022. }
  43023. if ( offsetSnippet ) {
  43024. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  43025. }
  43026. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  43027. } else {
  43028. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43029. }
  43030. }
  43031. /**
  43032. * Returns the variables of the given shader stage as a GLSL string.
  43033. *
  43034. * @param {string} shaderStage - The shader stage.
  43035. * @return {string} The GLSL snippet that defines the variables.
  43036. */
  43037. getVars( shaderStage ) {
  43038. const snippets = [];
  43039. const vars = this.vars[ shaderStage ];
  43040. if ( vars !== undefined ) {
  43041. for ( const variable of vars ) {
  43042. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  43043. }
  43044. }
  43045. return snippets.join( '\n\t' );
  43046. }
  43047. /**
  43048. * Returns the uniforms of the given shader stage as a GLSL string.
  43049. *
  43050. * @param {string} shaderStage - The shader stage.
  43051. * @return {string} The GLSL snippet that defines the uniforms.
  43052. */
  43053. getUniforms( shaderStage ) {
  43054. const uniforms = this.uniforms[ shaderStage ];
  43055. const bindingSnippets = [];
  43056. const uniformGroups = {};
  43057. for ( const uniform of uniforms ) {
  43058. let snippet = null;
  43059. let group = false;
  43060. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  43061. const texture = uniform.node.value;
  43062. let typePrefix = '';
  43063. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  43064. if ( texture.type === UnsignedIntType ) {
  43065. typePrefix = 'u';
  43066. } else if ( texture.type === IntType ) {
  43067. typePrefix = 'i';
  43068. }
  43069. }
  43070. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  43071. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  43072. } else if ( texture.compareFunction ) {
  43073. if ( texture.isArrayTexture === true ) {
  43074. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  43075. } else {
  43076. snippet = `sampler2DShadow ${ uniform.name };`;
  43077. }
  43078. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43079. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  43080. } else {
  43081. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  43082. }
  43083. } else if ( uniform.type === 'cubeTexture' ) {
  43084. snippet = `samplerCube ${ uniform.name };`;
  43085. } else if ( uniform.type === 'buffer' ) {
  43086. const bufferNode = uniform.node;
  43087. const bufferType = this.getType( bufferNode.bufferType );
  43088. const bufferCount = bufferNode.bufferCount;
  43089. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  43090. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  43091. } else {
  43092. const vectorType = this.getVectorType( uniform.type );
  43093. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  43094. group = true;
  43095. }
  43096. const precision = uniform.node.precision;
  43097. if ( precision !== null ) {
  43098. snippet = precisionLib[ precision ] + ' ' + snippet;
  43099. }
  43100. if ( group ) {
  43101. snippet = '\t' + snippet;
  43102. const groupName = uniform.groupNode.name;
  43103. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  43104. groupSnippets.push( snippet );
  43105. } else {
  43106. snippet = 'uniform ' + snippet;
  43107. bindingSnippets.push( snippet );
  43108. }
  43109. }
  43110. let output = '';
  43111. for ( const name in uniformGroups ) {
  43112. const groupSnippets = uniformGroups[ name ];
  43113. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  43114. }
  43115. output += bindingSnippets.join( '\n' );
  43116. return output;
  43117. }
  43118. /**
  43119. * Returns the type for a given buffer attribute.
  43120. *
  43121. * @param {BufferAttribute} attribute - The buffer attribute.
  43122. * @return {string} The type.
  43123. */
  43124. getTypeFromAttribute( attribute ) {
  43125. let nodeType = super.getTypeFromAttribute( attribute );
  43126. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  43127. let dataAttribute = attribute;
  43128. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  43129. const array = dataAttribute.array;
  43130. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  43131. nodeType = nodeType.slice( 1 );
  43132. }
  43133. }
  43134. return nodeType;
  43135. }
  43136. /**
  43137. * Returns the shader attributes of the given shader stage as a GLSL string.
  43138. *
  43139. * @param {string} shaderStage - The shader stage.
  43140. * @return {string} The GLSL snippet that defines the shader attributes.
  43141. */
  43142. getAttributes( shaderStage ) {
  43143. let snippet = '';
  43144. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43145. const attributes = this.getAttributesArray();
  43146. let location = 0;
  43147. for ( const attribute of attributes ) {
  43148. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  43149. }
  43150. }
  43151. return snippet;
  43152. }
  43153. /**
  43154. * Returns the members of the given struct type node as a GLSL string.
  43155. *
  43156. * @param {StructTypeNode} struct - The struct type node.
  43157. * @return {string} The GLSL snippet that defines the struct members.
  43158. */
  43159. getStructMembers( struct ) {
  43160. const snippets = [];
  43161. for ( const member of struct.members ) {
  43162. snippets.push( `\t${ member.type } ${ member.name };` );
  43163. }
  43164. return snippets.join( '\n' );
  43165. }
  43166. /**
  43167. * Returns the structs of the given shader stage as a GLSL string.
  43168. *
  43169. * @param {string} shaderStage - The shader stage.
  43170. * @return {string} The GLSL snippet that defines the structs.
  43171. */
  43172. getStructs( shaderStage ) {
  43173. const snippets = [];
  43174. const structs = this.structs[ shaderStage ];
  43175. const outputSnippet = [];
  43176. for ( const struct of structs ) {
  43177. if ( struct.output ) {
  43178. for ( const member of struct.members ) {
  43179. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  43180. }
  43181. } else {
  43182. let snippet = 'struct ' + struct.name + ' {\n';
  43183. snippet += this.getStructMembers( struct );
  43184. snippet += '\n};\n';
  43185. snippets.push( snippet );
  43186. }
  43187. }
  43188. if ( outputSnippet.length === 0 ) {
  43189. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  43190. }
  43191. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  43192. }
  43193. /**
  43194. * Returns the varyings of the given shader stage as a GLSL string.
  43195. *
  43196. * @param {string} shaderStage - The shader stage.
  43197. * @return {string} The GLSL snippet that defines the varyings.
  43198. */
  43199. getVaryings( shaderStage ) {
  43200. let snippet = '';
  43201. const varyings = this.varyings;
  43202. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43203. for ( const varying of varyings ) {
  43204. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  43205. const type = this.getType( varying.type );
  43206. if ( varying.needsInterpolation ) {
  43207. if ( varying.interpolationType ) {
  43208. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43209. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43210. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  43211. } else {
  43212. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43213. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  43214. }
  43215. } else {
  43216. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  43217. }
  43218. }
  43219. } else if ( shaderStage === 'fragment' ) {
  43220. for ( const varying of varyings ) {
  43221. if ( varying.needsInterpolation ) {
  43222. const type = this.getType( varying.type );
  43223. if ( varying.interpolationType ) {
  43224. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43225. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43226. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  43227. } else {
  43228. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43229. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  43230. }
  43231. }
  43232. }
  43233. }
  43234. for ( const builtin of this.builtins[ shaderStage ] ) {
  43235. snippet += `${builtin};\n`;
  43236. }
  43237. return snippet;
  43238. }
  43239. /**
  43240. * Returns the vertex index builtin.
  43241. *
  43242. * @return {string} The vertex index.
  43243. */
  43244. getVertexIndex() {
  43245. return 'uint( gl_VertexID )';
  43246. }
  43247. /**
  43248. * Contextually returns either the vertex stage instance index builtin
  43249. * or the linearized index of an compute invocation within a grid of workgroups.
  43250. *
  43251. * @return {string} The instance index.
  43252. */
  43253. getInstanceIndex() {
  43254. return 'uint( gl_InstanceID )';
  43255. }
  43256. /**
  43257. * Returns a builtin representing the index of an invocation within its workgroup.
  43258. *
  43259. * @return {string} The invocation local index.
  43260. */
  43261. getInvocationLocalIndex() {
  43262. const workgroupSize = this.object.workgroupSize;
  43263. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  43264. return `uint( gl_InstanceID ) % ${size}u`;
  43265. }
  43266. /**
  43267. * Returns a builtin representing the size of a subgroup within the current shader.
  43268. */
  43269. getSubgroupSize() {
  43270. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  43271. }
  43272. /**
  43273. * Returns a builtin representing the index of an invocation within its subgroup.
  43274. */
  43275. getInvocationSubgroupIndex() {
  43276. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  43277. }
  43278. /**
  43279. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  43280. */
  43281. getSubgroupIndex() {
  43282. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  43283. }
  43284. /**
  43285. * Returns the draw index builtin.
  43286. *
  43287. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  43288. */
  43289. getDrawIndex() {
  43290. const extensions = this.renderer.backend.extensions;
  43291. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  43292. return 'uint( gl_DrawID )';
  43293. }
  43294. return null;
  43295. }
  43296. /**
  43297. * Returns the front facing builtin.
  43298. *
  43299. * @return {string} The front facing builtin.
  43300. */
  43301. getFrontFacing() {
  43302. return 'gl_FrontFacing';
  43303. }
  43304. /**
  43305. * Returns the frag coord builtin.
  43306. *
  43307. * @return {string} The frag coord builtin.
  43308. */
  43309. getFragCoord() {
  43310. return 'gl_FragCoord.xy';
  43311. }
  43312. /**
  43313. * Returns the frag depth builtin.
  43314. *
  43315. * @return {string} The frag depth builtin.
  43316. */
  43317. getFragDepth() {
  43318. return 'gl_FragDepth';
  43319. }
  43320. /**
  43321. * Enables the given extension.
  43322. *
  43323. * @param {string} name - The extension name.
  43324. * @param {string} behavior - The extension behavior.
  43325. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  43326. */
  43327. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  43328. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  43329. if ( map.has( name ) === false ) {
  43330. map.set( name, {
  43331. name,
  43332. behavior
  43333. } );
  43334. }
  43335. }
  43336. /**
  43337. * Returns the enabled extensions of the given shader stage as a GLSL string.
  43338. *
  43339. * @param {string} shaderStage - The shader stage.
  43340. * @return {string} The GLSL snippet that defines the enabled extensions.
  43341. */
  43342. getExtensions( shaderStage ) {
  43343. const snippets = [];
  43344. if ( shaderStage === 'vertex' ) {
  43345. const ext = this.renderer.backend.extensions;
  43346. const isBatchedMesh = this.object.isBatchedMesh;
  43347. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  43348. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  43349. }
  43350. }
  43351. const extensions = this.extensions[ shaderStage ];
  43352. if ( extensions !== undefined ) {
  43353. for ( const { name, behavior } of extensions.values() ) {
  43354. snippets.push( `#extension ${name} : ${behavior}` );
  43355. }
  43356. }
  43357. return snippets.join( '\n' );
  43358. }
  43359. /**
  43360. * Returns the clip distances builtin.
  43361. *
  43362. * @return {string} The clip distances builtin.
  43363. */
  43364. getClipDistance() {
  43365. return 'gl_ClipDistance';
  43366. }
  43367. /**
  43368. * Whether the requested feature is available or not.
  43369. *
  43370. * @param {string} name - The requested feature.
  43371. * @return {boolean} Whether the requested feature is supported or not.
  43372. */
  43373. isAvailable( name ) {
  43374. let result = supports$1[ name ];
  43375. if ( result === undefined ) {
  43376. let extensionName;
  43377. result = false;
  43378. switch ( name ) {
  43379. case 'float32Filterable':
  43380. extensionName = 'OES_texture_float_linear';
  43381. break;
  43382. case 'clipDistance':
  43383. extensionName = 'WEBGL_clip_cull_distance';
  43384. break;
  43385. }
  43386. if ( extensionName !== undefined ) {
  43387. const extensions = this.renderer.backend.extensions;
  43388. if ( extensions.has( extensionName ) ) {
  43389. extensions.get( extensionName );
  43390. result = true;
  43391. }
  43392. }
  43393. supports$1[ name ] = result;
  43394. }
  43395. return result;
  43396. }
  43397. /**
  43398. * Whether to flip texture data along its vertical axis or not.
  43399. *
  43400. * @return {boolean} Returns always `true` in context of GLSL.
  43401. */
  43402. isFlipY() {
  43403. return true;
  43404. }
  43405. /**
  43406. * Enables hardware clipping.
  43407. *
  43408. * @param {string} planeCount - The clipping plane count.
  43409. */
  43410. enableHardwareClipping( planeCount ) {
  43411. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  43412. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  43413. }
  43414. /**
  43415. * Enables multiview.
  43416. */
  43417. enableMultiview() {
  43418. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  43419. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  43420. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  43421. }
  43422. /**
  43423. * Registers a transform in context of Transform Feedback.
  43424. *
  43425. * @param {string} varyingName - The varying name.
  43426. * @param {AttributeNode} attributeNode - The attribute node.
  43427. */
  43428. registerTransform( varyingName, attributeNode ) {
  43429. this.transforms.push( { varyingName, attributeNode } );
  43430. }
  43431. /**
  43432. * Returns the transforms of the given shader stage as a GLSL string.
  43433. *
  43434. * @param {string} shaderStage - The shader stage.
  43435. * @return {string} The GLSL snippet that defines the transforms.
  43436. */
  43437. getTransforms( /* shaderStage */ ) {
  43438. const transforms = this.transforms;
  43439. let snippet = '';
  43440. for ( let i = 0; i < transforms.length; i ++ ) {
  43441. const transform = transforms[ i ];
  43442. const attributeName = this.getPropertyName( transform.attributeNode );
  43443. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  43444. }
  43445. return snippet;
  43446. }
  43447. /**
  43448. * Returns a GLSL struct based on the given name and variables.
  43449. *
  43450. * @private
  43451. * @param {string} name - The struct name.
  43452. * @param {string} vars - The struct variables.
  43453. * @return {string} The GLSL snippet representing a struct.
  43454. */
  43455. _getGLSLUniformStruct( name, vars ) {
  43456. return `
  43457. layout( std140 ) uniform ${name} {
  43458. ${vars}
  43459. };`;
  43460. }
  43461. /**
  43462. * Returns a GLSL vertex shader based on the given shader data.
  43463. *
  43464. * @private
  43465. * @param {Object} shaderData - The shader data.
  43466. * @return {string} The vertex shader.
  43467. */
  43468. _getGLSLVertexCode( shaderData ) {
  43469. return `#version 300 es
  43470. ${ this.getSignature() }
  43471. // extensions
  43472. ${shaderData.extensions}
  43473. // precision
  43474. ${ defaultPrecisions }
  43475. // uniforms
  43476. ${shaderData.uniforms}
  43477. // varyings
  43478. ${shaderData.varyings}
  43479. // attributes
  43480. ${shaderData.attributes}
  43481. // codes
  43482. ${shaderData.codes}
  43483. void main() {
  43484. // vars
  43485. ${shaderData.vars}
  43486. // transforms
  43487. ${shaderData.transforms}
  43488. // flow
  43489. ${shaderData.flow}
  43490. gl_PointSize = 1.0;
  43491. }
  43492. `;
  43493. }
  43494. /**
  43495. * Returns a GLSL fragment shader based on the given shader data.
  43496. *
  43497. * @private
  43498. * @param {Object} shaderData - The shader data.
  43499. * @return {string} The vertex shader.
  43500. */
  43501. _getGLSLFragmentCode( shaderData ) {
  43502. return `#version 300 es
  43503. ${ this.getSignature() }
  43504. // extensions
  43505. ${shaderData.extensions}
  43506. // precision
  43507. ${ defaultPrecisions }
  43508. // structs
  43509. ${shaderData.structs}
  43510. // uniforms
  43511. ${shaderData.uniforms}
  43512. // varyings
  43513. ${shaderData.varyings}
  43514. // codes
  43515. ${shaderData.codes}
  43516. void main() {
  43517. // vars
  43518. ${shaderData.vars}
  43519. // flow
  43520. ${shaderData.flow}
  43521. }
  43522. `;
  43523. }
  43524. /**
  43525. * Controls the code build of the shader stages.
  43526. */
  43527. buildCode() {
  43528. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43529. this.sortBindingGroups();
  43530. for ( const shaderStage in shadersData ) {
  43531. let flow = '// code\n\n';
  43532. flow += this.flowCode[ shaderStage ];
  43533. const flowNodes = this.flowNodes[ shaderStage ];
  43534. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43535. for ( const node of flowNodes ) {
  43536. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43537. const slotName = node.name;
  43538. if ( slotName ) {
  43539. if ( flow.length > 0 ) flow += '\n';
  43540. flow += `\t// flow -> ${ slotName }\n\t`;
  43541. }
  43542. flow += `${ flowSlotData.code }\n\t`;
  43543. if ( node === mainNode && shaderStage !== 'compute' ) {
  43544. flow += '// result\n\t';
  43545. if ( shaderStage === 'vertex' ) {
  43546. flow += 'gl_Position = ';
  43547. flow += `${ flowSlotData.result };`;
  43548. } else if ( shaderStage === 'fragment' ) {
  43549. if ( ! node.outputNode.isOutputStructNode ) {
  43550. flow += 'fragColor = ';
  43551. flow += `${ flowSlotData.result };`;
  43552. }
  43553. }
  43554. }
  43555. }
  43556. const stageData = shadersData[ shaderStage ];
  43557. stageData.extensions = this.getExtensions( shaderStage );
  43558. stageData.uniforms = this.getUniforms( shaderStage );
  43559. stageData.attributes = this.getAttributes( shaderStage );
  43560. stageData.varyings = this.getVaryings( shaderStage );
  43561. stageData.vars = this.getVars( shaderStage );
  43562. stageData.structs = this.getStructs( shaderStage );
  43563. stageData.codes = this.getCodes( shaderStage );
  43564. stageData.transforms = this.getTransforms( shaderStage );
  43565. stageData.flow = flow;
  43566. }
  43567. if ( this.material !== null ) {
  43568. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  43569. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  43570. } else {
  43571. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  43572. }
  43573. }
  43574. /**
  43575. * This method is one of the more important ones since it's responsible
  43576. * for generating a matching binding instance for the given uniform node.
  43577. *
  43578. * These bindings are later used in the renderer to create bind groups
  43579. * and layouts.
  43580. *
  43581. * @param {UniformNode} node - The uniform node.
  43582. * @param {string} type - The node data type.
  43583. * @param {string} shaderStage - The shader stage.
  43584. * @param {?string} [name=null] - An optional uniform name.
  43585. * @return {NodeUniform} The node uniform object.
  43586. */
  43587. getUniformFromNode( node, type, shaderStage, name = null ) {
  43588. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43589. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43590. let uniformGPU = nodeData.uniformGPU;
  43591. if ( uniformGPU === undefined ) {
  43592. const group = node.groupNode;
  43593. const groupName = group.name;
  43594. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43595. if ( type === 'texture' ) {
  43596. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  43597. bindings.push( uniformGPU );
  43598. } else if ( type === 'cubeTexture' ) {
  43599. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  43600. bindings.push( uniformGPU );
  43601. } else if ( type === 'texture3D' ) {
  43602. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  43603. bindings.push( uniformGPU );
  43604. } else if ( type === 'buffer' ) {
  43605. node.name = `NodeBuffer_${ node.id }`;
  43606. uniformNode.name = `buffer${ node.id }`;
  43607. const buffer = new NodeUniformBuffer( node, group );
  43608. buffer.name = node.name;
  43609. bindings.push( buffer );
  43610. uniformGPU = buffer;
  43611. } else {
  43612. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43613. let uniformsGroup = uniformsStage[ groupName ];
  43614. if ( uniformsGroup === undefined ) {
  43615. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  43616. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43617. uniformsStage[ groupName ] = uniformsGroup;
  43618. bindings.push( uniformsGroup );
  43619. }
  43620. uniformGPU = this.getNodeUniform( uniformNode, type );
  43621. uniformsGroup.addUniform( uniformGPU );
  43622. }
  43623. nodeData.uniformGPU = uniformGPU;
  43624. }
  43625. return uniformNode;
  43626. }
  43627. }
  43628. let _vector2 = null;
  43629. let _color4 = null;
  43630. /**
  43631. * Most of the rendering related logic is implemented in the
  43632. * {@link Renderer} module and related management components.
  43633. * Sometimes it is required though to execute commands which are
  43634. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  43635. * This abstract base class defines an interface that encapsulates
  43636. * all backend-related logic. Derived classes for each backend must
  43637. * implement the interface.
  43638. *
  43639. * @abstract
  43640. * @private
  43641. */
  43642. class Backend {
  43643. /**
  43644. * Constructs a new backend.
  43645. *
  43646. * @param {Object} parameters - An object holding parameters for the backend.
  43647. */
  43648. constructor( parameters = {} ) {
  43649. /**
  43650. * The parameters of the backend.
  43651. *
  43652. * @type {Object}
  43653. */
  43654. this.parameters = Object.assign( {}, parameters );
  43655. /**
  43656. * This weak map holds backend-specific data of objects
  43657. * like textures, attributes or render targets.
  43658. *
  43659. * @type {WeakMap<Object, Object>}
  43660. */
  43661. this.data = new WeakMap();
  43662. /**
  43663. * A reference to the renderer.
  43664. *
  43665. * @type {?Renderer}
  43666. * @default null
  43667. */
  43668. this.renderer = null;
  43669. /**
  43670. * A reference to the canvas element the renderer is drawing to.
  43671. *
  43672. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  43673. * @default null
  43674. */
  43675. this.domElement = null;
  43676. /**
  43677. * A reference to the timestamp query pool.
  43678. *
  43679. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  43680. */
  43681. this.timestampQueryPool = {
  43682. [ TimestampQuery.RENDER ]: null,
  43683. [ TimestampQuery.COMPUTE ]: null
  43684. };
  43685. /**
  43686. * Whether to track timestamps with a Timestamp Query API or not.
  43687. *
  43688. * @type {boolean}
  43689. * @default false
  43690. */
  43691. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43692. }
  43693. /**
  43694. * Initializes the backend so it is ready for usage. Concrete backends
  43695. * are supposed to implement their rendering context creation and related
  43696. * operations in this method.
  43697. *
  43698. * @async
  43699. * @param {Renderer} renderer - The renderer.
  43700. * @return {Promise} A Promise that resolves when the backend has been initialized.
  43701. */
  43702. async init( renderer ) {
  43703. this.renderer = renderer;
  43704. }
  43705. /**
  43706. * The coordinate system of the backend.
  43707. *
  43708. * @abstract
  43709. * @type {number}
  43710. * @readonly
  43711. */
  43712. get coordinateSystem() {}
  43713. // render context
  43714. /**
  43715. * This method is executed at the beginning of a render call and
  43716. * can be used by the backend to prepare the state for upcoming
  43717. * draw calls.
  43718. *
  43719. * @abstract
  43720. * @param {RenderContext} renderContext - The render context.
  43721. */
  43722. beginRender( /*renderContext*/ ) {}
  43723. /**
  43724. * This method is executed at the end of a render call and
  43725. * can be used by the backend to finalize work after draw
  43726. * calls.
  43727. *
  43728. * @abstract
  43729. * @param {RenderContext} renderContext - The render context.
  43730. */
  43731. finishRender( /*renderContext*/ ) {}
  43732. /**
  43733. * This method is executed at the beginning of a compute call and
  43734. * can be used by the backend to prepare the state for upcoming
  43735. * compute tasks.
  43736. *
  43737. * @abstract
  43738. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43739. */
  43740. beginCompute( /*computeGroup*/ ) {}
  43741. /**
  43742. * This method is executed at the end of a compute call and
  43743. * can be used by the backend to finalize work after compute
  43744. * tasks.
  43745. *
  43746. * @abstract
  43747. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43748. */
  43749. finishCompute( /*computeGroup*/ ) {}
  43750. // render object
  43751. /**
  43752. * Executes a draw command for the given render object.
  43753. *
  43754. * @abstract
  43755. * @param {RenderObject} renderObject - The render object to draw.
  43756. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43757. */
  43758. draw( /*renderObject, info*/ ) { }
  43759. // compute node
  43760. /**
  43761. * Executes a compute command for the given compute node.
  43762. *
  43763. * @abstract
  43764. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43765. * @param {Node} computeNode - The compute node.
  43766. * @param {Array<BindGroup>} bindings - The bindings.
  43767. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43768. */
  43769. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  43770. // program
  43771. /**
  43772. * Creates a shader program from the given programmable stage.
  43773. *
  43774. * @abstract
  43775. * @param {ProgrammableStage} program - The programmable stage.
  43776. */
  43777. createProgram( /*program*/ ) { }
  43778. /**
  43779. * Destroys the shader program of the given programmable stage.
  43780. *
  43781. * @abstract
  43782. * @param {ProgrammableStage} program - The programmable stage.
  43783. */
  43784. destroyProgram( /*program*/ ) { }
  43785. // bindings
  43786. /**
  43787. * Creates bindings from the given bind group definition.
  43788. *
  43789. * @abstract
  43790. * @param {BindGroup} bindGroup - The bind group.
  43791. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43792. * @param {number} cacheIndex - The cache index.
  43793. * @param {number} version - The version.
  43794. */
  43795. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43796. /**
  43797. * Updates the given bind group definition.
  43798. *
  43799. * @abstract
  43800. * @param {BindGroup} bindGroup - The bind group.
  43801. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43802. * @param {number} cacheIndex - The cache index.
  43803. * @param {number} version - The version.
  43804. */
  43805. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43806. /**
  43807. * Updates a buffer binding.
  43808. *
  43809. * @abstract
  43810. * @param {Buffer} binding - The buffer binding to update.
  43811. */
  43812. updateBinding( /*binding*/ ) { }
  43813. // pipeline
  43814. /**
  43815. * Creates a render pipeline for the given render object.
  43816. *
  43817. * @abstract
  43818. * @param {RenderObject} renderObject - The render object.
  43819. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43820. */
  43821. createRenderPipeline( /*renderObject, promises*/ ) { }
  43822. /**
  43823. * Creates a compute pipeline for the given compute node.
  43824. *
  43825. * @abstract
  43826. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43827. * @param {Array<BindGroup>} bindings - The bindings.
  43828. */
  43829. createComputePipeline( /*computePipeline, bindings*/ ) { }
  43830. // cache key
  43831. /**
  43832. * Returns `true` if the render pipeline requires an update.
  43833. *
  43834. * @abstract
  43835. * @param {RenderObject} renderObject - The render object.
  43836. * @return {boolean} Whether the render pipeline requires an update or not.
  43837. */
  43838. needsRenderUpdate( /*renderObject*/ ) { }
  43839. /**
  43840. * Returns a cache key that is used to identify render pipelines.
  43841. *
  43842. * @abstract
  43843. * @param {RenderObject} renderObject - The render object.
  43844. * @return {string} The cache key.
  43845. */
  43846. getRenderCacheKey( /*renderObject*/ ) { }
  43847. // node builder
  43848. /**
  43849. * Returns a node builder for the given render object.
  43850. *
  43851. * @abstract
  43852. * @param {RenderObject} renderObject - The render object.
  43853. * @param {Renderer} renderer - The renderer.
  43854. * @return {NodeBuilder} The node builder.
  43855. */
  43856. createNodeBuilder( /*renderObject, renderer*/ ) { }
  43857. // textures
  43858. /**
  43859. * Updates a GPU sampler for the given texture.
  43860. *
  43861. * @abstract
  43862. * @param {Texture} texture - The texture to update the sampler for.
  43863. * @return {string} The current sampler key.
  43864. */
  43865. updateSampler( /*texture*/ ) { }
  43866. /**
  43867. * Creates a default texture for the given texture that can be used
  43868. * as a placeholder until the actual texture is ready for usage.
  43869. *
  43870. * @abstract
  43871. * @param {Texture} texture - The texture to create a default texture for.
  43872. */
  43873. createDefaultTexture( /*texture*/ ) { }
  43874. /**
  43875. * Defines a texture on the GPU for the given texture object.
  43876. *
  43877. * @abstract
  43878. * @param {Texture} texture - The texture.
  43879. * @param {Object} [options={}] - Optional configuration parameter.
  43880. */
  43881. createTexture( /*texture, options={}*/ ) { }
  43882. /**
  43883. * Uploads the updated texture data to the GPU.
  43884. *
  43885. * @abstract
  43886. * @param {Texture} texture - The texture.
  43887. * @param {Object} [options={}] - Optional configuration parameter.
  43888. */
  43889. updateTexture( /*texture, options = {}*/ ) { }
  43890. /**
  43891. * Generates mipmaps for the given texture.
  43892. *
  43893. * @abstract
  43894. * @param {Texture} texture - The texture.
  43895. */
  43896. generateMipmaps( /*texture*/ ) { }
  43897. /**
  43898. * Destroys the GPU data for the given texture object.
  43899. *
  43900. * @abstract
  43901. * @param {Texture} texture - The texture.
  43902. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  43903. */
  43904. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  43905. /**
  43906. * Returns texture data as a typed array.
  43907. *
  43908. * @abstract
  43909. * @async
  43910. * @param {Texture} texture - The texture to copy.
  43911. * @param {number} x - The x coordinate of the copy origin.
  43912. * @param {number} y - The y coordinate of the copy origin.
  43913. * @param {number} width - The width of the copy.
  43914. * @param {number} height - The height of the copy.
  43915. * @param {number} faceIndex - The face index.
  43916. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43917. */
  43918. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  43919. /**
  43920. * Copies data of the given source texture to the given destination texture.
  43921. *
  43922. * @abstract
  43923. * @param {Texture} srcTexture - The source texture.
  43924. * @param {Texture} dstTexture - The destination texture.
  43925. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43926. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43927. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43928. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43929. */
  43930. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  43931. /**
  43932. * Copies the current bound framebuffer to the given texture.
  43933. *
  43934. * @abstract
  43935. * @param {Texture} texture - The destination texture.
  43936. * @param {RenderContext} renderContext - The render context.
  43937. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43938. */
  43939. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  43940. // attributes
  43941. /**
  43942. * Creates the GPU buffer of a shader attribute.
  43943. *
  43944. * @abstract
  43945. * @param {BufferAttribute} attribute - The buffer attribute.
  43946. */
  43947. createAttribute( /*attribute*/ ) { }
  43948. /**
  43949. * Creates the GPU buffer of an indexed shader attribute.
  43950. *
  43951. * @abstract
  43952. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43953. */
  43954. createIndexAttribute( /*attribute*/ ) { }
  43955. /**
  43956. * Creates the GPU buffer of a storage attribute.
  43957. *
  43958. * @abstract
  43959. * @param {BufferAttribute} attribute - The buffer attribute.
  43960. */
  43961. createStorageAttribute( /*attribute*/ ) { }
  43962. /**
  43963. * Updates the GPU buffer of a shader attribute.
  43964. *
  43965. * @abstract
  43966. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43967. */
  43968. updateAttribute( /*attribute*/ ) { }
  43969. /**
  43970. * Destroys the GPU buffer of a shader attribute.
  43971. *
  43972. * @abstract
  43973. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43974. */
  43975. destroyAttribute( /*attribute*/ ) { }
  43976. // canvas
  43977. /**
  43978. * Returns the backend's rendering context.
  43979. *
  43980. * @abstract
  43981. * @return {Object} The rendering context.
  43982. */
  43983. getContext() { }
  43984. /**
  43985. * Backends can use this method if they have to run
  43986. * logic when the renderer gets resized.
  43987. *
  43988. * @abstract
  43989. */
  43990. updateSize() { }
  43991. /**
  43992. * Updates the viewport with the values from the given render context.
  43993. *
  43994. * @abstract
  43995. * @param {RenderContext} renderContext - The render context.
  43996. */
  43997. updateViewport( /*renderContext*/ ) {}
  43998. // utils
  43999. /**
  44000. * Updates a unique identifier for the given render context that can be used
  44001. * to allocate resources like occlusion queries or timestamp queries.
  44002. *
  44003. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  44004. */
  44005. updateTimeStampUID( abstractRenderContext ) {
  44006. const contextData = this.get( abstractRenderContext );
  44007. const frame = this.renderer.info.frame;
  44008. let prefix;
  44009. if ( abstractRenderContext.isComputeNode === true ) {
  44010. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  44011. } else {
  44012. prefix = 'r:' + this.renderer.info.render.frameCalls;
  44013. }
  44014. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  44015. }
  44016. /**
  44017. * Returns a unique identifier for the given render context that can be used
  44018. * to allocate resources like occlusion queries or timestamp queries.
  44019. *
  44020. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  44021. * @return {string} The unique identifier.
  44022. */
  44023. getTimestampUID( abstractRenderContext ) {
  44024. return this.get( abstractRenderContext ).timestampUID;
  44025. }
  44026. /**
  44027. * Returns all timestamp frames for the given type.
  44028. *
  44029. * @param {string} type - The type of the time stamp.
  44030. * @return {Array<number>} The timestamp frames.
  44031. */
  44032. getTimestampFrames( type ) {
  44033. const queryPool = this.timestampQueryPool[ type ];
  44034. return queryPool ? queryPool.getTimestampFrames() : [];
  44035. }
  44036. /**
  44037. * Returns the query pool for the given uid.
  44038. *
  44039. * @param {string} uid - The unique identifier.
  44040. * @return {TimestampQueryPool} The query pool.
  44041. */
  44042. _getQueryPool( uid ) {
  44043. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  44044. const queryPool = this.timestampQueryPool[ type ];
  44045. return queryPool;
  44046. }
  44047. /**
  44048. * Returns the timestamp for the given uid.
  44049. *
  44050. * @param {string} uid - The unique identifier.
  44051. * @return {number} The timestamp.
  44052. */
  44053. getTimestamp( uid ) {
  44054. const queryPool = this._getQueryPool( uid );
  44055. return queryPool.getTimestamp( uid );
  44056. }
  44057. /**
  44058. * Returns `true` if a timestamp for the given uid is available.
  44059. *
  44060. * @param {string} uid - The unique identifier.
  44061. * @return {boolean} Whether the timestamp is available or not.
  44062. */
  44063. hasTimestamp( uid ) {
  44064. const queryPool = this._getQueryPool( uid );
  44065. return queryPool.hasTimestamp( uid );
  44066. }
  44067. /**
  44068. * Returns `true` if the given 3D object is fully occluded by other
  44069. * 3D objects in the scene. Backends must implement this method by using
  44070. * a Occlusion Query API.
  44071. *
  44072. * @abstract
  44073. * @param {RenderContext} renderContext - The render context.
  44074. * @param {Object3D} object - The 3D object to test.
  44075. * @return {boolean} Whether the 3D object is fully occluded or not.
  44076. */
  44077. isOccluded( /*renderContext, object*/ ) {}
  44078. /**
  44079. * Resolves the time stamp for the given render context and type.
  44080. *
  44081. * @async
  44082. * @abstract
  44083. * @param {string} [type='render'] - The type of the time stamp.
  44084. * @return {Promise<number>} A Promise that resolves with the time stamp.
  44085. */
  44086. async resolveTimestampsAsync( type = 'render' ) {
  44087. if ( ! this.trackTimestamp ) {
  44088. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  44089. return;
  44090. }
  44091. const queryPool = this.timestampQueryPool[ type ];
  44092. if ( ! queryPool ) {
  44093. return;
  44094. }
  44095. const duration = await queryPool.resolveQueriesAsync();
  44096. this.renderer.info[ type ].timestamp = duration;
  44097. return duration;
  44098. }
  44099. /**
  44100. * This method performs a readback operation by moving buffer data from
  44101. * a storage buffer attribute from the GPU to the CPU.
  44102. *
  44103. * @async
  44104. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44105. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44106. */
  44107. async getArrayBufferAsync( /* attribute */ ) {}
  44108. /**
  44109. * Checks if the given feature is supported by the backend.
  44110. *
  44111. * @async
  44112. * @abstract
  44113. * @param {string} name - The feature's name.
  44114. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44115. */
  44116. async hasFeatureAsync( /*name*/ ) { }
  44117. /**
  44118. * Checks if the given feature is supported by the backend.
  44119. *
  44120. * @abstract
  44121. * @param {string} name - The feature's name.
  44122. * @return {boolean} Whether the feature is supported or not.
  44123. */
  44124. hasFeature( /*name*/ ) {}
  44125. /**
  44126. * Returns the maximum anisotropy texture filtering value.
  44127. *
  44128. * @abstract
  44129. * @return {number} The maximum anisotropy texture filtering value.
  44130. */
  44131. getMaxAnisotropy() {}
  44132. /**
  44133. * Returns the drawing buffer size.
  44134. *
  44135. * @return {Vector2} The drawing buffer size.
  44136. */
  44137. getDrawingBufferSize() {
  44138. _vector2 = _vector2 || new Vector2();
  44139. return this.renderer.getDrawingBufferSize( _vector2 );
  44140. }
  44141. /**
  44142. * Defines the scissor test.
  44143. *
  44144. * @abstract
  44145. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44146. */
  44147. setScissorTest( /*boolean*/ ) { }
  44148. /**
  44149. * Returns the clear color and alpha into a single
  44150. * color object.
  44151. *
  44152. * @return {Color4} The clear color.
  44153. */
  44154. getClearColor() {
  44155. const renderer = this.renderer;
  44156. _color4 = _color4 || new Color4();
  44157. renderer.getClearColor( _color4 );
  44158. _color4.getRGB( _color4 );
  44159. return _color4;
  44160. }
  44161. /**
  44162. * Returns the DOM element. If no DOM element exists, the backend
  44163. * creates a new one.
  44164. *
  44165. * @return {HTMLCanvasElement} The DOM element.
  44166. */
  44167. getDomElement() {
  44168. let domElement = this.domElement;
  44169. if ( domElement === null ) {
  44170. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  44171. // OffscreenCanvas does not have setAttribute, see #22811
  44172. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  44173. this.domElement = domElement;
  44174. }
  44175. return domElement;
  44176. }
  44177. /**
  44178. * Sets a dictionary for the given object into the
  44179. * internal data structure.
  44180. *
  44181. * @param {Object} object - The object.
  44182. * @param {Object} value - The dictionary to set.
  44183. */
  44184. set( object, value ) {
  44185. this.data.set( object, value );
  44186. }
  44187. /**
  44188. * Returns the dictionary for the given object.
  44189. *
  44190. * @param {Object} object - The object.
  44191. * @return {Object} The object's dictionary.
  44192. */
  44193. get( object ) {
  44194. let map = this.data.get( object );
  44195. if ( map === undefined ) {
  44196. map = {};
  44197. this.data.set( object, map );
  44198. }
  44199. return map;
  44200. }
  44201. /**
  44202. * Checks if the given object has a dictionary
  44203. * with data defined.
  44204. *
  44205. * @param {Object} object - The object.
  44206. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  44207. */
  44208. has( object ) {
  44209. return this.data.has( object );
  44210. }
  44211. /**
  44212. * Deletes an object from the internal data structure.
  44213. *
  44214. * @param {Object} object - The object to delete.
  44215. */
  44216. delete( object ) {
  44217. this.data.delete( object );
  44218. }
  44219. /**
  44220. * Frees internal resources.
  44221. *
  44222. * @abstract
  44223. */
  44224. dispose() { }
  44225. }
  44226. let _id$1 = 0;
  44227. /**
  44228. * This module is internally used in context of compute shaders.
  44229. * This type of shader is not natively supported in WebGL 2 and
  44230. * thus implemented via Transform Feedback. `DualAttributeData`
  44231. * manages the related data.
  44232. *
  44233. * @private
  44234. */
  44235. class DualAttributeData {
  44236. constructor( attributeData, dualBuffer ) {
  44237. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  44238. this.type = attributeData.type;
  44239. this.bufferType = attributeData.bufferType;
  44240. this.pbo = attributeData.pbo;
  44241. this.byteLength = attributeData.byteLength;
  44242. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  44243. this.version = attributeData.version;
  44244. this.isInteger = attributeData.isInteger;
  44245. this.activeBufferIndex = 0;
  44246. this.baseId = attributeData.id;
  44247. }
  44248. get id() {
  44249. return `${ this.baseId }|${ this.activeBufferIndex }`;
  44250. }
  44251. get bufferGPU() {
  44252. return this.buffers[ this.activeBufferIndex ];
  44253. }
  44254. get transformBuffer() {
  44255. return this.buffers[ this.activeBufferIndex ^ 1 ];
  44256. }
  44257. switchBuffers() {
  44258. this.activeBufferIndex ^= 1;
  44259. }
  44260. }
  44261. /**
  44262. * A WebGL 2 backend utility module for managing shader attributes.
  44263. *
  44264. * @private
  44265. */
  44266. class WebGLAttributeUtils {
  44267. /**
  44268. * Constructs a new utility object.
  44269. *
  44270. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44271. */
  44272. constructor( backend ) {
  44273. /**
  44274. * A reference to the WebGL 2 backend.
  44275. *
  44276. * @type {WebGLBackend}
  44277. */
  44278. this.backend = backend;
  44279. }
  44280. /**
  44281. * Creates the GPU buffer for the given buffer attribute.
  44282. *
  44283. * @param {BufferAttribute} attribute - The buffer attribute.
  44284. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44285. */
  44286. createAttribute( attribute, bufferType ) {
  44287. const backend = this.backend;
  44288. const { gl } = backend;
  44289. const array = attribute.array;
  44290. const usage = attribute.usage || gl.STATIC_DRAW;
  44291. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44292. const bufferData = backend.get( bufferAttribute );
  44293. let bufferGPU = bufferData.bufferGPU;
  44294. if ( bufferGPU === undefined ) {
  44295. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  44296. bufferData.bufferGPU = bufferGPU;
  44297. bufferData.bufferType = bufferType;
  44298. bufferData.version = bufferAttribute.version;
  44299. }
  44300. //attribute.onUploadCallback();
  44301. let type;
  44302. if ( array instanceof Float32Array ) {
  44303. type = gl.FLOAT;
  44304. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  44305. type = gl.HALF_FLOAT;
  44306. } else if ( array instanceof Uint16Array ) {
  44307. if ( attribute.isFloat16BufferAttribute ) {
  44308. type = gl.HALF_FLOAT;
  44309. } else {
  44310. type = gl.UNSIGNED_SHORT;
  44311. }
  44312. } else if ( array instanceof Int16Array ) {
  44313. type = gl.SHORT;
  44314. } else if ( array instanceof Uint32Array ) {
  44315. type = gl.UNSIGNED_INT;
  44316. } else if ( array instanceof Int32Array ) {
  44317. type = gl.INT;
  44318. } else if ( array instanceof Int8Array ) {
  44319. type = gl.BYTE;
  44320. } else if ( array instanceof Uint8Array ) {
  44321. type = gl.UNSIGNED_BYTE;
  44322. } else if ( array instanceof Uint8ClampedArray ) {
  44323. type = gl.UNSIGNED_BYTE;
  44324. } else {
  44325. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  44326. }
  44327. let attributeData = {
  44328. bufferGPU,
  44329. bufferType,
  44330. type,
  44331. byteLength: array.byteLength,
  44332. bytesPerElement: array.BYTES_PER_ELEMENT,
  44333. version: attribute.version,
  44334. pbo: attribute.pbo,
  44335. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  44336. id: _id$1 ++
  44337. };
  44338. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  44339. // create buffer for transform feedback use
  44340. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  44341. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  44342. }
  44343. backend.set( attribute, attributeData );
  44344. }
  44345. /**
  44346. * Updates the GPU buffer of the given buffer attribute.
  44347. *
  44348. * @param {BufferAttribute} attribute - The buffer attribute.
  44349. */
  44350. updateAttribute( attribute ) {
  44351. const backend = this.backend;
  44352. const { gl } = backend;
  44353. const array = attribute.array;
  44354. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44355. const bufferData = backend.get( bufferAttribute );
  44356. const bufferType = bufferData.bufferType;
  44357. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  44358. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  44359. if ( updateRanges.length === 0 ) {
  44360. // Not using update ranges
  44361. gl.bufferSubData( bufferType, 0, array );
  44362. } else {
  44363. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44364. const range = updateRanges[ i ];
  44365. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  44366. array, range.start, range.count );
  44367. }
  44368. bufferAttribute.clearUpdateRanges();
  44369. }
  44370. gl.bindBuffer( bufferType, null );
  44371. bufferData.version = bufferAttribute.version;
  44372. }
  44373. /**
  44374. * Destroys the GPU buffer of the given buffer attribute.
  44375. *
  44376. * @param {BufferAttribute} attribute - The buffer attribute.
  44377. */
  44378. destroyAttribute( attribute ) {
  44379. const backend = this.backend;
  44380. const { gl } = backend;
  44381. if ( attribute.isInterleavedBufferAttribute ) {
  44382. backend.delete( attribute.data );
  44383. }
  44384. const attributeData = backend.get( attribute );
  44385. gl.deleteBuffer( attributeData.bufferGPU );
  44386. backend.delete( attribute );
  44387. }
  44388. /**
  44389. * This method performs a readback operation by moving buffer data from
  44390. * a storage buffer attribute from the GPU to the CPU.
  44391. *
  44392. * @async
  44393. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44394. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44395. */
  44396. async getArrayBufferAsync( attribute ) {
  44397. const backend = this.backend;
  44398. const { gl } = backend;
  44399. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44400. const { bufferGPU } = backend.get( bufferAttribute );
  44401. const array = attribute.array;
  44402. const byteLength = array.byteLength;
  44403. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  44404. const writeBuffer = gl.createBuffer();
  44405. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44406. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  44407. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  44408. await backend.utils._clientWaitAsync();
  44409. const dstBuffer = new attribute.array.constructor( array.length );
  44410. // Ensure the buffer is bound before reading
  44411. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44412. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  44413. gl.deleteBuffer( writeBuffer );
  44414. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  44415. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  44416. return dstBuffer.buffer;
  44417. }
  44418. /**
  44419. * Creates a WebGL buffer with the given data.
  44420. *
  44421. * @private
  44422. * @param {WebGL2RenderingContext} gl - The rendering context.
  44423. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44424. * @param {TypedArray} array - The array of the buffer attribute.
  44425. * @param {GLenum} usage - The usage.
  44426. * @return {WebGLBuffer} The WebGL buffer.
  44427. */
  44428. _createBuffer( gl, bufferType, array, usage ) {
  44429. const bufferGPU = gl.createBuffer();
  44430. gl.bindBuffer( bufferType, bufferGPU );
  44431. gl.bufferData( bufferType, array, usage );
  44432. gl.bindBuffer( bufferType, null );
  44433. return bufferGPU;
  44434. }
  44435. }
  44436. let equationToGL, factorToGL;
  44437. /**
  44438. * A WebGL 2 backend utility module for managing the WebGL state.
  44439. *
  44440. * The major goal of this module is to reduce the number of state changes
  44441. * by caching the WEbGL state with a series of variables. In this way, the
  44442. * renderer only executes state change commands when necessary which
  44443. * improves the overall performance.
  44444. *
  44445. * @private
  44446. */
  44447. class WebGLState {
  44448. /**
  44449. * Constructs a new utility object.
  44450. *
  44451. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44452. */
  44453. constructor( backend ) {
  44454. /**
  44455. * A reference to the WebGL 2 backend.
  44456. *
  44457. * @type {WebGLBackend}
  44458. */
  44459. this.backend = backend;
  44460. /**
  44461. * A reference to the rendering context.
  44462. *
  44463. * @type {WebGL2RenderingContext}
  44464. */
  44465. this.gl = this.backend.gl;
  44466. // Below properties are intended to cache
  44467. // the WebGL state and are not explicitly
  44468. // documented for convenience reasons.
  44469. this.enabled = {};
  44470. this.currentFlipSided = null;
  44471. this.currentCullFace = null;
  44472. this.currentProgram = null;
  44473. this.currentBlendingEnabled = false;
  44474. this.currentBlending = null;
  44475. this.currentBlendSrc = null;
  44476. this.currentBlendDst = null;
  44477. this.currentBlendSrcAlpha = null;
  44478. this.currentBlendDstAlpha = null;
  44479. this.currentPremultipledAlpha = null;
  44480. this.currentPolygonOffsetFactor = null;
  44481. this.currentPolygonOffsetUnits = null;
  44482. this.currentColorMask = null;
  44483. this.currentDepthFunc = null;
  44484. this.currentDepthMask = null;
  44485. this.currentStencilFunc = null;
  44486. this.currentStencilRef = null;
  44487. this.currentStencilFuncMask = null;
  44488. this.currentStencilFail = null;
  44489. this.currentStencilZFail = null;
  44490. this.currentStencilZPass = null;
  44491. this.currentStencilMask = null;
  44492. this.currentLineWidth = null;
  44493. this.currentClippingPlanes = 0;
  44494. this.currentVAO = null;
  44495. this.currentIndex = null;
  44496. this.currentBoundFramebuffers = {};
  44497. this.currentDrawbuffers = new WeakMap();
  44498. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  44499. this.currentTextureSlot = null;
  44500. this.currentBoundTextures = {};
  44501. this.currentBoundBufferBases = {};
  44502. this._init();
  44503. }
  44504. /**
  44505. * Inits the state of the utility.
  44506. *
  44507. * @private
  44508. */
  44509. _init() {
  44510. const gl = this.gl;
  44511. // Store only WebGL constants here.
  44512. equationToGL = {
  44513. [ AddEquation ]: gl.FUNC_ADD,
  44514. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  44515. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  44516. };
  44517. factorToGL = {
  44518. [ ZeroFactor ]: gl.ZERO,
  44519. [ OneFactor ]: gl.ONE,
  44520. [ SrcColorFactor ]: gl.SRC_COLOR,
  44521. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  44522. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  44523. [ DstColorFactor ]: gl.DST_COLOR,
  44524. [ DstAlphaFactor ]: gl.DST_ALPHA,
  44525. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  44526. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  44527. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  44528. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  44529. };
  44530. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  44531. const viewportParam = gl.getParameter( gl.VIEWPORT );
  44532. this.currentScissor = new Vector4().fromArray( scissorParam );
  44533. this.currentViewport = new Vector4().fromArray( viewportParam );
  44534. this._tempVec4 = new Vector4();
  44535. }
  44536. /**
  44537. * Enables the given WebGL capability.
  44538. *
  44539. * This method caches the capability state so
  44540. * `gl.enable()` is only called when necessary.
  44541. *
  44542. * @param {GLenum} id - The capability to enable.
  44543. */
  44544. enable( id ) {
  44545. const { enabled } = this;
  44546. if ( enabled[ id ] !== true ) {
  44547. this.gl.enable( id );
  44548. enabled[ id ] = true;
  44549. }
  44550. }
  44551. /**
  44552. * Disables the given WebGL capability.
  44553. *
  44554. * This method caches the capability state so
  44555. * `gl.disable()` is only called when necessary.
  44556. *
  44557. * @param {GLenum} id - The capability to enable.
  44558. */
  44559. disable( id ) {
  44560. const { enabled } = this;
  44561. if ( enabled[ id ] !== false ) {
  44562. this.gl.disable( id );
  44563. enabled[ id ] = false;
  44564. }
  44565. }
  44566. /**
  44567. * Specifies whether polygons are front- or back-facing
  44568. * by setting the winding orientation.
  44569. *
  44570. * This method caches the state so `gl.frontFace()` is only
  44571. * called when necessary.
  44572. *
  44573. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  44574. */
  44575. setFlipSided( flipSided ) {
  44576. if ( this.currentFlipSided !== flipSided ) {
  44577. const { gl } = this;
  44578. if ( flipSided ) {
  44579. gl.frontFace( gl.CW );
  44580. } else {
  44581. gl.frontFace( gl.CCW );
  44582. }
  44583. this.currentFlipSided = flipSided;
  44584. }
  44585. }
  44586. /**
  44587. * Specifies whether or not front- and/or back-facing
  44588. * polygons can be culled.
  44589. *
  44590. * This method caches the state so `gl.cullFace()` is only
  44591. * called when necessary.
  44592. *
  44593. * @param {number} cullFace - Defines which polygons are candidates for culling.
  44594. */
  44595. setCullFace( cullFace ) {
  44596. const { gl } = this;
  44597. if ( cullFace !== CullFaceNone ) {
  44598. this.enable( gl.CULL_FACE );
  44599. if ( cullFace !== this.currentCullFace ) {
  44600. if ( cullFace === CullFaceBack ) {
  44601. gl.cullFace( gl.BACK );
  44602. } else if ( cullFace === CullFaceFront ) {
  44603. gl.cullFace( gl.FRONT );
  44604. } else {
  44605. gl.cullFace( gl.FRONT_AND_BACK );
  44606. }
  44607. }
  44608. } else {
  44609. this.disable( gl.CULL_FACE );
  44610. }
  44611. this.currentCullFace = cullFace;
  44612. }
  44613. /**
  44614. * Specifies the width of line primitives.
  44615. *
  44616. * This method caches the state so `gl.lineWidth()` is only
  44617. * called when necessary.
  44618. *
  44619. * @param {number} width - The line width.
  44620. */
  44621. setLineWidth( width ) {
  44622. const { currentLineWidth, gl } = this;
  44623. if ( width !== currentLineWidth ) {
  44624. gl.lineWidth( width );
  44625. this.currentLineWidth = width;
  44626. }
  44627. }
  44628. /**
  44629. * Defines the blending.
  44630. *
  44631. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  44632. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  44633. *
  44634. * @param {number} blending - The blending type.
  44635. * @param {number} blendEquation - The blending equation.
  44636. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  44637. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  44638. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  44639. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  44640. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  44641. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  44642. */
  44643. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  44644. const { gl } = this;
  44645. if ( blending === NoBlending ) {
  44646. if ( this.currentBlendingEnabled === true ) {
  44647. this.disable( gl.BLEND );
  44648. this.currentBlendingEnabled = false;
  44649. }
  44650. return;
  44651. }
  44652. if ( this.currentBlendingEnabled === false ) {
  44653. this.enable( gl.BLEND );
  44654. this.currentBlendingEnabled = true;
  44655. }
  44656. if ( blending !== CustomBlending ) {
  44657. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  44658. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  44659. gl.blendEquation( gl.FUNC_ADD );
  44660. this.currentBlendEquation = AddEquation;
  44661. this.currentBlendEquationAlpha = AddEquation;
  44662. }
  44663. if ( premultipliedAlpha ) {
  44664. switch ( blending ) {
  44665. case NormalBlending:
  44666. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44667. break;
  44668. case AdditiveBlending:
  44669. gl.blendFunc( gl.ONE, gl.ONE );
  44670. break;
  44671. case SubtractiveBlending:
  44672. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  44673. break;
  44674. case MultiplyBlending:
  44675. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  44676. break;
  44677. default:
  44678. error( 'WebGLState: Invalid blending: ', blending );
  44679. break;
  44680. }
  44681. } else {
  44682. switch ( blending ) {
  44683. case NormalBlending:
  44684. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44685. break;
  44686. case AdditiveBlending:
  44687. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  44688. break;
  44689. case SubtractiveBlending:
  44690. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  44691. break;
  44692. case MultiplyBlending:
  44693. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  44694. break;
  44695. default:
  44696. error( 'WebGLState: Invalid blending: ', blending );
  44697. break;
  44698. }
  44699. }
  44700. this.currentBlendSrc = null;
  44701. this.currentBlendDst = null;
  44702. this.currentBlendSrcAlpha = null;
  44703. this.currentBlendDstAlpha = null;
  44704. this.currentBlending = blending;
  44705. this.currentPremultipledAlpha = premultipliedAlpha;
  44706. }
  44707. return;
  44708. }
  44709. // custom blending
  44710. blendEquationAlpha = blendEquationAlpha || blendEquation;
  44711. blendSrcAlpha = blendSrcAlpha || blendSrc;
  44712. blendDstAlpha = blendDstAlpha || blendDst;
  44713. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  44714. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  44715. this.currentBlendEquation = blendEquation;
  44716. this.currentBlendEquationAlpha = blendEquationAlpha;
  44717. }
  44718. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  44719. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  44720. this.currentBlendSrc = blendSrc;
  44721. this.currentBlendDst = blendDst;
  44722. this.currentBlendSrcAlpha = blendSrcAlpha;
  44723. this.currentBlendDstAlpha = blendDstAlpha;
  44724. }
  44725. this.currentBlending = blending;
  44726. this.currentPremultipledAlpha = false;
  44727. }
  44728. /**
  44729. * Specifies whether colors can be written when rendering
  44730. * into a framebuffer or not.
  44731. *
  44732. * This method caches the state so `gl.colorMask()` is only
  44733. * called when necessary.
  44734. *
  44735. * @param {boolean} colorMask - The color mask.
  44736. */
  44737. setColorMask( colorMask ) {
  44738. if ( this.currentColorMask !== colorMask ) {
  44739. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  44740. this.currentColorMask = colorMask;
  44741. }
  44742. }
  44743. /**
  44744. * Specifies whether the depth test is enabled or not.
  44745. *
  44746. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  44747. */
  44748. setDepthTest( depthTest ) {
  44749. const { gl } = this;
  44750. if ( depthTest ) {
  44751. this.enable( gl.DEPTH_TEST );
  44752. } else {
  44753. this.disable( gl.DEPTH_TEST );
  44754. }
  44755. }
  44756. /**
  44757. * Specifies whether depth values can be written when rendering
  44758. * into a framebuffer or not.
  44759. *
  44760. * This method caches the state so `gl.depthMask()` is only
  44761. * called when necessary.
  44762. *
  44763. * @param {boolean} depthMask - The depth mask.
  44764. */
  44765. setDepthMask( depthMask ) {
  44766. if ( this.currentDepthMask !== depthMask ) {
  44767. this.gl.depthMask( depthMask );
  44768. this.currentDepthMask = depthMask;
  44769. }
  44770. }
  44771. /**
  44772. * Specifies the depth compare function.
  44773. *
  44774. * This method caches the state so `gl.depthFunc()` is only
  44775. * called when necessary.
  44776. *
  44777. * @param {number} depthFunc - The depth compare function.
  44778. */
  44779. setDepthFunc( depthFunc ) {
  44780. if ( this.currentDepthFunc !== depthFunc ) {
  44781. const { gl } = this;
  44782. switch ( depthFunc ) {
  44783. case NeverDepth:
  44784. gl.depthFunc( gl.NEVER );
  44785. break;
  44786. case AlwaysDepth:
  44787. gl.depthFunc( gl.ALWAYS );
  44788. break;
  44789. case LessDepth:
  44790. gl.depthFunc( gl.LESS );
  44791. break;
  44792. case LessEqualDepth:
  44793. gl.depthFunc( gl.LEQUAL );
  44794. break;
  44795. case EqualDepth:
  44796. gl.depthFunc( gl.EQUAL );
  44797. break;
  44798. case GreaterEqualDepth:
  44799. gl.depthFunc( gl.GEQUAL );
  44800. break;
  44801. case GreaterDepth:
  44802. gl.depthFunc( gl.GREATER );
  44803. break;
  44804. case NotEqualDepth:
  44805. gl.depthFunc( gl.NOTEQUAL );
  44806. break;
  44807. default:
  44808. gl.depthFunc( gl.LEQUAL );
  44809. }
  44810. this.currentDepthFunc = depthFunc;
  44811. }
  44812. }
  44813. /**
  44814. * Specifies the scissor box.
  44815. *
  44816. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44817. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44818. * @param {number} width - The width of the viewport.
  44819. * @param {number} height - The height of the viewport.
  44820. *
  44821. */
  44822. scissor( x, y, width, height ) {
  44823. const scissor = this._tempVec4.set( x, y, width, height );
  44824. if ( this.currentScissor.equals( scissor ) === false ) {
  44825. const { gl } = this;
  44826. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  44827. this.currentScissor.copy( scissor );
  44828. }
  44829. }
  44830. /**
  44831. * Specifies the viewport.
  44832. *
  44833. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44834. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44835. * @param {number} width - The width of the viewport.
  44836. * @param {number} height - The height of the viewport.
  44837. *
  44838. */
  44839. viewport( x, y, width, height ) {
  44840. const viewport = this._tempVec4.set( x, y, width, height );
  44841. if ( this.currentViewport.equals( viewport ) === false ) {
  44842. const { gl } = this;
  44843. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  44844. this.currentViewport.copy( viewport );
  44845. }
  44846. }
  44847. /**
  44848. * Defines the scissor test.
  44849. *
  44850. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44851. */
  44852. setScissorTest( boolean ) {
  44853. const gl = this.gl;
  44854. if ( boolean ) {
  44855. gl.enable( gl.SCISSOR_TEST );
  44856. } else {
  44857. gl.disable( gl.SCISSOR_TEST );
  44858. }
  44859. }
  44860. /**
  44861. * Specifies whether the stencil test is enabled or not.
  44862. *
  44863. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  44864. */
  44865. setStencilTest( stencilTest ) {
  44866. const { gl } = this;
  44867. if ( stencilTest ) {
  44868. this.enable( gl.STENCIL_TEST );
  44869. } else {
  44870. this.disable( gl.STENCIL_TEST );
  44871. }
  44872. }
  44873. /**
  44874. * Specifies whether stencil values can be written when rendering
  44875. * into a framebuffer or not.
  44876. *
  44877. * This method caches the state so `gl.stencilMask()` is only
  44878. * called when necessary.
  44879. *
  44880. * @param {boolean} stencilMask - The stencil mask.
  44881. */
  44882. setStencilMask( stencilMask ) {
  44883. if ( this.currentStencilMask !== stencilMask ) {
  44884. this.gl.stencilMask( stencilMask );
  44885. this.currentStencilMask = stencilMask;
  44886. }
  44887. }
  44888. /**
  44889. * Specifies whether the stencil test functions.
  44890. *
  44891. * This method caches the state so `gl.stencilFunc()` is only
  44892. * called when necessary.
  44893. *
  44894. * @param {number} stencilFunc - The stencil compare function.
  44895. * @param {number} stencilRef - The reference value for the stencil test.
  44896. * @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.
  44897. */
  44898. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  44899. if ( this.currentStencilFunc !== stencilFunc ||
  44900. this.currentStencilRef !== stencilRef ||
  44901. this.currentStencilFuncMask !== stencilMask ) {
  44902. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  44903. this.currentStencilFunc = stencilFunc;
  44904. this.currentStencilRef = stencilRef;
  44905. this.currentStencilFuncMask = stencilMask;
  44906. }
  44907. }
  44908. /**
  44909. * Specifies whether the stencil test operation.
  44910. *
  44911. * This method caches the state so `gl.stencilOp()` is only
  44912. * called when necessary.
  44913. *
  44914. * @param {number} stencilFail - The function to use when the stencil test fails.
  44915. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  44916. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  44917. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  44918. */
  44919. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  44920. if ( this.currentStencilFail !== stencilFail ||
  44921. this.currentStencilZFail !== stencilZFail ||
  44922. this.currentStencilZPass !== stencilZPass ) {
  44923. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  44924. this.currentStencilFail = stencilFail;
  44925. this.currentStencilZFail = stencilZFail;
  44926. this.currentStencilZPass = stencilZPass;
  44927. }
  44928. }
  44929. /**
  44930. * Configures the WebGL state for the given material.
  44931. *
  44932. * @param {Material} material - The material to configure the state for.
  44933. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  44934. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  44935. */
  44936. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  44937. const { gl } = this;
  44938. material.side === DoubleSide
  44939. ? this.disable( gl.CULL_FACE )
  44940. : this.enable( gl.CULL_FACE );
  44941. let flipSided = ( material.side === BackSide );
  44942. if ( frontFaceCW ) flipSided = ! flipSided;
  44943. this.setFlipSided( flipSided );
  44944. ( material.blending === NormalBlending && material.transparent === false )
  44945. ? this.setBlending( NoBlending )
  44946. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  44947. this.setDepthFunc( material.depthFunc );
  44948. this.setDepthTest( material.depthTest );
  44949. this.setDepthMask( material.depthWrite );
  44950. this.setColorMask( material.colorWrite );
  44951. const stencilWrite = material.stencilWrite;
  44952. this.setStencilTest( stencilWrite );
  44953. if ( stencilWrite ) {
  44954. this.setStencilMask( material.stencilWriteMask );
  44955. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  44956. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  44957. }
  44958. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  44959. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  44960. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  44961. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  44962. if ( hardwareClippingPlanes > 0 ) {
  44963. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  44964. const CLIP_DISTANCE0_WEBGL = 0x3000;
  44965. for ( let i = 0; i < 8; i ++ ) {
  44966. if ( i < hardwareClippingPlanes ) {
  44967. this.enable( CLIP_DISTANCE0_WEBGL + i );
  44968. } else {
  44969. this.disable( CLIP_DISTANCE0_WEBGL + i );
  44970. }
  44971. }
  44972. }
  44973. }
  44974. }
  44975. /**
  44976. * Specifies the polygon offset.
  44977. *
  44978. * This method caches the state so `gl.polygonOffset()` is only
  44979. * called when necessary.
  44980. *
  44981. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  44982. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  44983. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  44984. */
  44985. setPolygonOffset( polygonOffset, factor, units ) {
  44986. const { gl } = this;
  44987. if ( polygonOffset ) {
  44988. this.enable( gl.POLYGON_OFFSET_FILL );
  44989. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  44990. gl.polygonOffset( factor, units );
  44991. this.currentPolygonOffsetFactor = factor;
  44992. this.currentPolygonOffsetUnits = units;
  44993. }
  44994. } else {
  44995. this.disable( gl.POLYGON_OFFSET_FILL );
  44996. }
  44997. }
  44998. /**
  44999. * Defines the usage of the given WebGL program.
  45000. *
  45001. * This method caches the state so `gl.useProgram()` is only
  45002. * called when necessary.
  45003. *
  45004. * @param {WebGLProgram} program - The WebGL program to use.
  45005. * @return {boolean} Whether a program change has been executed or not.
  45006. */
  45007. useProgram( program ) {
  45008. if ( this.currentProgram !== program ) {
  45009. this.gl.useProgram( program );
  45010. this.currentProgram = program;
  45011. return true;
  45012. }
  45013. return false;
  45014. }
  45015. /**
  45016. * Sets the vertex state by binding the given VAO and element buffer.
  45017. *
  45018. * @param {WebGLVertexArrayObject} vao - The VAO.
  45019. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  45020. * @return {boolean} Whether a vertex state has been changed or not.
  45021. */
  45022. setVertexState( vao, indexBuffer = null ) {
  45023. const gl = this.gl;
  45024. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  45025. gl.bindVertexArray( vao );
  45026. if ( indexBuffer !== null ) {
  45027. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  45028. }
  45029. this.currentVAO = vao;
  45030. this.currentIndex = indexBuffer;
  45031. return true;
  45032. }
  45033. return false;
  45034. }
  45035. /**
  45036. * Resets the vertex array state by resetting the VAO and element buffer.
  45037. */
  45038. resetVertexState() {
  45039. const gl = this.gl;
  45040. gl.bindVertexArray( null );
  45041. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  45042. this.currentVAO = null;
  45043. this.currentIndex = null;
  45044. }
  45045. // framebuffer
  45046. /**
  45047. * Binds the given framebuffer.
  45048. *
  45049. * This method caches the state so `gl.bindFramebuffer()` is only
  45050. * called when necessary.
  45051. *
  45052. * @param {number} target - The binding point (target).
  45053. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  45054. * @return {boolean} Whether a bind has been executed or not.
  45055. */
  45056. bindFramebuffer( target, framebuffer ) {
  45057. const { gl, currentBoundFramebuffers } = this;
  45058. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  45059. gl.bindFramebuffer( target, framebuffer );
  45060. currentBoundFramebuffers[ target ] = framebuffer;
  45061. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  45062. if ( target === gl.DRAW_FRAMEBUFFER ) {
  45063. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  45064. }
  45065. if ( target === gl.FRAMEBUFFER ) {
  45066. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  45067. }
  45068. return true;
  45069. }
  45070. return false;
  45071. }
  45072. /**
  45073. * Defines draw buffers to which fragment colors are written into.
  45074. * Configures the MRT setup of custom framebuffers.
  45075. *
  45076. * This method caches the state so `gl.drawBuffers()` is only
  45077. * called when necessary.
  45078. *
  45079. * @param {RenderContext} renderContext - The render context.
  45080. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  45081. */
  45082. drawBuffers( renderContext, framebuffer ) {
  45083. const { gl } = this;
  45084. let drawBuffers = [];
  45085. let needsUpdate = false;
  45086. if ( renderContext.textures !== null ) {
  45087. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  45088. if ( drawBuffers === undefined ) {
  45089. drawBuffers = [];
  45090. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  45091. }
  45092. const textures = renderContext.textures;
  45093. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  45094. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  45095. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  45096. }
  45097. drawBuffers.length = textures.length;
  45098. needsUpdate = true;
  45099. }
  45100. } else {
  45101. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  45102. drawBuffers[ 0 ] = gl.BACK;
  45103. needsUpdate = true;
  45104. }
  45105. }
  45106. if ( needsUpdate ) {
  45107. gl.drawBuffers( drawBuffers );
  45108. }
  45109. }
  45110. // texture
  45111. /**
  45112. * Makes the given texture unit active.
  45113. *
  45114. * This method caches the state so `gl.activeTexture()` is only
  45115. * called when necessary.
  45116. *
  45117. * @param {number} webglSlot - The texture unit to make active.
  45118. */
  45119. activeTexture( webglSlot ) {
  45120. const { gl, currentTextureSlot, maxTextures } = this;
  45121. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45122. if ( currentTextureSlot !== webglSlot ) {
  45123. gl.activeTexture( webglSlot );
  45124. this.currentTextureSlot = webglSlot;
  45125. }
  45126. }
  45127. /**
  45128. * Binds the given WebGL texture to a target.
  45129. *
  45130. * This method caches the state so `gl.bindTexture()` is only
  45131. * called when necessary.
  45132. *
  45133. * @param {number} webglType - The binding point (target).
  45134. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  45135. * @param {number} webglSlot - The texture.
  45136. */
  45137. bindTexture( webglType, webglTexture, webglSlot ) {
  45138. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  45139. if ( webglSlot === undefined ) {
  45140. if ( currentTextureSlot === null ) {
  45141. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45142. } else {
  45143. webglSlot = currentTextureSlot;
  45144. }
  45145. }
  45146. let boundTexture = currentBoundTextures[ webglSlot ];
  45147. if ( boundTexture === undefined ) {
  45148. boundTexture = { type: undefined, texture: undefined };
  45149. currentBoundTextures[ webglSlot ] = boundTexture;
  45150. }
  45151. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  45152. if ( currentTextureSlot !== webglSlot ) {
  45153. gl.activeTexture( webglSlot );
  45154. this.currentTextureSlot = webglSlot;
  45155. }
  45156. gl.bindTexture( webglType, webglTexture );
  45157. boundTexture.type = webglType;
  45158. boundTexture.texture = webglTexture;
  45159. }
  45160. }
  45161. /**
  45162. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  45163. *
  45164. * This method caches the state so `gl.bindBufferBase()` is only
  45165. * called when necessary.
  45166. *
  45167. * @param {number} target - The target for the bind operation.
  45168. * @param {number} index - The index of the target.
  45169. * @param {WebGLBuffer} buffer - The WebGL buffer.
  45170. * @return {boolean} Whether a bind has been executed or not.
  45171. */
  45172. bindBufferBase( target, index, buffer ) {
  45173. const { gl } = this;
  45174. const key = `${target}-${index}`;
  45175. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  45176. gl.bindBufferBase( target, index, buffer );
  45177. this.currentBoundBufferBases[ key ] = buffer;
  45178. return true;
  45179. }
  45180. return false;
  45181. }
  45182. /**
  45183. * Unbinds the current bound texture.
  45184. *
  45185. * This method caches the state so `gl.bindTexture()` is only
  45186. * called when necessary.
  45187. */
  45188. unbindTexture() {
  45189. const { gl, currentTextureSlot, currentBoundTextures } = this;
  45190. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  45191. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  45192. gl.bindTexture( boundTexture.type, null );
  45193. boundTexture.type = undefined;
  45194. boundTexture.texture = undefined;
  45195. }
  45196. }
  45197. }
  45198. /**
  45199. * A WebGL 2 backend utility module with common helpers.
  45200. *
  45201. * @private
  45202. */
  45203. class WebGLUtils {
  45204. /**
  45205. * Constructs a new utility object.
  45206. *
  45207. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45208. */
  45209. constructor( backend ) {
  45210. /**
  45211. * A reference to the WebGL 2 backend.
  45212. *
  45213. * @type {WebGLBackend}
  45214. */
  45215. this.backend = backend;
  45216. /**
  45217. * A reference to the rendering context.
  45218. *
  45219. * @type {WebGL2RenderingContext}
  45220. */
  45221. this.gl = this.backend.gl;
  45222. /**
  45223. * A reference to a backend module holding extension-related
  45224. * utility functions.
  45225. *
  45226. * @type {WebGLExtensions}
  45227. */
  45228. this.extensions = backend.extensions;
  45229. }
  45230. /**
  45231. * Converts the given three.js constant into a WebGL constant.
  45232. * The method currently supports the conversion of texture formats
  45233. * and types.
  45234. *
  45235. * @param {number} p - The three.js constant.
  45236. * @param {string} [colorSpace=NoColorSpace] - The color space.
  45237. * @return {?number} The corresponding WebGL constant.
  45238. */
  45239. convert( p, colorSpace = NoColorSpace ) {
  45240. const { gl, extensions } = this;
  45241. let extension;
  45242. const transfer = ColorManagement.getTransfer( colorSpace );
  45243. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  45244. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  45245. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  45246. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  45247. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  45248. if ( p === ByteType ) return gl.BYTE;
  45249. if ( p === ShortType ) return gl.SHORT;
  45250. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  45251. if ( p === IntType ) return gl.INT;
  45252. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  45253. if ( p === FloatType ) return gl.FLOAT;
  45254. if ( p === HalfFloatType ) {
  45255. return gl.HALF_FLOAT;
  45256. }
  45257. if ( p === AlphaFormat ) return gl.ALPHA;
  45258. if ( p === RGBFormat ) return gl.RGB;
  45259. if ( p === RGBAFormat ) return gl.RGBA;
  45260. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  45261. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  45262. // WebGL2 formats.
  45263. if ( p === RedFormat ) return gl.RED;
  45264. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  45265. if ( p === RGFormat ) return gl.RG;
  45266. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  45267. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  45268. // S3TC
  45269. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  45270. if ( transfer === SRGBTransfer ) {
  45271. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  45272. if ( extension !== null ) {
  45273. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  45274. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  45275. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  45276. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  45277. } else {
  45278. return null;
  45279. }
  45280. } else {
  45281. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  45282. if ( extension !== null ) {
  45283. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45284. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45285. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45286. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45287. } else {
  45288. return null;
  45289. }
  45290. }
  45291. }
  45292. // PVRTC
  45293. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  45294. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  45295. if ( extension !== null ) {
  45296. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45297. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45298. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45299. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45300. } else {
  45301. return null;
  45302. }
  45303. }
  45304. // ETC
  45305. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  45306. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  45307. if ( extension !== null ) {
  45308. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  45309. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  45310. } else {
  45311. return null;
  45312. }
  45313. }
  45314. // ASTC
  45315. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  45316. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  45317. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  45318. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  45319. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  45320. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  45321. if ( extension !== null ) {
  45322. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  45323. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  45324. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  45325. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  45326. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  45327. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  45328. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  45329. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  45330. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  45331. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  45332. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  45333. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  45334. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  45335. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  45336. } else {
  45337. return null;
  45338. }
  45339. }
  45340. // BPTC
  45341. if ( p === RGBA_BPTC_Format ) {
  45342. extension = extensions.get( 'EXT_texture_compression_bptc' );
  45343. if ( extension !== null ) {
  45344. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  45345. } else {
  45346. return null;
  45347. }
  45348. }
  45349. // RGTC
  45350. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  45351. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  45352. if ( extension !== null ) {
  45353. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  45354. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  45355. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  45356. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  45357. } else {
  45358. return null;
  45359. }
  45360. }
  45361. //
  45362. if ( p === UnsignedInt248Type ) {
  45363. return gl.UNSIGNED_INT_24_8;
  45364. }
  45365. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  45366. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  45367. }
  45368. /**
  45369. * This method can be used to synchronize the CPU with the GPU by waiting until
  45370. * ongoing GPU commands have been completed.
  45371. *
  45372. * @private
  45373. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  45374. */
  45375. _clientWaitAsync() {
  45376. const { gl } = this;
  45377. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  45378. gl.flush();
  45379. return new Promise( ( resolve, reject ) => {
  45380. function test() {
  45381. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  45382. if ( res === gl.WAIT_FAILED ) {
  45383. gl.deleteSync( sync );
  45384. reject();
  45385. return;
  45386. }
  45387. if ( res === gl.TIMEOUT_EXPIRED ) {
  45388. requestAnimationFrame( test );
  45389. return;
  45390. }
  45391. gl.deleteSync( sync );
  45392. resolve();
  45393. }
  45394. test();
  45395. } );
  45396. }
  45397. }
  45398. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  45399. /**
  45400. * A WebGL 2 backend utility module for managing textures.
  45401. *
  45402. * @private
  45403. */
  45404. class WebGLTextureUtils {
  45405. /**
  45406. * Constructs a new utility object.
  45407. *
  45408. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45409. */
  45410. constructor( backend ) {
  45411. /**
  45412. * A reference to the WebGL 2 backend.
  45413. *
  45414. * @type {WebGLBackend}
  45415. */
  45416. this.backend = backend;
  45417. /**
  45418. * A reference to the rendering context.
  45419. *
  45420. * @type {WebGL2RenderingContext}
  45421. */
  45422. this.gl = backend.gl;
  45423. /**
  45424. * A reference to a backend module holding extension-related
  45425. * utility functions.
  45426. *
  45427. * @type {WebGLExtensions}
  45428. */
  45429. this.extensions = backend.extensions;
  45430. /**
  45431. * A dictionary for managing default textures. The key
  45432. * is the binding point (target), the value the WEbGL texture object.
  45433. *
  45434. * @type {Object<GLenum,WebGLTexture>}
  45435. */
  45436. this.defaultTextures = {};
  45437. /**
  45438. * A scratch framebuffer used for attaching the source texture in
  45439. * {@link copyTextureToTexture}.
  45440. *
  45441. * @private
  45442. * @type {?WebGLFramebuffer}
  45443. */
  45444. this._srcFramebuffer = null;
  45445. /**
  45446. * A scratch framebuffer used for attaching the destination texture in
  45447. * {@link copyTextureToTexture}.
  45448. *
  45449. * @private
  45450. * @type {?WebGLFramebuffer}
  45451. */
  45452. this._dstFramebuffer = null;
  45453. if ( initialized === false ) {
  45454. this._init();
  45455. initialized = true;
  45456. }
  45457. }
  45458. /**
  45459. * Inits the state of the utility.
  45460. *
  45461. * @private
  45462. */
  45463. _init() {
  45464. const gl = this.gl;
  45465. // Store only WebGL constants here.
  45466. wrappingToGL = {
  45467. [ RepeatWrapping ]: gl.REPEAT,
  45468. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  45469. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  45470. };
  45471. filterToGL = {
  45472. [ NearestFilter ]: gl.NEAREST,
  45473. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  45474. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  45475. [ LinearFilter ]: gl.LINEAR,
  45476. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  45477. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  45478. };
  45479. compareToGL = {
  45480. [ NeverCompare ]: gl.NEVER,
  45481. [ AlwaysCompare ]: gl.ALWAYS,
  45482. [ LessCompare ]: gl.LESS,
  45483. [ LessEqualCompare ]: gl.LEQUAL,
  45484. [ EqualCompare ]: gl.EQUAL,
  45485. [ GreaterEqualCompare ]: gl.GEQUAL,
  45486. [ GreaterCompare ]: gl.GREATER,
  45487. [ NotEqualCompare ]: gl.NOTEQUAL
  45488. };
  45489. }
  45490. /**
  45491. * Returns the native texture type for the given texture.
  45492. *
  45493. * @param {Texture} texture - The texture.
  45494. * @return {GLenum} The native texture type.
  45495. */
  45496. getGLTextureType( texture ) {
  45497. const { gl } = this;
  45498. let glTextureType;
  45499. if ( texture.isCubeTexture === true ) {
  45500. glTextureType = gl.TEXTURE_CUBE_MAP;
  45501. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45502. glTextureType = gl.TEXTURE_2D_ARRAY;
  45503. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  45504. glTextureType = gl.TEXTURE_3D;
  45505. } else {
  45506. glTextureType = gl.TEXTURE_2D;
  45507. }
  45508. return glTextureType;
  45509. }
  45510. /**
  45511. * Returns the native texture type for the given texture.
  45512. *
  45513. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  45514. * @param {GLenum} glFormat - The WebGL format.
  45515. * @param {GLenum} glType - The WebGL type.
  45516. * @param {string} colorSpace - The texture's color space.
  45517. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  45518. * @return {GLenum} The internal format.
  45519. */
  45520. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  45521. const { gl, extensions } = this;
  45522. if ( internalFormatName !== null ) {
  45523. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  45524. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  45525. }
  45526. let internalFormat = glFormat;
  45527. if ( glFormat === gl.RED ) {
  45528. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  45529. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  45530. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  45531. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  45532. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45533. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45534. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45535. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45536. }
  45537. if ( glFormat === gl.RED_INTEGER ) {
  45538. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  45539. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  45540. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45541. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45542. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45543. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45544. }
  45545. if ( glFormat === gl.RG ) {
  45546. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  45547. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  45548. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  45549. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  45550. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45551. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45552. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45553. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45554. }
  45555. if ( glFormat === gl.RG_INTEGER ) {
  45556. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  45557. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  45558. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45559. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45560. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45561. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45562. }
  45563. if ( glFormat === gl.RGB ) {
  45564. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45565. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  45566. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  45567. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  45568. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  45569. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45570. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45571. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45572. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45573. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  45574. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  45575. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45576. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  45577. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  45578. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  45579. }
  45580. if ( glFormat === gl.RGB_INTEGER ) {
  45581. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  45582. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  45583. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45584. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45585. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45586. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45587. }
  45588. if ( glFormat === gl.RGBA ) {
  45589. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45590. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  45591. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  45592. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  45593. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  45594. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45595. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45596. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45597. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45598. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  45599. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  45600. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45601. }
  45602. if ( glFormat === gl.RGBA_INTEGER ) {
  45603. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  45604. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  45605. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45606. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45607. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45608. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45609. }
  45610. if ( glFormat === gl.DEPTH_COMPONENT ) {
  45611. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  45612. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  45613. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  45614. }
  45615. if ( glFormat === gl.DEPTH_STENCIL ) {
  45616. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  45617. }
  45618. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  45619. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  45620. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  45621. extensions.get( 'EXT_color_buffer_float' );
  45622. }
  45623. return internalFormat;
  45624. }
  45625. /**
  45626. * Sets the texture parameters for the given texture.
  45627. *
  45628. * @param {GLenum} textureType - The texture type.
  45629. * @param {Texture} texture - The texture.
  45630. */
  45631. setTextureParameters( textureType, texture ) {
  45632. const { gl, extensions, backend } = this;
  45633. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  45634. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  45635. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  45636. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  45637. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  45638. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  45639. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  45640. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  45641. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  45642. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  45643. // WebGL 2 does not support wrapping for depth 2D array textures
  45644. if ( ! texture.isArrayTexture ) {
  45645. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  45646. }
  45647. }
  45648. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  45649. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  45650. // follow WebGPU backend mapping for texture filtering
  45651. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  45652. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  45653. if ( texture.compareFunction ) {
  45654. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  45655. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  45656. }
  45657. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45658. if ( texture.magFilter === NearestFilter ) return;
  45659. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  45660. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  45661. if ( texture.anisotropy > 1 ) {
  45662. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45663. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  45664. }
  45665. }
  45666. }
  45667. /**
  45668. * Creates a default texture for the given texture that can be used
  45669. * as a placeholder until the actual texture is ready for usage.
  45670. *
  45671. * @param {Texture} texture - The texture to create a default texture for.
  45672. */
  45673. createDefaultTexture( texture ) {
  45674. const { gl, backend, defaultTextures } = this;
  45675. const glTextureType = this.getGLTextureType( texture );
  45676. let textureGPU = defaultTextures[ glTextureType ];
  45677. if ( textureGPU === undefined ) {
  45678. textureGPU = gl.createTexture();
  45679. backend.state.bindTexture( glTextureType, textureGPU );
  45680. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  45681. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  45682. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  45683. defaultTextures[ glTextureType ] = textureGPU;
  45684. }
  45685. backend.set( texture, {
  45686. textureGPU,
  45687. glTextureType
  45688. } );
  45689. }
  45690. /**
  45691. * Defines a texture on the GPU for the given texture object.
  45692. *
  45693. * @param {Texture} texture - The texture.
  45694. * @param {Object} [options={}] - Optional configuration parameter.
  45695. * @return {undefined}
  45696. */
  45697. createTexture( texture, options ) {
  45698. const { gl, backend } = this;
  45699. const { levels, width, height, depth } = options;
  45700. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  45701. const glType = backend.utils.convert( texture.type );
  45702. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  45703. const textureGPU = gl.createTexture();
  45704. const glTextureType = this.getGLTextureType( texture );
  45705. backend.state.bindTexture( glTextureType, textureGPU );
  45706. this.setTextureParameters( glTextureType, texture );
  45707. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  45708. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  45709. } else if ( texture.isData3DTexture ) {
  45710. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  45711. } else if ( ! texture.isVideoTexture ) {
  45712. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  45713. }
  45714. backend.set( texture, {
  45715. textureGPU,
  45716. glTextureType,
  45717. glFormat,
  45718. glType,
  45719. glInternalFormat
  45720. } );
  45721. }
  45722. /**
  45723. * Uploads texture buffer data to the GPU memory.
  45724. *
  45725. * @param {WebGLBuffer} buffer - The buffer data.
  45726. * @param {Texture} texture - The texture,
  45727. */
  45728. copyBufferToTexture( buffer, texture ) {
  45729. const { gl, backend } = this;
  45730. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  45731. const { width, height } = texture.source.data;
  45732. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  45733. backend.state.bindTexture( glTextureType, textureGPU );
  45734. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  45735. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  45736. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  45737. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  45738. backend.state.unbindTexture();
  45739. // debug
  45740. // const framebuffer = gl.createFramebuffer();
  45741. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  45742. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  45743. // const readout = new Float32Array( width * height * 4 );
  45744. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  45745. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  45746. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  45747. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  45748. // log( readout );
  45749. }
  45750. /**
  45751. * Uploads the updated texture data to the GPU.
  45752. *
  45753. * @param {Texture} texture - The texture.
  45754. * @param {Object} [options={}] - Optional configuration parameter.
  45755. */
  45756. updateTexture( texture, options ) {
  45757. const { gl } = this;
  45758. const { width, height } = options;
  45759. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  45760. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  45761. return;
  45762. this.backend.state.bindTexture( glTextureType, textureGPU );
  45763. this.setTextureParameters( glTextureType, texture );
  45764. if ( texture.isCompressedTexture ) {
  45765. const mipmaps = texture.mipmaps;
  45766. const image = options.image;
  45767. for ( let i = 0; i < mipmaps.length; i ++ ) {
  45768. const mipmap = mipmaps[ i ];
  45769. if ( texture.isCompressedArrayTexture ) {
  45770. if ( texture.format !== gl.RGBA ) {
  45771. if ( glFormat !== null ) {
  45772. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  45773. } else {
  45774. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  45775. }
  45776. } else {
  45777. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  45778. }
  45779. } else {
  45780. if ( glFormat !== null ) {
  45781. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  45782. } else {
  45783. warn( 'WebGLBackend: Unsupported compressed texture format' );
  45784. }
  45785. }
  45786. }
  45787. } else if ( texture.isCubeTexture ) {
  45788. const images = options.images;
  45789. const mipmaps = texture.mipmaps;
  45790. for ( let i = 0; i < 6; i ++ ) {
  45791. const image = getImage( images[ i ] );
  45792. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  45793. for ( let j = 0; j < mipmaps.length; j ++ ) {
  45794. const mipmap = mipmaps[ j ];
  45795. const image = getImage( mipmap.images[ i ] );
  45796. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  45797. }
  45798. }
  45799. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  45800. const image = options.image;
  45801. if ( texture.layerUpdates.size > 0 ) {
  45802. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  45803. for ( const layerIndex of texture.layerUpdates ) {
  45804. const layerData = image.data.subarray(
  45805. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  45806. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  45807. );
  45808. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  45809. }
  45810. texture.clearLayerUpdates();
  45811. } else {
  45812. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45813. }
  45814. } else if ( texture.isData3DTexture ) {
  45815. const image = options.image;
  45816. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45817. } else if ( texture.isVideoTexture ) {
  45818. texture.update();
  45819. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  45820. } else {
  45821. const mipmaps = texture.mipmaps;
  45822. if ( mipmaps.length > 0 ) {
  45823. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  45824. const mipmap = mipmaps[ i ];
  45825. const image = getImage( mipmap );
  45826. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  45827. }
  45828. } else {
  45829. const image = getImage( options.image );
  45830. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  45831. }
  45832. }
  45833. }
  45834. /**
  45835. * Generates mipmaps for the given texture.
  45836. *
  45837. * @param {Texture} texture - The texture.
  45838. */
  45839. generateMipmaps( texture ) {
  45840. const { gl, backend } = this;
  45841. const { textureGPU, glTextureType } = backend.get( texture );
  45842. backend.state.bindTexture( glTextureType, textureGPU );
  45843. gl.generateMipmap( glTextureType );
  45844. }
  45845. /**
  45846. * Deallocates the render buffers of the given render target.
  45847. *
  45848. * @param {RenderTarget} renderTarget - The render target.
  45849. */
  45850. deallocateRenderBuffers( renderTarget ) {
  45851. const { gl, backend } = this;
  45852. // remove framebuffer reference
  45853. if ( renderTarget ) {
  45854. const renderContextData = backend.get( renderTarget );
  45855. renderContextData.renderBufferStorageSetup = undefined;
  45856. if ( renderContextData.framebuffers ) {
  45857. for ( const cacheKey in renderContextData.framebuffers ) {
  45858. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  45859. }
  45860. delete renderContextData.framebuffers;
  45861. }
  45862. if ( renderContextData.depthRenderbuffer ) {
  45863. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  45864. delete renderContextData.depthRenderbuffer;
  45865. }
  45866. if ( renderContextData.stencilRenderbuffer ) {
  45867. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  45868. delete renderContextData.stencilRenderbuffer;
  45869. }
  45870. if ( renderContextData.msaaFrameBuffer ) {
  45871. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  45872. delete renderContextData.msaaFrameBuffer;
  45873. }
  45874. if ( renderContextData.msaaRenderbuffers ) {
  45875. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  45876. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  45877. }
  45878. delete renderContextData.msaaRenderbuffers;
  45879. }
  45880. }
  45881. }
  45882. /**
  45883. * Destroys the GPU data for the given texture object.
  45884. *
  45885. * @param {Texture} texture - The texture.
  45886. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45887. */
  45888. destroyTexture( texture, isDefaultTexture = false ) {
  45889. const { gl, backend } = this;
  45890. const { textureGPU, renderTarget } = backend.get( texture );
  45891. this.deallocateRenderBuffers( renderTarget );
  45892. if ( isDefaultTexture === false ) {
  45893. gl.deleteTexture( textureGPU );
  45894. }
  45895. backend.delete( texture );
  45896. }
  45897. /**
  45898. * Copies data of the given source texture to the given destination texture.
  45899. *
  45900. * @param {Texture} srcTexture - The source texture.
  45901. * @param {Texture} dstTexture - The destination texture.
  45902. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45903. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45904. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45905. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45906. */
  45907. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45908. const { gl, backend } = this;
  45909. const { state } = this.backend;
  45910. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  45911. state.bindTexture( glTextureType, dstTextureGPU );
  45912. // gather the necessary dimensions to copy
  45913. let width, height, depth, minX, minY, minZ;
  45914. let dstX, dstY, dstZ;
  45915. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  45916. if ( srcRegion !== null ) {
  45917. width = srcRegion.max.x - srcRegion.min.x;
  45918. height = srcRegion.max.y - srcRegion.min.y;
  45919. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  45920. minX = srcRegion.min.x;
  45921. minY = srcRegion.min.y;
  45922. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  45923. } else {
  45924. const levelScale = Math.pow( 2, - srcLevel );
  45925. width = Math.floor( image.width * levelScale );
  45926. height = Math.floor( image.height * levelScale );
  45927. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  45928. depth = image.depth;
  45929. } else if ( srcTexture.isData3DTexture ) {
  45930. depth = Math.floor( image.depth * levelScale );
  45931. } else {
  45932. depth = 1;
  45933. }
  45934. minX = 0;
  45935. minY = 0;
  45936. minZ = 0;
  45937. }
  45938. if ( dstPosition !== null ) {
  45939. dstX = dstPosition.x;
  45940. dstY = dstPosition.y;
  45941. dstZ = dstPosition.z;
  45942. } else {
  45943. dstX = 0;
  45944. dstY = 0;
  45945. dstZ = 0;
  45946. }
  45947. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  45948. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  45949. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  45950. // used for copying data from cpu
  45951. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  45952. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  45953. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  45954. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  45955. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  45956. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  45957. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  45958. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  45959. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  45960. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  45961. // set up the src texture
  45962. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  45963. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  45964. if ( srcTexture.isDepthTexture ) {
  45965. const srcTextureData = backend.get( srcTexture );
  45966. const dstTextureData = backend.get( dstTexture );
  45967. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  45968. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  45969. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  45970. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  45971. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  45972. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  45973. for ( let i = 0; i < depth; i ++ ) {
  45974. // if the source or destination are a 3d target then a layer needs to be bound
  45975. if ( isSrc3D ) {
  45976. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45977. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45978. }
  45979. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  45980. }
  45981. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45982. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45983. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  45984. // get the appropriate frame buffers
  45985. const srcTextureData = backend.get( srcTexture );
  45986. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  45987. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  45988. // bind the frame buffer targets
  45989. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  45990. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  45991. for ( let i = 0; i < depth; i ++ ) {
  45992. // assign the correct layers and mip maps to the frame buffers
  45993. if ( isSrc3D ) {
  45994. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45995. } else {
  45996. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  45997. }
  45998. if ( isDst3D ) {
  45999. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  46000. } else {
  46001. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  46002. }
  46003. // copy the data using the fastest function that can achieve the copy
  46004. if ( srcLevel !== 0 ) {
  46005. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  46006. } else if ( isDst3D ) {
  46007. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  46008. } else {
  46009. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  46010. }
  46011. }
  46012. // unbind read, draw buffers
  46013. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  46014. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  46015. } else {
  46016. if ( isDst3D ) {
  46017. // copy data into the 3d texture
  46018. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  46019. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  46020. } else if ( dstTexture.isCompressedArrayTexture ) {
  46021. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  46022. } else {
  46023. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  46024. }
  46025. } else {
  46026. // copy data into the 2d texture
  46027. if ( srcTexture.isDataTexture ) {
  46028. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  46029. } else if ( srcTexture.isCompressedTexture ) {
  46030. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  46031. } else {
  46032. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  46033. }
  46034. }
  46035. }
  46036. // reset values
  46037. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  46038. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  46039. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  46040. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  46041. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  46042. // Generate mipmaps only when copying level 0
  46043. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  46044. gl.generateMipmap( glTextureType );
  46045. }
  46046. state.unbindTexture();
  46047. }
  46048. /**
  46049. * Copies the current bound framebuffer to the given texture.
  46050. *
  46051. * @param {Texture} texture - The destination texture.
  46052. * @param {RenderContext} renderContext - The render context.
  46053. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46054. */
  46055. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46056. const { gl } = this;
  46057. const { state } = this.backend;
  46058. const { textureGPU } = this.backend.get( texture );
  46059. const { x, y, z: width, w: height } = rectangle;
  46060. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  46061. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  46062. if ( requireDrawFrameBuffer ) {
  46063. const partial = ( x !== 0 || y !== 0 );
  46064. let mask;
  46065. let attachment;
  46066. if ( texture.isDepthTexture === true ) {
  46067. mask = gl.DEPTH_BUFFER_BIT;
  46068. attachment = gl.DEPTH_ATTACHMENT;
  46069. if ( renderContext.stencil ) {
  46070. mask |= gl.STENCIL_BUFFER_BIT;
  46071. }
  46072. } else {
  46073. mask = gl.COLOR_BUFFER_BIT;
  46074. attachment = gl.COLOR_ATTACHMENT0;
  46075. }
  46076. if ( partial ) {
  46077. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  46078. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  46079. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46080. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46081. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  46082. const flippedY = srcHeight - y - height;
  46083. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  46084. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46085. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46086. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  46087. state.unbindTexture();
  46088. } else {
  46089. const fb = gl.createFramebuffer();
  46090. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46091. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  46092. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  46093. gl.deleteFramebuffer( fb );
  46094. }
  46095. } else {
  46096. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46097. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  46098. state.unbindTexture();
  46099. }
  46100. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  46101. this.backend._setFramebuffer( renderContext );
  46102. }
  46103. /**
  46104. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  46105. *
  46106. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  46107. * @param {RenderContext} renderContext - The render context.
  46108. * @param {number} samples - The MSAA sample count.
  46109. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  46110. */
  46111. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  46112. const { gl } = this;
  46113. const renderTarget = renderContext.renderTarget;
  46114. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  46115. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46116. if ( depthBuffer && ! stencilBuffer ) {
  46117. let glInternalFormat = gl.DEPTH_COMPONENT24;
  46118. if ( useMultisampledRTT === true ) {
  46119. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46120. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  46121. } else if ( samples > 0 ) {
  46122. if ( depthTexture && depthTexture.isDepthTexture ) {
  46123. if ( depthTexture.type === gl.FLOAT ) {
  46124. glInternalFormat = gl.DEPTH_COMPONENT32F;
  46125. }
  46126. }
  46127. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  46128. } else {
  46129. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  46130. }
  46131. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46132. } else if ( depthBuffer && stencilBuffer ) {
  46133. if ( samples > 0 ) {
  46134. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  46135. } else {
  46136. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  46137. }
  46138. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46139. }
  46140. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46141. }
  46142. /**
  46143. * Returns texture data as a typed array.
  46144. *
  46145. * @async
  46146. * @param {Texture} texture - The texture to copy.
  46147. * @param {number} x - The x coordinate of the copy origin.
  46148. * @param {number} y - The y coordinate of the copy origin.
  46149. * @param {number} width - The width of the copy.
  46150. * @param {number} height - The height of the copy.
  46151. * @param {number} faceIndex - The face index.
  46152. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46153. */
  46154. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46155. const { backend, gl } = this;
  46156. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  46157. const fb = gl.createFramebuffer();
  46158. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46159. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  46160. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  46161. const typedArrayType = this._getTypedArrayType( glType );
  46162. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  46163. const elementCount = width * height;
  46164. const byteLength = elementCount * bytesPerTexel;
  46165. const buffer = gl.createBuffer();
  46166. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46167. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  46168. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  46169. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46170. await backend.utils._clientWaitAsync();
  46171. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  46172. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46173. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  46174. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46175. gl.deleteFramebuffer( fb );
  46176. return dstBuffer;
  46177. }
  46178. /**
  46179. * Returns the corresponding typed array type for the given WebGL data type.
  46180. *
  46181. * @private
  46182. * @param {GLenum} glType - The WebGL data type.
  46183. * @return {TypedArray.constructor} The typed array type.
  46184. */
  46185. _getTypedArrayType( glType ) {
  46186. const { gl } = this;
  46187. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  46188. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  46189. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  46190. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  46191. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  46192. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  46193. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  46194. if ( glType === gl.FLOAT ) return Float32Array;
  46195. throw new Error( `Unsupported WebGL type: ${glType}` );
  46196. }
  46197. /**
  46198. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  46199. *
  46200. * @private
  46201. * @param {GLenum} glType - The WebGL data type.
  46202. * @param {GLenum} glFormat - The WebGL texture format.
  46203. * @return {number} The bytes-per-texel.
  46204. */
  46205. _getBytesPerTexel( glType, glFormat ) {
  46206. const { gl } = this;
  46207. let bytesPerComponent = 0;
  46208. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  46209. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  46210. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  46211. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  46212. glType === gl.UNSIGNED_SHORT ||
  46213. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  46214. if ( glType === gl.UNSIGNED_INT ||
  46215. glType === gl.FLOAT ) bytesPerComponent = 4;
  46216. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  46217. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  46218. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  46219. }
  46220. /**
  46221. * Frees the internal resources.
  46222. */
  46223. dispose() {
  46224. const { gl } = this;
  46225. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  46226. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  46227. }
  46228. }
  46229. function getImage( source ) {
  46230. if ( source.isDataTexture ) {
  46231. return source.image.data;
  46232. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  46233. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  46234. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  46235. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  46236. return source;
  46237. }
  46238. return source.data;
  46239. }
  46240. /**
  46241. * A WebGL 2 backend utility module for managing extensions.
  46242. *
  46243. * @private
  46244. */
  46245. class WebGLExtensions {
  46246. /**
  46247. * Constructs a new utility object.
  46248. *
  46249. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46250. */
  46251. constructor( backend ) {
  46252. /**
  46253. * A reference to the WebGL 2 backend.
  46254. *
  46255. * @type {WebGLBackend}
  46256. */
  46257. this.backend = backend;
  46258. /**
  46259. * A reference to the rendering context.
  46260. *
  46261. * @type {WebGL2RenderingContext}
  46262. */
  46263. this.gl = this.backend.gl;
  46264. /**
  46265. * A list with all the supported WebGL extensions.
  46266. *
  46267. * @type {Array<string>}
  46268. */
  46269. this.availableExtensions = this.gl.getSupportedExtensions();
  46270. /**
  46271. * A dictionary with requested WebGL extensions.
  46272. * The key is the name of the extension, the value
  46273. * the requested extension object.
  46274. *
  46275. * @type {Object<string,Object>}
  46276. */
  46277. this.extensions = {};
  46278. }
  46279. /**
  46280. * Returns the extension object for the given extension name.
  46281. *
  46282. * @param {string} name - The extension name.
  46283. * @return {Object} The extension object.
  46284. */
  46285. get( name ) {
  46286. let extension = this.extensions[ name ];
  46287. if ( extension === undefined ) {
  46288. extension = this.gl.getExtension( name );
  46289. this.extensions[ name ] = extension;
  46290. }
  46291. return extension;
  46292. }
  46293. /**
  46294. * Returns `true` if the requested extension is available.
  46295. *
  46296. * @param {string} name - The extension name.
  46297. * @return {boolean} Whether the given extension is available or not.
  46298. */
  46299. has( name ) {
  46300. return this.availableExtensions.includes( name );
  46301. }
  46302. }
  46303. /**
  46304. * A WebGL 2 backend utility module for managing the device's capabilities.
  46305. *
  46306. * @private
  46307. */
  46308. class WebGLCapabilities {
  46309. /**
  46310. * Constructs a new utility object.
  46311. *
  46312. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46313. */
  46314. constructor( backend ) {
  46315. /**
  46316. * A reference to the WebGL 2 backend.
  46317. *
  46318. * @type {WebGLBackend}
  46319. */
  46320. this.backend = backend;
  46321. /**
  46322. * This value holds the cached max anisotropy value.
  46323. *
  46324. * @type {?number}
  46325. * @default null
  46326. */
  46327. this.maxAnisotropy = null;
  46328. }
  46329. /**
  46330. * Returns the maximum anisotropy texture filtering value. This value
  46331. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  46332. * WebGL extension.
  46333. *
  46334. * @return {number} The maximum anisotropy texture filtering value.
  46335. */
  46336. getMaxAnisotropy() {
  46337. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  46338. const gl = this.backend.gl;
  46339. const extensions = this.backend.extensions;
  46340. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46341. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46342. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  46343. } else {
  46344. this.maxAnisotropy = 0;
  46345. }
  46346. return this.maxAnisotropy;
  46347. }
  46348. }
  46349. const GLFeatureName = {
  46350. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  46351. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  46352. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  46353. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  46354. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46355. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46356. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  46357. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  46358. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  46359. 'OVR_multiview2': 'OVR_multiview2'
  46360. };
  46361. class WebGLBufferRenderer {
  46362. constructor( backend ) {
  46363. this.gl = backend.gl;
  46364. this.extensions = backend.extensions;
  46365. this.info = backend.renderer.info;
  46366. this.mode = null;
  46367. this.index = 0;
  46368. this.type = null;
  46369. this.object = null;
  46370. }
  46371. render( start, count ) {
  46372. const { gl, mode, object, type, info, index } = this;
  46373. if ( index !== 0 ) {
  46374. gl.drawElements( mode, count, type, start );
  46375. } else {
  46376. gl.drawArrays( mode, start, count );
  46377. }
  46378. info.update( object, count, 1 );
  46379. }
  46380. renderInstances( start, count, primcount ) {
  46381. const { gl, mode, type, index, object, info } = this;
  46382. if ( primcount === 0 ) return;
  46383. if ( index !== 0 ) {
  46384. gl.drawElementsInstanced( mode, count, type, start, primcount );
  46385. } else {
  46386. gl.drawArraysInstanced( mode, start, count, primcount );
  46387. }
  46388. info.update( object, count, primcount );
  46389. }
  46390. renderMultiDraw( starts, counts, drawCount ) {
  46391. const { extensions, mode, object, info } = this;
  46392. if ( drawCount === 0 ) return;
  46393. const extension = extensions.get( 'WEBGL_multi_draw' );
  46394. if ( extension === null ) {
  46395. for ( let i = 0; i < drawCount; i ++ ) {
  46396. this.render( starts[ i ], counts[ i ] );
  46397. }
  46398. } else {
  46399. if ( this.index !== 0 ) {
  46400. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  46401. } else {
  46402. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  46403. }
  46404. let elementCount = 0;
  46405. for ( let i = 0; i < drawCount; i ++ ) {
  46406. elementCount += counts[ i ];
  46407. }
  46408. info.update( object, elementCount, 1 );
  46409. }
  46410. }
  46411. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  46412. const { extensions, mode, object, info } = this;
  46413. if ( drawCount === 0 ) return;
  46414. const extension = extensions.get( 'WEBGL_multi_draw' );
  46415. if ( extension === null ) {
  46416. for ( let i = 0; i < drawCount; i ++ ) {
  46417. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  46418. }
  46419. } else {
  46420. if ( this.index !== 0 ) {
  46421. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  46422. } else {
  46423. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  46424. }
  46425. let elementCount = 0;
  46426. for ( let i = 0; i < drawCount; i ++ ) {
  46427. elementCount += counts[ i ] * primcount[ i ];
  46428. }
  46429. info.update( object, elementCount, 1 );
  46430. }
  46431. }
  46432. //
  46433. }
  46434. /**
  46435. * Abstract base class of a timestamp query pool.
  46436. *
  46437. * @abstract
  46438. */
  46439. class TimestampQueryPool {
  46440. /**
  46441. * Creates a new timestamp query pool.
  46442. *
  46443. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  46444. */
  46445. constructor( maxQueries = 256 ) {
  46446. /**
  46447. * Whether to track timestamps or not.
  46448. *
  46449. * @type {boolean}
  46450. * @default true
  46451. */
  46452. this.trackTimestamp = true;
  46453. /**
  46454. * Maximum number of queries this pool can hold.
  46455. *
  46456. * @type {number}
  46457. * @default 256
  46458. */
  46459. this.maxQueries = maxQueries;
  46460. /**
  46461. * How many queries allocated so far.
  46462. *
  46463. * @type {number}
  46464. * @default 0
  46465. */
  46466. this.currentQueryIndex = 0;
  46467. /**
  46468. * Tracks offsets for different contexts.
  46469. *
  46470. * @type {Map<string, number>}
  46471. */
  46472. this.queryOffsets = new Map();
  46473. /**
  46474. * Whether the pool has been disposed or not.
  46475. *
  46476. * @type {boolean}
  46477. * @default false
  46478. */
  46479. this.isDisposed = false;
  46480. /**
  46481. * TODO
  46482. *
  46483. * @type {number}
  46484. * @default 0
  46485. */
  46486. this.lastValue = 0;
  46487. /**
  46488. * Stores all timestamp frames.
  46489. *
  46490. * @type {Array<number>}
  46491. */
  46492. this.frames = [];
  46493. /**
  46494. * TODO
  46495. *
  46496. * @type {boolean}
  46497. * @default false
  46498. */
  46499. this.pendingResolve = false;
  46500. /**
  46501. * Stores the latest timestamp for each render context.
  46502. *
  46503. * @type {Map<string, number>}
  46504. */
  46505. this.timestamps = new Map();
  46506. }
  46507. /**
  46508. * Returns all timestamp frames.
  46509. *
  46510. * @return {Array<number>} The timestamp frames.
  46511. */
  46512. getTimestampFrames() {
  46513. return this.frames;
  46514. }
  46515. /**
  46516. * Returns the timestamp for a given render context.
  46517. *
  46518. * @param {string} uid - A unique identifier for the render context.
  46519. * @return {?number} The timestamp, or undefined if not available.
  46520. */
  46521. getTimestamp( uid ) {
  46522. let timestamp = this.timestamps.get( uid );
  46523. if ( timestamp === undefined ) {
  46524. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  46525. timestamp = 0;
  46526. }
  46527. return timestamp;
  46528. }
  46529. /**
  46530. * Returns whether a timestamp is available for a given render context.
  46531. *
  46532. * @param {string} uid - A unique identifier for the render context.
  46533. * @return {boolean} True if a timestamp is available, false otherwise.
  46534. */
  46535. hasTimestamp( uid ) {
  46536. return this.timestamps.has( uid );
  46537. }
  46538. /**
  46539. * Allocate queries for a specific uid.
  46540. *
  46541. * @abstract
  46542. * @param {string} uid - A unique identifier for the render context.
  46543. * @param {number} frameId - The current frame identifier.
  46544. * @returns {?number}
  46545. */
  46546. allocateQueriesForContext( /* uid, frameId */ ) {}
  46547. /**
  46548. * Resolve all timestamps and return data (or process them).
  46549. *
  46550. * @abstract
  46551. * @async
  46552. * @returns {Promise<number>|number} The resolved timestamp value.
  46553. */
  46554. async resolveQueriesAsync() {}
  46555. /**
  46556. * Dispose of the query pool.
  46557. *
  46558. * @abstract
  46559. */
  46560. dispose() {}
  46561. }
  46562. /**
  46563. * Manages a pool of WebGL timestamp queries for performance measurement.
  46564. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  46565. *
  46566. * @augments TimestampQueryPool
  46567. */
  46568. class WebGLTimestampQueryPool extends TimestampQueryPool {
  46569. /**
  46570. * Creates a new WebGL timestamp query pool.
  46571. *
  46572. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  46573. * @param {string} type - The type identifier for this query pool.
  46574. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46575. */
  46576. constructor( gl, type, maxQueries = 2048 ) {
  46577. super( maxQueries );
  46578. this.gl = gl;
  46579. this.type = type;
  46580. // Check for timer query extensions
  46581. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  46582. gl.getExtension( 'EXT_disjoint_timer_query' );
  46583. if ( ! this.ext ) {
  46584. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  46585. this.trackTimestamp = false;
  46586. return;
  46587. }
  46588. // Create query objects
  46589. this.queries = [];
  46590. for ( let i = 0; i < this.maxQueries; i ++ ) {
  46591. this.queries.push( gl.createQuery() );
  46592. }
  46593. this.activeQuery = null;
  46594. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  46595. }
  46596. /**
  46597. * Allocates a pair of queries for a given render context.
  46598. *
  46599. * @param {string} uid - A unique identifier for the render context.
  46600. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46601. */
  46602. allocateQueriesForContext( uid ) {
  46603. if ( ! this.trackTimestamp ) return null;
  46604. // Check if we have enough space for a new query pair
  46605. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46606. 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() } ).` );
  46607. return null;
  46608. }
  46609. const baseOffset = this.currentQueryIndex;
  46610. this.currentQueryIndex += 2;
  46611. // Initialize query states
  46612. this.queryStates.set( baseOffset, 'inactive' );
  46613. this.queryOffsets.set( uid, baseOffset );
  46614. return baseOffset;
  46615. }
  46616. /**
  46617. * Begins a timestamp query for the specified render context.
  46618. *
  46619. * @param {string} uid - A unique identifier for the render context.
  46620. */
  46621. beginQuery( uid ) {
  46622. if ( ! this.trackTimestamp || this.isDisposed ) {
  46623. return;
  46624. }
  46625. const baseOffset = this.queryOffsets.get( uid );
  46626. if ( baseOffset == null ) {
  46627. return;
  46628. }
  46629. // Don't start a new query if there's an active one
  46630. if ( this.activeQuery !== null ) {
  46631. return;
  46632. }
  46633. const query = this.queries[ baseOffset ];
  46634. if ( ! query ) {
  46635. return;
  46636. }
  46637. try {
  46638. // Only begin if query is inactive
  46639. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  46640. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  46641. this.activeQuery = baseOffset;
  46642. this.queryStates.set( baseOffset, 'started' );
  46643. }
  46644. } catch ( error ) {
  46645. error( 'Error in beginQuery:', error );
  46646. this.activeQuery = null;
  46647. this.queryStates.set( baseOffset, 'inactive' );
  46648. }
  46649. }
  46650. /**
  46651. * Ends the active timestamp query for the specified render context.
  46652. *
  46653. * @param {string} uid - A unique identifier for the render context.
  46654. */
  46655. endQuery( uid ) {
  46656. if ( ! this.trackTimestamp || this.isDisposed ) {
  46657. return;
  46658. }
  46659. const baseOffset = this.queryOffsets.get( uid );
  46660. if ( baseOffset == null ) {
  46661. return;
  46662. }
  46663. // Only end if this is the active query
  46664. if ( this.activeQuery !== baseOffset ) {
  46665. return;
  46666. }
  46667. try {
  46668. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  46669. this.queryStates.set( baseOffset, 'ended' );
  46670. this.activeQuery = null;
  46671. } catch ( error ) {
  46672. error( 'Error in endQuery:', error );
  46673. // Reset state on error
  46674. this.queryStates.set( baseOffset, 'inactive' );
  46675. this.activeQuery = null;
  46676. }
  46677. }
  46678. /**
  46679. * Asynchronously resolves all completed queries and returns the total duration.
  46680. *
  46681. * @async
  46682. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46683. */
  46684. async resolveQueriesAsync() {
  46685. if ( ! this.trackTimestamp || this.pendingResolve ) {
  46686. return this.lastValue;
  46687. }
  46688. this.pendingResolve = true;
  46689. try {
  46690. // Wait for all ended queries to complete
  46691. const resolvePromises = new Map();
  46692. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  46693. const state = this.queryStates.get( baseOffset );
  46694. if ( state === 'ended' ) {
  46695. const query = this.queries[ baseOffset ];
  46696. resolvePromises.set( uid, this.resolveQuery( query ) );
  46697. }
  46698. }
  46699. if ( resolvePromises.size === 0 ) {
  46700. return this.lastValue;
  46701. }
  46702. //
  46703. const framesDuration = {};
  46704. const frames = [];
  46705. for ( const [ uid, promise ] of resolvePromises ) {
  46706. const match = uid.match( /^(.*):f(\d+)$/ );
  46707. const frame = parseInt( match[ 2 ] );
  46708. if ( frames.includes( frame ) === false ) {
  46709. frames.push( frame );
  46710. }
  46711. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  46712. const duration = await promise;
  46713. this.timestamps.set( uid, duration );
  46714. framesDuration[ frame ] += duration;
  46715. }
  46716. // Return the total duration of the last frame
  46717. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  46718. // Store the last valid result
  46719. this.lastValue = totalDuration;
  46720. this.frames = frames;
  46721. // Reset states
  46722. this.currentQueryIndex = 0;
  46723. this.queryOffsets.clear();
  46724. this.queryStates.clear();
  46725. this.activeQuery = null;
  46726. return totalDuration;
  46727. } catch ( error ) {
  46728. error( 'Error resolving queries:', error );
  46729. return this.lastValue;
  46730. } finally {
  46731. this.pendingResolve = false;
  46732. }
  46733. }
  46734. /**
  46735. * Resolves a single query, checking for completion and disjoint operation.
  46736. *
  46737. * @async
  46738. * @param {WebGLQuery} query - The query object to resolve.
  46739. * @returns {Promise<number>} The elapsed time in milliseconds.
  46740. */
  46741. async resolveQuery( query ) {
  46742. return new Promise( ( resolve ) => {
  46743. if ( this.isDisposed ) {
  46744. resolve( this.lastValue );
  46745. return;
  46746. }
  46747. let timeoutId;
  46748. let isResolved = false;
  46749. const cleanup = () => {
  46750. if ( timeoutId ) {
  46751. clearTimeout( timeoutId );
  46752. timeoutId = null;
  46753. }
  46754. };
  46755. const finalizeResolution = ( value ) => {
  46756. if ( ! isResolved ) {
  46757. isResolved = true;
  46758. cleanup();
  46759. resolve( value );
  46760. }
  46761. };
  46762. const checkQuery = () => {
  46763. if ( this.isDisposed ) {
  46764. finalizeResolution( this.lastValue );
  46765. return;
  46766. }
  46767. try {
  46768. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  46769. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  46770. if ( disjoint ) {
  46771. finalizeResolution( this.lastValue );
  46772. return;
  46773. }
  46774. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  46775. if ( ! available ) {
  46776. timeoutId = setTimeout( checkQuery, 1 );
  46777. return;
  46778. }
  46779. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  46780. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  46781. } catch ( error ) {
  46782. error( 'Error checking query:', error );
  46783. resolve( this.lastValue );
  46784. }
  46785. };
  46786. checkQuery();
  46787. } );
  46788. }
  46789. /**
  46790. * Releases all resources held by this query pool.
  46791. * This includes deleting all query objects and clearing internal state.
  46792. */
  46793. dispose() {
  46794. if ( this.isDisposed ) {
  46795. return;
  46796. }
  46797. this.isDisposed = true;
  46798. if ( ! this.trackTimestamp ) return;
  46799. for ( const query of this.queries ) {
  46800. this.gl.deleteQuery( query );
  46801. }
  46802. this.queries = [];
  46803. this.queryStates.clear();
  46804. this.queryOffsets.clear();
  46805. this.lastValue = 0;
  46806. this.activeQuery = null;
  46807. }
  46808. }
  46809. /**
  46810. * A backend implementation targeting WebGL 2.
  46811. *
  46812. * @private
  46813. * @augments Backend
  46814. */
  46815. class WebGLBackend extends Backend {
  46816. /**
  46817. * WebGLBackend options.
  46818. *
  46819. * @typedef {Object} WebGLBackend~Options
  46820. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46821. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46822. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46823. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46824. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46825. * @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.
  46826. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46827. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  46828. */
  46829. /**
  46830. * Constructs a new WebGPU backend.
  46831. *
  46832. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  46833. */
  46834. constructor( parameters = {} ) {
  46835. super( parameters );
  46836. /**
  46837. * This flag can be used for type testing.
  46838. *
  46839. * @type {boolean}
  46840. * @readonly
  46841. * @default true
  46842. */
  46843. this.isWebGLBackend = true;
  46844. /**
  46845. * A reference to a backend module holding shader attribute-related
  46846. * utility functions.
  46847. *
  46848. * @type {?WebGLAttributeUtils}
  46849. * @default null
  46850. */
  46851. this.attributeUtils = null;
  46852. /**
  46853. * A reference to a backend module holding extension-related
  46854. * utility functions.
  46855. *
  46856. * @type {?WebGLExtensions}
  46857. * @default null
  46858. */
  46859. this.extensions = null;
  46860. /**
  46861. * A reference to a backend module holding capability-related
  46862. * utility functions.
  46863. *
  46864. * @type {?WebGLCapabilities}
  46865. * @default null
  46866. */
  46867. this.capabilities = null;
  46868. /**
  46869. * A reference to a backend module holding texture-related
  46870. * utility functions.
  46871. *
  46872. * @type {?WebGLTextureUtils}
  46873. * @default null
  46874. */
  46875. this.textureUtils = null;
  46876. /**
  46877. * A reference to a backend module holding renderer-related
  46878. * utility functions.
  46879. *
  46880. * @type {?WebGLBufferRenderer}
  46881. * @default null
  46882. */
  46883. this.bufferRenderer = null;
  46884. /**
  46885. * A reference to the rendering context.
  46886. *
  46887. * @type {?WebGL2RenderingContext}
  46888. * @default null
  46889. */
  46890. this.gl = null;
  46891. /**
  46892. * A reference to a backend module holding state-related
  46893. * utility functions.
  46894. *
  46895. * @type {?WebGLState}
  46896. * @default null
  46897. */
  46898. this.state = null;
  46899. /**
  46900. * A reference to a backend module holding common
  46901. * utility functions.
  46902. *
  46903. * @type {?WebGLUtils}
  46904. * @default null
  46905. */
  46906. this.utils = null;
  46907. /**
  46908. * Dictionary for caching VAOs.
  46909. *
  46910. * @type {Object<string,WebGLVertexArrayObject>}
  46911. */
  46912. this.vaoCache = {};
  46913. /**
  46914. * Dictionary for caching transform feedback objects.
  46915. *
  46916. * @type {Object<string,WebGLTransformFeedback>}
  46917. */
  46918. this.transformFeedbackCache = {};
  46919. /**
  46920. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  46921. * Only relevant when using compute shaders.
  46922. *
  46923. * @type {boolean}
  46924. * @default false
  46925. */
  46926. this.discard = false;
  46927. /**
  46928. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  46929. * device does not support the extension.
  46930. *
  46931. * @type {?EXTDisjointTimerQueryWebGL2}
  46932. * @default null
  46933. */
  46934. this.disjoint = null;
  46935. /**
  46936. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  46937. * device does not support the extension.
  46938. *
  46939. * @type {?KHRParallelShaderCompile}
  46940. * @default null
  46941. */
  46942. this.parallel = null;
  46943. /**
  46944. * A reference to the current render context.
  46945. *
  46946. * @private
  46947. * @type {RenderContext}
  46948. * @default null
  46949. */
  46950. this._currentContext = null;
  46951. /**
  46952. * A unique collection of bindings.
  46953. *
  46954. * @private
  46955. * @type {WeakSet<Array<BindGroup>>}
  46956. */
  46957. this._knownBindings = new WeakSet();
  46958. /**
  46959. * Whether the device supports framebuffers invalidation or not.
  46960. *
  46961. * @private
  46962. * @type {boolean}
  46963. */
  46964. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  46965. /**
  46966. * The target framebuffer when rendering with
  46967. * the WebXR device API.
  46968. *
  46969. * @private
  46970. * @type {?WebGLFramebuffer}
  46971. * @default null
  46972. */
  46973. this._xrFramebuffer = null;
  46974. }
  46975. /**
  46976. * Initializes the backend so it is ready for usage.
  46977. *
  46978. * @param {Renderer} renderer - The renderer.
  46979. */
  46980. init( renderer ) {
  46981. super.init( renderer );
  46982. //
  46983. const parameters = this.parameters;
  46984. const contextAttributes = {
  46985. antialias: renderer.currentSamples > 0,
  46986. alpha: true, // always true for performance reasons
  46987. depth: renderer.depth,
  46988. stencil: renderer.stencil
  46989. };
  46990. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  46991. function onContextLost( event ) {
  46992. event.preventDefault();
  46993. const contextLossInfo = {
  46994. api: 'WebGL',
  46995. message: event.statusMessage || 'Unknown reason',
  46996. reason: null,
  46997. originalEvent: event
  46998. };
  46999. renderer.onDeviceLost( contextLossInfo );
  47000. }
  47001. this._onContextLost = onContextLost;
  47002. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  47003. this.gl = glContext;
  47004. this.extensions = new WebGLExtensions( this );
  47005. this.capabilities = new WebGLCapabilities( this );
  47006. this.attributeUtils = new WebGLAttributeUtils( this );
  47007. this.textureUtils = new WebGLTextureUtils( this );
  47008. this.bufferRenderer = new WebGLBufferRenderer( this );
  47009. this.state = new WebGLState( this );
  47010. this.utils = new WebGLUtils( this );
  47011. this.extensions.get( 'EXT_color_buffer_float' );
  47012. this.extensions.get( 'WEBGL_clip_cull_distance' );
  47013. this.extensions.get( 'OES_texture_float_linear' );
  47014. this.extensions.get( 'EXT_color_buffer_half_float' );
  47015. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47016. this.extensions.get( 'WEBGL_render_shared_exponent' );
  47017. this.extensions.get( 'WEBGL_multi_draw' );
  47018. this.extensions.get( 'OVR_multiview2' );
  47019. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  47020. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  47021. }
  47022. /**
  47023. * The coordinate system of the backend.
  47024. *
  47025. * @type {number}
  47026. * @readonly
  47027. */
  47028. get coordinateSystem() {
  47029. return WebGLCoordinateSystem;
  47030. }
  47031. /**
  47032. * This method performs a readback operation by moving buffer data from
  47033. * a storage buffer attribute from the GPU to the CPU.
  47034. *
  47035. * @async
  47036. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47037. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47038. */
  47039. async getArrayBufferAsync( attribute ) {
  47040. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47041. }
  47042. /**
  47043. * Ensures the backend is XR compatible.
  47044. *
  47045. * @async
  47046. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  47047. */
  47048. async makeXRCompatible() {
  47049. const attributes = this.gl.getContextAttributes();
  47050. if ( attributes.xrCompatible !== true ) {
  47051. await this.gl.makeXRCompatible();
  47052. }
  47053. }
  47054. /**
  47055. * Sets the XR rendering destination.
  47056. *
  47057. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  47058. */
  47059. setXRTarget( xrFramebuffer ) {
  47060. this._xrFramebuffer = xrFramebuffer;
  47061. }
  47062. /**
  47063. * Configures the given XR render target with external textures.
  47064. *
  47065. * This method is only relevant when using the WebXR Layers API.
  47066. *
  47067. * @param {XRRenderTarget} renderTarget - The XR render target.
  47068. * @param {WebGLTexture} colorTexture - A native color texture.
  47069. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  47070. */
  47071. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  47072. const gl = this.gl;
  47073. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  47074. if ( depthTexture !== null ) {
  47075. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  47076. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  47077. // The multisample_render_to_texture extension doesn't work properly if there
  47078. // are midframe flushes and an external depth texture.
  47079. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  47080. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  47081. }
  47082. renderTarget._autoAllocateDepthBuffer = false;
  47083. }
  47084. }
  47085. /**
  47086. * Inits a time stamp query for the given render context.
  47087. *
  47088. * @param {string} type - The type of the timestamp query.
  47089. * @param {string} uid - A unique identifier for the timestamp query.
  47090. */
  47091. initTimestampQuery( type, uid ) {
  47092. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47093. if ( ! this.timestampQueryPool[ type ] ) {
  47094. // TODO: Variable maxQueries?
  47095. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  47096. }
  47097. const timestampQueryPool = this.timestampQueryPool[ type ];
  47098. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  47099. if ( baseOffset !== null ) {
  47100. timestampQueryPool.beginQuery( uid );
  47101. }
  47102. }
  47103. // timestamp utils
  47104. /**
  47105. * Prepares the timestamp buffer.
  47106. *
  47107. * @param {string} type - The type of the timestamp query.
  47108. * @param {string} uid - A unique identifier for the timestamp query.
  47109. */
  47110. prepareTimestampBuffer( type, uid ) {
  47111. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47112. const timestampQueryPool = this.timestampQueryPool[ type ];
  47113. timestampQueryPool.endQuery( uid );
  47114. }
  47115. /**
  47116. * Returns the backend's rendering context.
  47117. *
  47118. * @return {WebGL2RenderingContext} The rendering context.
  47119. */
  47120. getContext() {
  47121. return this.gl;
  47122. }
  47123. /**
  47124. * This method is executed at the beginning of a render call and prepares
  47125. * the WebGL state for upcoming render calls
  47126. *
  47127. * @param {RenderContext} renderContext - The render context.
  47128. */
  47129. beginRender( renderContext ) {
  47130. const { state } = this;
  47131. const renderContextData = this.get( renderContext );
  47132. //
  47133. if ( renderContext.viewport ) {
  47134. this.updateViewport( renderContext );
  47135. } else {
  47136. const { width, height } = this.getDrawingBufferSize();
  47137. state.viewport( 0, 0, width, height );
  47138. }
  47139. if ( renderContext.scissor ) {
  47140. const { x, y, width, height } = renderContext.scissorValue;
  47141. state.scissor( x, renderContext.height - height - y, width, height );
  47142. }
  47143. //
  47144. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47145. renderContextData.previousContext = this._currentContext;
  47146. this._currentContext = renderContext;
  47147. this._setFramebuffer( renderContext );
  47148. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  47149. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47150. if ( occlusionQueryCount > 0 ) {
  47151. // Get a reference to the array of objects with queries. The renderContextData property
  47152. // can be changed by another render pass before the async reading of all previous queries complete
  47153. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  47154. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47155. renderContextData.lastOcclusionObject = null;
  47156. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  47157. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47158. renderContextData.occlusionQueryIndex = 0;
  47159. }
  47160. }
  47161. /**
  47162. * This method is executed at the end of a render call and finalizes work
  47163. * after draw calls.
  47164. *
  47165. * @param {RenderContext} renderContext - The render context.
  47166. */
  47167. finishRender( renderContext ) {
  47168. const { gl, state } = this;
  47169. const renderContextData = this.get( renderContext );
  47170. const previousContext = renderContextData.previousContext;
  47171. state.resetVertexState();
  47172. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47173. if ( occlusionQueryCount > 0 ) {
  47174. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47175. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47176. }
  47177. this.resolveOccludedAsync( renderContext );
  47178. }
  47179. const textures = renderContext.textures;
  47180. if ( textures !== null ) {
  47181. for ( let i = 0; i < textures.length; i ++ ) {
  47182. const texture = textures[ i ];
  47183. if ( texture.generateMipmaps ) {
  47184. this.generateMipmaps( texture );
  47185. }
  47186. }
  47187. }
  47188. this._currentContext = previousContext;
  47189. this._resolveRenderTarget( renderContext );
  47190. if ( previousContext !== null ) {
  47191. this._setFramebuffer( previousContext );
  47192. if ( previousContext.viewport ) {
  47193. this.updateViewport( previousContext );
  47194. } else {
  47195. const { width, height } = this.getDrawingBufferSize();
  47196. state.viewport( 0, 0, width, height );
  47197. }
  47198. }
  47199. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47200. }
  47201. /**
  47202. * This method processes the result of occlusion queries and writes it
  47203. * into render context data.
  47204. *
  47205. * @async
  47206. * @param {RenderContext} renderContext - The render context.
  47207. */
  47208. resolveOccludedAsync( renderContext ) {
  47209. const renderContextData = this.get( renderContext );
  47210. // handle occlusion query results
  47211. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  47212. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  47213. const occluded = new WeakSet();
  47214. const { gl } = this;
  47215. renderContextData.currentOcclusionQueryObjects = null;
  47216. renderContextData.currentOcclusionQueries = null;
  47217. const check = () => {
  47218. let completed = 0;
  47219. // check all queries and requeue as appropriate
  47220. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  47221. const query = currentOcclusionQueries[ i ];
  47222. if ( query === null ) continue;
  47223. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  47224. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  47225. currentOcclusionQueries[ i ] = null;
  47226. gl.deleteQuery( query );
  47227. completed ++;
  47228. }
  47229. }
  47230. if ( completed < currentOcclusionQueries.length ) {
  47231. requestAnimationFrame( check );
  47232. } else {
  47233. renderContextData.occluded = occluded;
  47234. }
  47235. };
  47236. check();
  47237. }
  47238. }
  47239. /**
  47240. * Returns `true` if the given 3D object is fully occluded by other
  47241. * 3D objects in the scene.
  47242. *
  47243. * @param {RenderContext} renderContext - The render context.
  47244. * @param {Object3D} object - The 3D object to test.
  47245. * @return {boolean} Whether the 3D object is fully occluded or not.
  47246. */
  47247. isOccluded( renderContext, object ) {
  47248. const renderContextData = this.get( renderContext );
  47249. return renderContextData.occluded && renderContextData.occluded.has( object );
  47250. }
  47251. /**
  47252. * Updates the viewport with the values from the given render context.
  47253. *
  47254. * @param {RenderContext} renderContext - The render context.
  47255. */
  47256. updateViewport( renderContext ) {
  47257. const { state } = this;
  47258. const { x, y, width, height } = renderContext.viewportValue;
  47259. state.viewport( x, renderContext.height - height - y, width, height );
  47260. }
  47261. /**
  47262. * Defines the scissor test.
  47263. *
  47264. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47265. */
  47266. setScissorTest( boolean ) {
  47267. const state = this.state;
  47268. state.setScissorTest( boolean );
  47269. }
  47270. /**
  47271. * Returns the clear color and alpha into a single
  47272. * color object.
  47273. *
  47274. * @return {Color4} The clear color.
  47275. */
  47276. getClearColor() {
  47277. const clearColor = super.getClearColor();
  47278. // Since the canvas is always created with alpha: true,
  47279. // WebGL must always premultiply the clear color.
  47280. clearColor.r *= clearColor.a;
  47281. clearColor.g *= clearColor.a;
  47282. clearColor.b *= clearColor.a;
  47283. return clearColor;
  47284. }
  47285. /**
  47286. * Performs a clear operation.
  47287. *
  47288. * @param {boolean} color - Whether the color buffer should be cleared or not.
  47289. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  47290. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  47291. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  47292. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  47293. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  47294. * or not. Only relevant for explicit clears.
  47295. */
  47296. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  47297. const { gl, renderer } = this;
  47298. if ( descriptor === null ) {
  47299. const clearColor = this.getClearColor();
  47300. descriptor = {
  47301. textures: null,
  47302. clearColorValue: clearColor
  47303. };
  47304. }
  47305. //
  47306. let clear = 0;
  47307. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  47308. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  47309. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  47310. if ( clear !== 0 ) {
  47311. let clearColor;
  47312. if ( descriptor.clearColorValue ) {
  47313. clearColor = descriptor.clearColorValue;
  47314. } else {
  47315. clearColor = this.getClearColor();
  47316. }
  47317. const clearDepth = renderer.getClearDepth();
  47318. const clearStencil = renderer.getClearStencil();
  47319. if ( depth ) this.state.setDepthMask( true );
  47320. if ( descriptor.textures === null ) {
  47321. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  47322. gl.clear( clear );
  47323. } else {
  47324. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  47325. if ( color ) {
  47326. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  47327. if ( i === 0 ) {
  47328. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  47329. } else {
  47330. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  47331. }
  47332. }
  47333. }
  47334. if ( depth && stencil ) {
  47335. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  47336. } else if ( depth ) {
  47337. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  47338. } else if ( stencil ) {
  47339. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  47340. }
  47341. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  47342. }
  47343. }
  47344. }
  47345. /**
  47346. * This method is executed at the beginning of a compute call and
  47347. * prepares the state for upcoming compute tasks.
  47348. *
  47349. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47350. */
  47351. beginCompute( computeGroup ) {
  47352. const { state, gl } = this;
  47353. //
  47354. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47355. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47356. }
  47357. /**
  47358. * Executes a compute command for the given compute node.
  47359. *
  47360. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47361. * @param {Node} computeNode - The compute node.
  47362. * @param {Array<BindGroup>} bindings - The bindings.
  47363. * @param {ComputePipeline} pipeline - The compute pipeline.
  47364. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  47365. */
  47366. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  47367. const { state, gl } = this;
  47368. if ( this.discard === false ) {
  47369. // required here to handle async behaviour of render.compute()
  47370. gl.enable( gl.RASTERIZER_DISCARD );
  47371. this.discard = true;
  47372. }
  47373. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  47374. const vaoKey = this._getVaoKey( attributes );
  47375. const vaoGPU = this.vaoCache[ vaoKey ];
  47376. if ( vaoGPU === undefined ) {
  47377. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  47378. } else {
  47379. state.setVertexState( vaoGPU );
  47380. }
  47381. state.useProgram( programGPU );
  47382. this._bindUniforms( bindings );
  47383. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  47384. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47385. gl.beginTransformFeedback( gl.POINTS );
  47386. count = ( count !== null ) ? count : computeNode.count;
  47387. if ( Array.isArray( count ) ) {
  47388. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  47389. count = count[ 0 ];
  47390. }
  47391. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  47392. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  47393. } else {
  47394. gl.drawArrays( gl.POINTS, 0, count );
  47395. }
  47396. gl.endTransformFeedback();
  47397. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47398. // switch active buffers
  47399. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47400. const dualAttributeData = transformBuffers[ i ];
  47401. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  47402. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  47403. }
  47404. dualAttributeData.switchBuffers();
  47405. }
  47406. }
  47407. /**
  47408. * This method is executed at the end of a compute call and
  47409. * finalizes work after compute tasks.
  47410. *
  47411. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47412. */
  47413. finishCompute( computeGroup ) {
  47414. const gl = this.gl;
  47415. this.discard = false;
  47416. gl.disable( gl.RASTERIZER_DISCARD );
  47417. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47418. if ( this._currentContext ) {
  47419. this._setFramebuffer( this._currentContext );
  47420. }
  47421. }
  47422. /**
  47423. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  47424. *
  47425. * @param {RenderContext} renderContext - The render context.
  47426. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  47427. *
  47428. * @private
  47429. */
  47430. _isRenderCameraDepthArray( renderContext ) {
  47431. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  47432. }
  47433. /**
  47434. * Executes a draw command for the given render object.
  47435. *
  47436. * @param {RenderObject} renderObject - The render object to draw.
  47437. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47438. */
  47439. draw( renderObject/*, info*/ ) {
  47440. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  47441. const { programGPU } = this.get( pipeline );
  47442. const { gl, state } = this;
  47443. const contextData = this.get( context );
  47444. const drawParams = renderObject.getDrawParameters();
  47445. if ( drawParams === null ) return;
  47446. //
  47447. this._bindUniforms( renderObject.getBindings() );
  47448. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  47449. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  47450. state.useProgram( programGPU );
  47451. // vertex state
  47452. const attributes = renderObject.getAttributes();
  47453. const attributesData = this.get( attributes );
  47454. let vaoGPU = attributesData.vaoGPU;
  47455. if ( vaoGPU === undefined ) {
  47456. const vaoKey = this._getVaoKey( attributes );
  47457. vaoGPU = this.vaoCache[ vaoKey ];
  47458. if ( vaoGPU === undefined ) {
  47459. vaoGPU = this._createVao( attributes );
  47460. this.vaoCache[ vaoKey ] = vaoGPU;
  47461. attributesData.vaoGPU = vaoGPU;
  47462. }
  47463. }
  47464. const index = renderObject.getIndex();
  47465. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  47466. state.setVertexState( vaoGPU, indexGPU );
  47467. //
  47468. const lastObject = contextData.lastOcclusionObject;
  47469. if ( lastObject !== object && lastObject !== undefined ) {
  47470. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47471. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47472. contextData.occlusionQueryIndex ++;
  47473. }
  47474. if ( object.occlusionTest === true ) {
  47475. const query = gl.createQuery();
  47476. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  47477. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  47478. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  47479. }
  47480. contextData.lastOcclusionObject = object;
  47481. }
  47482. //
  47483. const renderer = this.bufferRenderer;
  47484. if ( object.isPoints ) renderer.mode = gl.POINTS;
  47485. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  47486. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  47487. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  47488. else {
  47489. if ( material.wireframe === true ) {
  47490. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  47491. renderer.mode = gl.LINES;
  47492. } else {
  47493. renderer.mode = gl.TRIANGLES;
  47494. }
  47495. }
  47496. //
  47497. const { vertexCount, instanceCount } = drawParams;
  47498. let { firstVertex } = drawParams;
  47499. renderer.object = object;
  47500. if ( index !== null ) {
  47501. firstVertex *= index.array.BYTES_PER_ELEMENT;
  47502. const indexData = this.get( index );
  47503. renderer.index = index.count;
  47504. renderer.type = indexData.type;
  47505. } else {
  47506. renderer.index = 0;
  47507. }
  47508. const draw = () => {
  47509. if ( object.isBatchedMesh ) {
  47510. if ( object._multiDrawInstances !== null ) {
  47511. // @deprecated, r174
  47512. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  47513. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  47514. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  47515. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  47516. } else {
  47517. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  47518. }
  47519. } else if ( instanceCount > 1 ) {
  47520. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  47521. } else {
  47522. renderer.render( firstVertex, vertexCount );
  47523. }
  47524. };
  47525. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  47526. const cameraData = this.get( renderObject.camera );
  47527. const cameras = renderObject.camera.cameras;
  47528. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  47529. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47530. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47531. const indexesGPU = [];
  47532. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47533. const bufferGPU = gl.createBuffer();
  47534. data[ 0 ] = i;
  47535. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47536. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  47537. indexesGPU.push( bufferGPU );
  47538. }
  47539. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47540. }
  47541. const cameraIndexData = this.get( cameraIndex );
  47542. const pixelRatio = this.renderer.getPixelRatio();
  47543. const renderTarget = this._currentContext.renderTarget;
  47544. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  47545. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  47546. if ( isRenderCameraDepthArray ) {
  47547. // Clear the depth texture
  47548. const textureData = this.get( renderTarget.depthTexture );
  47549. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  47550. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  47551. const { stencilBuffer } = renderTarget;
  47552. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47553. this.renderer._activeCubeFace = i;
  47554. this._currentContext.activeCubeFace = i;
  47555. this._setFramebuffer( this._currentContext );
  47556. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  47557. }
  47558. this.renderer._activeCubeFace = prevActiveCubeFace;
  47559. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47560. }
  47561. }
  47562. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47563. const subCamera = cameras[ i ];
  47564. if ( object.layers.test( subCamera.layers ) ) {
  47565. if ( isRenderCameraDepthArray ) {
  47566. // Update the active layer
  47567. this.renderer._activeCubeFace = i;
  47568. this._currentContext.activeCubeFace = i;
  47569. this._setFramebuffer( this._currentContext );
  47570. }
  47571. const vp = subCamera.viewport;
  47572. if ( vp !== undefined ) {
  47573. const x = vp.x * pixelRatio;
  47574. const y = vp.y * pixelRatio;
  47575. const width = vp.width * pixelRatio;
  47576. const height = vp.height * pixelRatio;
  47577. state.viewport(
  47578. Math.floor( x ),
  47579. Math.floor( renderObject.context.height - height - y ),
  47580. Math.floor( width ),
  47581. Math.floor( height )
  47582. );
  47583. }
  47584. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  47585. draw();
  47586. }
  47587. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47588. this.renderer._activeCubeFace = prevActiveCubeFace;
  47589. }
  47590. } else {
  47591. draw();
  47592. }
  47593. }
  47594. /**
  47595. * Explain why always null is returned.
  47596. *
  47597. * @param {RenderObject} renderObject - The render object.
  47598. * @return {boolean} Whether the render pipeline requires an update or not.
  47599. */
  47600. needsRenderUpdate( /*renderObject*/ ) {
  47601. return false;
  47602. }
  47603. /**
  47604. * Explain why no cache key is computed.
  47605. *
  47606. * @param {RenderObject} renderObject - The render object.
  47607. * @return {string} The cache key.
  47608. */
  47609. getRenderCacheKey( /*renderObject*/ ) {
  47610. return '';
  47611. }
  47612. // textures
  47613. /**
  47614. * Creates a default texture for the given texture that can be used
  47615. * as a placeholder until the actual texture is ready for usage.
  47616. *
  47617. * @param {Texture} texture - The texture to create a default texture for.
  47618. */
  47619. createDefaultTexture( texture ) {
  47620. this.textureUtils.createDefaultTexture( texture );
  47621. }
  47622. /**
  47623. * Defines a texture on the GPU for the given texture object.
  47624. *
  47625. * @param {Texture} texture - The texture.
  47626. * @param {Object} [options={}] - Optional configuration parameter.
  47627. */
  47628. createTexture( texture, options ) {
  47629. this.textureUtils.createTexture( texture, options );
  47630. }
  47631. /**
  47632. * Uploads the updated texture data to the GPU.
  47633. *
  47634. * @param {Texture} texture - The texture.
  47635. * @param {Object} [options={}] - Optional configuration parameter.
  47636. */
  47637. updateTexture( texture, options ) {
  47638. this.textureUtils.updateTexture( texture, options );
  47639. }
  47640. /**
  47641. * Generates mipmaps for the given texture.
  47642. *
  47643. * @param {Texture} texture - The texture.
  47644. */
  47645. generateMipmaps( texture ) {
  47646. this.textureUtils.generateMipmaps( texture );
  47647. }
  47648. /**
  47649. * Destroys the GPU data for the given texture object.
  47650. *
  47651. * @param {Texture} texture - The texture.
  47652. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47653. */
  47654. destroyTexture( texture, isDefaultTexture = false ) {
  47655. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  47656. }
  47657. /**
  47658. * Returns texture data as a typed array.
  47659. *
  47660. * @async
  47661. * @param {Texture} texture - The texture to copy.
  47662. * @param {number} x - The x coordinate of the copy origin.
  47663. * @param {number} y - The y coordinate of the copy origin.
  47664. * @param {number} width - The width of the copy.
  47665. * @param {number} height - The height of the copy.
  47666. * @param {number} faceIndex - The face index.
  47667. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47668. */
  47669. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47670. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47671. }
  47672. /**
  47673. * This method does nothing since WebGL 2 has no concept of samplers.
  47674. *
  47675. * @param {Texture} texture - The texture to update the sampler for.
  47676. * @return {string} The current sampler key.
  47677. */
  47678. updateSampler( /*texture*/ ) {
  47679. return '';
  47680. }
  47681. // node builder
  47682. /**
  47683. * Returns a node builder for the given render object.
  47684. *
  47685. * @param {RenderObject} object - The render object.
  47686. * @param {Renderer} renderer - The renderer.
  47687. * @return {GLSLNodeBuilder} The node builder.
  47688. */
  47689. createNodeBuilder( object, renderer ) {
  47690. return new GLSLNodeBuilder( object, renderer );
  47691. }
  47692. // program
  47693. /**
  47694. * Creates a shader program from the given programmable stage.
  47695. *
  47696. * @param {ProgrammableStage} program - The programmable stage.
  47697. */
  47698. createProgram( program ) {
  47699. const gl = this.gl;
  47700. const { stage, code } = program;
  47701. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  47702. gl.shaderSource( shader, code );
  47703. gl.compileShader( shader );
  47704. this.set( program, {
  47705. shaderGPU: shader
  47706. } );
  47707. }
  47708. /**
  47709. * Destroys the shader program of the given programmable stage.
  47710. *
  47711. * @param {ProgrammableStage} program - The programmable stage.
  47712. */
  47713. destroyProgram( program ) {
  47714. this.delete( program );
  47715. }
  47716. /**
  47717. * Creates a render pipeline for the given render object.
  47718. *
  47719. * @param {RenderObject} renderObject - The render object.
  47720. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47721. */
  47722. createRenderPipeline( renderObject, promises ) {
  47723. const gl = this.gl;
  47724. const pipeline = renderObject.pipeline;
  47725. // Program
  47726. const { fragmentProgram, vertexProgram } = pipeline;
  47727. const programGPU = gl.createProgram();
  47728. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47729. const vertexShader = this.get( vertexProgram ).shaderGPU;
  47730. gl.attachShader( programGPU, fragmentShader );
  47731. gl.attachShader( programGPU, vertexShader );
  47732. gl.linkProgram( programGPU );
  47733. this.set( pipeline, {
  47734. programGPU,
  47735. fragmentShader,
  47736. vertexShader
  47737. } );
  47738. if ( promises !== null && this.parallel ) {
  47739. const p = new Promise( ( resolve /*, reject*/ ) => {
  47740. const parallel = this.parallel;
  47741. const checkStatus = () => {
  47742. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  47743. this._completeCompile( renderObject, pipeline );
  47744. resolve();
  47745. } else {
  47746. requestAnimationFrame( checkStatus );
  47747. }
  47748. };
  47749. checkStatus();
  47750. } );
  47751. promises.push( p );
  47752. return;
  47753. }
  47754. this._completeCompile( renderObject, pipeline );
  47755. }
  47756. /**
  47757. * Formats the source code of error messages.
  47758. *
  47759. * @private
  47760. * @param {string} string - The code.
  47761. * @param {number} errorLine - The error line.
  47762. * @return {string} The formatted code.
  47763. */
  47764. _handleSource( string, errorLine ) {
  47765. const lines = string.split( '\n' );
  47766. const lines2 = [];
  47767. const from = Math.max( errorLine - 6, 0 );
  47768. const to = Math.min( errorLine + 6, lines.length );
  47769. for ( let i = from; i < to; i ++ ) {
  47770. const line = i + 1;
  47771. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  47772. }
  47773. return lines2.join( '\n' );
  47774. }
  47775. /**
  47776. * Gets the shader compilation errors from the info log.
  47777. *
  47778. * @private
  47779. * @param {WebGL2RenderingContext} gl - The rendering context.
  47780. * @param {WebGLShader} shader - The WebGL shader object.
  47781. * @param {string} type - The shader type.
  47782. * @return {string} The shader errors.
  47783. */
  47784. _getShaderErrors( gl, shader, type ) {
  47785. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  47786. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  47787. const errors = shaderInfoLog.trim();
  47788. if ( status && errors === '' ) return '';
  47789. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  47790. if ( errorMatches ) {
  47791. const errorLine = parseInt( errorMatches[ 1 ] );
  47792. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  47793. } else {
  47794. return errors;
  47795. }
  47796. }
  47797. /**
  47798. * Logs shader compilation errors.
  47799. *
  47800. * @private
  47801. * @param {WebGLProgram} programGPU - The WebGL program.
  47802. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  47803. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  47804. */
  47805. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  47806. if ( this.renderer.debug.checkShaderErrors ) {
  47807. const gl = this.gl;
  47808. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  47809. const programLog = programInfoLog.trim();
  47810. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47811. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  47812. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  47813. } else {
  47814. // default error reporting
  47815. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  47816. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  47817. error(
  47818. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47819. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  47820. 'Program Info Log: ' + programLog + '\n' +
  47821. vertexErrors + '\n' +
  47822. fragmentErrors
  47823. );
  47824. }
  47825. } else if ( programLog !== '' ) {
  47826. warn( 'WebGLProgram: Program Info Log:', programLog );
  47827. }
  47828. }
  47829. }
  47830. /**
  47831. * Completes the shader program setup for the given render object.
  47832. *
  47833. * @private
  47834. * @param {RenderObject} renderObject - The render object.
  47835. * @param {RenderPipeline} pipeline - The render pipeline.
  47836. */
  47837. _completeCompile( renderObject, pipeline ) {
  47838. const { state, gl } = this;
  47839. const pipelineData = this.get( pipeline );
  47840. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  47841. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47842. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47843. }
  47844. state.useProgram( programGPU );
  47845. // Bindings
  47846. const bindings = renderObject.getBindings();
  47847. this._setupBindings( bindings, programGPU );
  47848. //
  47849. this.set( pipeline, {
  47850. programGPU
  47851. } );
  47852. }
  47853. /**
  47854. * Creates a compute pipeline for the given compute node.
  47855. *
  47856. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47857. * @param {Array<BindGroup>} bindings - The bindings.
  47858. */
  47859. createComputePipeline( computePipeline, bindings ) {
  47860. const { state, gl } = this;
  47861. // Program
  47862. const fragmentProgram = {
  47863. stage: 'fragment',
  47864. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  47865. };
  47866. this.createProgram( fragmentProgram );
  47867. const { computeProgram } = computePipeline;
  47868. const programGPU = gl.createProgram();
  47869. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47870. const vertexShader = this.get( computeProgram ).shaderGPU;
  47871. const transforms = computeProgram.transforms;
  47872. const transformVaryingNames = [];
  47873. const transformAttributeNodes = [];
  47874. for ( let i = 0; i < transforms.length; i ++ ) {
  47875. const transform = transforms[ i ];
  47876. transformVaryingNames.push( transform.varyingName );
  47877. transformAttributeNodes.push( transform.attributeNode );
  47878. }
  47879. gl.attachShader( programGPU, fragmentShader );
  47880. gl.attachShader( programGPU, vertexShader );
  47881. gl.transformFeedbackVaryings(
  47882. programGPU,
  47883. transformVaryingNames,
  47884. gl.SEPARATE_ATTRIBS
  47885. );
  47886. gl.linkProgram( programGPU );
  47887. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47888. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47889. }
  47890. state.useProgram( programGPU );
  47891. // Bindings
  47892. this._setupBindings( bindings, programGPU );
  47893. const attributeNodes = computeProgram.attributes;
  47894. const attributes = [];
  47895. const transformBuffers = [];
  47896. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  47897. const attribute = attributeNodes[ i ].node.attribute;
  47898. attributes.push( attribute );
  47899. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47900. }
  47901. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  47902. const attribute = transformAttributeNodes[ i ].attribute;
  47903. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47904. const attributeData = this.get( attribute );
  47905. transformBuffers.push( attributeData );
  47906. }
  47907. //
  47908. this.set( computePipeline, {
  47909. programGPU,
  47910. transformBuffers,
  47911. attributes
  47912. } );
  47913. }
  47914. /**
  47915. * Creates bindings from the given bind group definition.
  47916. *
  47917. * @param {BindGroup} bindGroup - The bind group.
  47918. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47919. * @param {number} cacheIndex - The cache index.
  47920. * @param {number} version - The version.
  47921. */
  47922. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  47923. if ( this._knownBindings.has( bindings ) === false ) {
  47924. this._knownBindings.add( bindings );
  47925. let uniformBuffers = 0;
  47926. let textures = 0;
  47927. for ( const bindGroup of bindings ) {
  47928. this.set( bindGroup, {
  47929. textures: textures,
  47930. uniformBuffers: uniformBuffers
  47931. } );
  47932. for ( const binding of bindGroup.bindings ) {
  47933. if ( binding.isUniformBuffer ) uniformBuffers ++;
  47934. if ( binding.isSampledTexture ) textures ++;
  47935. }
  47936. }
  47937. }
  47938. this.updateBindings( bindGroup, bindings );
  47939. }
  47940. /**
  47941. * Updates the given bind group definition.
  47942. *
  47943. * @param {BindGroup} bindGroup - The bind group.
  47944. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47945. * @param {number} cacheIndex - The cache index.
  47946. * @param {number} version - The version.
  47947. */
  47948. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  47949. const { gl } = this;
  47950. const bindGroupData = this.get( bindGroup );
  47951. let i = bindGroupData.uniformBuffers;
  47952. let t = bindGroupData.textures;
  47953. for ( const binding of bindGroup.bindings ) {
  47954. const map = this.get( binding );
  47955. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47956. const data = binding.buffer;
  47957. let { bufferGPU } = this.get( data );
  47958. if ( bufferGPU === undefined ) {
  47959. // create
  47960. bufferGPU = gl.createBuffer();
  47961. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47962. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47963. this.set( data, { bufferGPU } );
  47964. } else {
  47965. // update
  47966. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47967. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  47968. }
  47969. map.index = i ++;
  47970. map.bufferGPU = bufferGPU;
  47971. this.set( binding, map );
  47972. } else if ( binding.isSampledTexture ) {
  47973. const { textureGPU, glTextureType } = this.get( binding.texture );
  47974. map.index = t ++;
  47975. map.textureGPU = textureGPU;
  47976. map.glTextureType = glTextureType;
  47977. this.set( binding, map );
  47978. }
  47979. }
  47980. }
  47981. /**
  47982. * Updates a buffer binding.
  47983. *
  47984. * @param {Buffer} binding - The buffer binding to update.
  47985. */
  47986. updateBinding( binding ) {
  47987. const gl = this.gl;
  47988. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47989. const bindingData = this.get( binding );
  47990. const bufferGPU = bindingData.bufferGPU;
  47991. const data = binding.buffer;
  47992. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47993. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47994. }
  47995. }
  47996. // attributes
  47997. /**
  47998. * Creates the GPU buffer of an indexed shader attribute.
  47999. *
  48000. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48001. */
  48002. createIndexAttribute( attribute ) {
  48003. const gl = this.gl;
  48004. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  48005. }
  48006. /**
  48007. * Creates the GPU buffer of a shader attribute.
  48008. *
  48009. * @param {BufferAttribute} attribute - The buffer attribute.
  48010. */
  48011. createAttribute( attribute ) {
  48012. if ( this.has( attribute ) ) return;
  48013. const gl = this.gl;
  48014. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48015. }
  48016. /**
  48017. * Creates the GPU buffer of a storage attribute.
  48018. *
  48019. * @param {BufferAttribute} attribute - The buffer attribute.
  48020. */
  48021. createStorageAttribute( attribute ) {
  48022. if ( this.has( attribute ) ) return;
  48023. const gl = this.gl;
  48024. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48025. }
  48026. /**
  48027. * Updates the GPU buffer of a shader attribute.
  48028. *
  48029. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48030. */
  48031. updateAttribute( attribute ) {
  48032. this.attributeUtils.updateAttribute( attribute );
  48033. }
  48034. /**
  48035. * Destroys the GPU buffer of a shader attribute.
  48036. *
  48037. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48038. */
  48039. destroyAttribute( attribute ) {
  48040. this.attributeUtils.destroyAttribute( attribute );
  48041. }
  48042. /**
  48043. * Checks if the given feature is supported by the backend.
  48044. *
  48045. * @param {string} name - The feature's name.
  48046. * @return {boolean} Whether the feature is supported or not.
  48047. */
  48048. hasFeature( name ) {
  48049. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  48050. const extensions = this.extensions;
  48051. for ( let i = 0; i < keysMatching.length; i ++ ) {
  48052. if ( extensions.has( keysMatching[ i ] ) ) return true;
  48053. }
  48054. return false;
  48055. }
  48056. /**
  48057. * Returns the maximum anisotropy texture filtering value.
  48058. *
  48059. * @return {number} The maximum anisotropy texture filtering value.
  48060. */
  48061. getMaxAnisotropy() {
  48062. return this.capabilities.getMaxAnisotropy();
  48063. }
  48064. /**
  48065. * Copies data of the given source texture to the given destination texture.
  48066. *
  48067. * @param {Texture} srcTexture - The source texture.
  48068. * @param {Texture} dstTexture - The destination texture.
  48069. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48070. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48071. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48072. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48073. */
  48074. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48075. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  48076. }
  48077. /**
  48078. * Copies the current bound framebuffer to the given texture.
  48079. *
  48080. * @param {Texture} texture - The destination texture.
  48081. * @param {RenderContext} renderContext - The render context.
  48082. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48083. */
  48084. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48085. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  48086. }
  48087. /**
  48088. * Configures the active framebuffer from the given render context.
  48089. *
  48090. * @private
  48091. * @param {RenderContext} descriptor - The render context.
  48092. */
  48093. _setFramebuffer( descriptor ) {
  48094. const { gl, state } = this;
  48095. let currentFrameBuffer = null;
  48096. if ( descriptor.textures !== null ) {
  48097. const renderTarget = descriptor.renderTarget;
  48098. const renderTargetContextData = this.get( renderTarget );
  48099. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  48100. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  48101. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  48102. const isRenderTargetArray = renderTarget.depth > 1;
  48103. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  48104. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  48105. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  48106. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  48107. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48108. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  48109. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  48110. const cacheKey = getCacheKey( descriptor );
  48111. let fb;
  48112. if ( isCube ) {
  48113. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  48114. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  48115. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  48116. fb = this._xrFramebuffer;
  48117. } else {
  48118. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  48119. fb = renderTargetContextData.framebuffers[ cacheKey ];
  48120. }
  48121. if ( fb === undefined ) {
  48122. fb = gl.createFramebuffer();
  48123. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48124. const textures = descriptor.textures;
  48125. const depthInvalidationArray = [];
  48126. if ( isCube ) {
  48127. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  48128. const { textureGPU } = this.get( textures[ 0 ] );
  48129. const cubeFace = this.renderer._activeCubeFace;
  48130. const mipLevel = this.renderer._activeMipmapLevel;
  48131. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  48132. } else {
  48133. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  48134. for ( let i = 0; i < textures.length; i ++ ) {
  48135. const texture = textures[ i ];
  48136. const textureData = this.get( texture );
  48137. textureData.renderTarget = descriptor.renderTarget;
  48138. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48139. const attachment = gl.COLOR_ATTACHMENT0 + i;
  48140. if ( renderTarget.multiview ) {
  48141. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  48142. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  48143. const layer = this.renderer._activeCubeFace;
  48144. const mipLevel = this.renderer._activeMipmapLevel;
  48145. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  48146. } else {
  48147. if ( useMultisampledRTT ) {
  48148. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48149. } else {
  48150. const mipLevel = this.renderer._activeMipmapLevel;
  48151. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  48152. }
  48153. }
  48154. }
  48155. }
  48156. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48157. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48158. const renderbuffer = gl.createRenderbuffer();
  48159. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  48160. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  48161. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48162. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48163. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48164. } else {
  48165. if ( descriptor.depthTexture !== null ) {
  48166. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48167. const textureData = this.get( descriptor.depthTexture );
  48168. textureData.renderTarget = descriptor.renderTarget;
  48169. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48170. if ( renderTarget.multiview ) {
  48171. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48172. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  48173. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48174. } else {
  48175. if ( descriptor.depthTexture.isArrayTexture ) {
  48176. const layer = this.renderer._activeCubeFace;
  48177. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  48178. } else {
  48179. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48180. }
  48181. }
  48182. }
  48183. }
  48184. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  48185. } else {
  48186. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  48187. if ( isRenderCameraDepthArray ) {
  48188. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48189. const layer = this.renderer._activeCubeFace;
  48190. const depthData = this.get( descriptor.depthTexture );
  48191. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48192. gl.framebufferTextureLayer(
  48193. gl.FRAMEBUFFER,
  48194. depthStyle,
  48195. depthData.textureGPU,
  48196. 0,
  48197. layer
  48198. );
  48199. }
  48200. // rebind external XR textures
  48201. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  48202. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48203. // rebind color
  48204. const textureData = this.get( descriptor.textures[ 0 ] );
  48205. if ( renderTarget.multiview ) {
  48206. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  48207. } else if ( useMultisampledRTT ) {
  48208. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48209. } else {
  48210. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48211. }
  48212. // rebind depth
  48213. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48214. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48215. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  48216. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48217. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48218. } else {
  48219. const textureData = this.get( descriptor.depthTexture );
  48220. if ( renderTarget.multiview ) {
  48221. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48222. } else if ( useMultisampledRTT ) {
  48223. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48224. } else {
  48225. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48226. }
  48227. }
  48228. }
  48229. }
  48230. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  48231. if ( msaaFb === undefined ) {
  48232. const invalidationArray = [];
  48233. msaaFb = gl.createFramebuffer();
  48234. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  48235. const msaaRenderbuffers = [];
  48236. const textures = descriptor.textures;
  48237. for ( let i = 0; i < textures.length; i ++ ) {
  48238. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  48239. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48240. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  48241. const texture = descriptor.textures[ i ];
  48242. const textureData = this.get( texture );
  48243. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  48244. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48245. }
  48246. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48247. renderTargetContextData.msaaFrameBuffer = msaaFb;
  48248. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  48249. if ( depthBuffer && depthRenderbuffer === undefined ) {
  48250. depthRenderbuffer = gl.createRenderbuffer();
  48251. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  48252. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  48253. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48254. invalidationArray.push( depthStyle );
  48255. }
  48256. renderTargetContextData.invalidationArray = invalidationArray;
  48257. }
  48258. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48259. } else {
  48260. currentFrameBuffer = fb;
  48261. }
  48262. state.drawBuffers( descriptor, fb );
  48263. }
  48264. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  48265. }
  48266. /**
  48267. * Computes the VAO key for the given index and attributes.
  48268. *
  48269. * @private
  48270. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48271. * @return {string} The VAO key.
  48272. */
  48273. _getVaoKey( attributes ) {
  48274. let key = '';
  48275. for ( let i = 0; i < attributes.length; i ++ ) {
  48276. const attributeData = this.get( attributes[ i ] );
  48277. key += ':' + attributeData.id;
  48278. }
  48279. return key;
  48280. }
  48281. /**
  48282. * Creates a VAO from the index and attributes.
  48283. *
  48284. * @private
  48285. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48286. * @return {Object} The VAO data.
  48287. */
  48288. _createVao( attributes ) {
  48289. const { gl } = this;
  48290. const vaoGPU = gl.createVertexArray();
  48291. gl.bindVertexArray( vaoGPU );
  48292. for ( let i = 0; i < attributes.length; i ++ ) {
  48293. const attribute = attributes[ i ];
  48294. const attributeData = this.get( attribute );
  48295. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  48296. gl.enableVertexAttribArray( i );
  48297. let stride, offset;
  48298. if ( attribute.isInterleavedBufferAttribute === true ) {
  48299. stride = attribute.data.stride * attributeData.bytesPerElement;
  48300. offset = attribute.offset * attributeData.bytesPerElement;
  48301. } else {
  48302. stride = 0;
  48303. offset = 0;
  48304. }
  48305. if ( attributeData.isInteger ) {
  48306. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  48307. } else {
  48308. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  48309. }
  48310. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  48311. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  48312. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  48313. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  48314. }
  48315. }
  48316. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  48317. return vaoGPU;
  48318. }
  48319. /**
  48320. * Creates a transform feedback from the given transform buffers.
  48321. *
  48322. * @private
  48323. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  48324. * @return {WebGLTransformFeedback} The transform feedback.
  48325. */
  48326. _getTransformFeedback( transformBuffers ) {
  48327. let key = '';
  48328. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48329. key += ':' + transformBuffers[ i ].id;
  48330. }
  48331. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  48332. if ( transformFeedbackGPU !== undefined ) {
  48333. return transformFeedbackGPU;
  48334. }
  48335. const { gl } = this;
  48336. transformFeedbackGPU = gl.createTransformFeedback();
  48337. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48338. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48339. const attributeData = transformBuffers[ i ];
  48340. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  48341. }
  48342. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48343. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  48344. return transformFeedbackGPU;
  48345. }
  48346. /**
  48347. * Setups the given bindings.
  48348. *
  48349. * @private
  48350. * @param {Array<BindGroup>} bindings - The bindings.
  48351. * @param {WebGLProgram} programGPU - The WebGL program.
  48352. */
  48353. _setupBindings( bindings, programGPU ) {
  48354. const gl = this.gl;
  48355. for ( const bindGroup of bindings ) {
  48356. for ( const binding of bindGroup.bindings ) {
  48357. const bindingData = this.get( binding );
  48358. const index = bindingData.index;
  48359. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48360. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  48361. gl.uniformBlockBinding( programGPU, location, index );
  48362. } else if ( binding.isSampledTexture ) {
  48363. const location = gl.getUniformLocation( programGPU, binding.name );
  48364. gl.uniform1i( location, index );
  48365. }
  48366. }
  48367. }
  48368. }
  48369. /**
  48370. * Binds the given uniforms.
  48371. *
  48372. * @private
  48373. * @param {Array<BindGroup>} bindings - The bindings.
  48374. */
  48375. _bindUniforms( bindings ) {
  48376. const { gl, state } = this;
  48377. for ( const bindGroup of bindings ) {
  48378. for ( const binding of bindGroup.bindings ) {
  48379. const bindingData = this.get( binding );
  48380. const index = bindingData.index;
  48381. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48382. // TODO USE bindBufferRange to group multiple uniform buffers
  48383. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  48384. } else if ( binding.isSampledTexture ) {
  48385. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  48386. }
  48387. }
  48388. }
  48389. }
  48390. /**
  48391. * The method ensures multisampled render targets are resolved.
  48392. *
  48393. * @private
  48394. * @param {RenderContext} renderContext - The render context.
  48395. */
  48396. _resolveRenderTarget( renderContext ) {
  48397. const { gl, state } = this;
  48398. const renderTarget = renderContext.renderTarget;
  48399. if ( renderContext.textures !== null && renderTarget ) {
  48400. const renderTargetContextData = this.get( renderTarget );
  48401. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  48402. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48403. let mask = gl.COLOR_BUFFER_BIT;
  48404. if ( renderTarget.resolveDepthBuffer ) {
  48405. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  48406. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  48407. }
  48408. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48409. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  48410. const textures = renderContext.textures;
  48411. const isMRT = textures.length > 1;
  48412. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48413. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48414. if ( isMRT ) {
  48415. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  48416. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  48417. for ( let i = 0; i < textures.length; i ++ ) {
  48418. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  48419. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  48420. }
  48421. }
  48422. for ( let i = 0; i < textures.length; i ++ ) {
  48423. if ( isMRT ) {
  48424. // configure attachment for resolve
  48425. const { textureGPU } = this.get( textures[ i ] );
  48426. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48427. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  48428. }
  48429. if ( renderContext.scissor ) {
  48430. const { x, y, width, height } = renderContext.scissorValue;
  48431. const viewY = renderContext.height - height - y;
  48432. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  48433. } else {
  48434. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  48435. }
  48436. }
  48437. if ( isMRT ) {
  48438. // restore attachments
  48439. for ( let i = 0; i < textures.length; i ++ ) {
  48440. const { textureGPU } = this.get( textures[ i ] );
  48441. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48442. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  48443. }
  48444. }
  48445. if ( this._supportsInvalidateFramebuffer === true ) {
  48446. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  48447. }
  48448. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  48449. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48450. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48451. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  48452. }
  48453. }
  48454. }
  48455. /**
  48456. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  48457. * should be used when MSAA is enabled.
  48458. *
  48459. * @private
  48460. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  48461. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  48462. */
  48463. _useMultisampledExtension( renderTarget ) {
  48464. if ( renderTarget.multiview === true ) {
  48465. return true;
  48466. }
  48467. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  48468. }
  48469. /**
  48470. * Frees internal resources.
  48471. */
  48472. dispose() {
  48473. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  48474. const extension = this.extensions.get( 'WEBGL_lose_context' );
  48475. if ( extension ) extension.loseContext();
  48476. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  48477. }
  48478. }
  48479. const GPUPrimitiveTopology = {
  48480. PointList: 'point-list',
  48481. LineList: 'line-list',
  48482. LineStrip: 'line-strip',
  48483. TriangleList: 'triangle-list',
  48484. TriangleStrip: 'triangle-strip',
  48485. };
  48486. const GPUCompareFunction = {
  48487. Never: 'never',
  48488. Less: 'less',
  48489. Equal: 'equal',
  48490. LessEqual: 'less-equal',
  48491. Greater: 'greater',
  48492. NotEqual: 'not-equal',
  48493. GreaterEqual: 'greater-equal',
  48494. Always: 'always'
  48495. };
  48496. const GPUStoreOp = {
  48497. Store: 'store'};
  48498. const GPULoadOp = {
  48499. Load: 'load',
  48500. Clear: 'clear'
  48501. };
  48502. const GPUFrontFace = {
  48503. CCW: 'ccw',
  48504. CW: 'cw'
  48505. };
  48506. const GPUCullMode = {
  48507. None: 'none',
  48508. Back: 'back'
  48509. };
  48510. const GPUIndexFormat = {
  48511. Uint16: 'uint16',
  48512. Uint32: 'uint32'
  48513. };
  48514. const GPUTextureFormat = {
  48515. // 8-bit formats
  48516. R8Unorm: 'r8unorm',
  48517. R8Snorm: 'r8snorm',
  48518. R8Uint: 'r8uint',
  48519. R8Sint: 'r8sint',
  48520. // 16-bit formats
  48521. R16Uint: 'r16uint',
  48522. R16Sint: 'r16sint',
  48523. R16Float: 'r16float',
  48524. RG8Unorm: 'rg8unorm',
  48525. RG8Snorm: 'rg8snorm',
  48526. RG8Uint: 'rg8uint',
  48527. RG8Sint: 'rg8sint',
  48528. // 32-bit formats
  48529. R32Uint: 'r32uint',
  48530. R32Sint: 'r32sint',
  48531. R32Float: 'r32float',
  48532. RG16Uint: 'rg16uint',
  48533. RG16Sint: 'rg16sint',
  48534. RG16Float: 'rg16float',
  48535. RGBA8Unorm: 'rgba8unorm',
  48536. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  48537. RGBA8Snorm: 'rgba8snorm',
  48538. RGBA8Uint: 'rgba8uint',
  48539. RGBA8Sint: 'rgba8sint',
  48540. BGRA8Unorm: 'bgra8unorm',
  48541. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  48542. // Packed 32-bit formats
  48543. RGB9E5UFloat: 'rgb9e5ufloat',
  48544. RGB10A2Unorm: 'rgb10a2unorm',
  48545. RG11B10UFloat: 'rg11b10ufloat',
  48546. // 64-bit formats
  48547. RG32Uint: 'rg32uint',
  48548. RG32Sint: 'rg32sint',
  48549. RG32Float: 'rg32float',
  48550. RGBA16Uint: 'rgba16uint',
  48551. RGBA16Sint: 'rgba16sint',
  48552. RGBA16Float: 'rgba16float',
  48553. // 128-bit formats
  48554. RGBA32Uint: 'rgba32uint',
  48555. RGBA32Sint: 'rgba32sint',
  48556. RGBA32Float: 'rgba32float',
  48557. Depth16Unorm: 'depth16unorm',
  48558. Depth24Plus: 'depth24plus',
  48559. Depth24PlusStencil8: 'depth24plus-stencil8',
  48560. Depth32Float: 'depth32float',
  48561. // 'depth32float-stencil8' extension
  48562. Depth32FloatStencil8: 'depth32float-stencil8',
  48563. // BC compressed formats usable if 'texture-compression-bc' is both
  48564. // supported by the device/user agent and enabled in requestDevice.
  48565. BC1RGBAUnorm: 'bc1-rgba-unorm',
  48566. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  48567. BC2RGBAUnorm: 'bc2-rgba-unorm',
  48568. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  48569. BC3RGBAUnorm: 'bc3-rgba-unorm',
  48570. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  48571. BC4RUnorm: 'bc4-r-unorm',
  48572. BC4RSnorm: 'bc4-r-snorm',
  48573. BC5RGUnorm: 'bc5-rg-unorm',
  48574. BC5RGSnorm: 'bc5-rg-snorm',
  48575. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  48576. BC6HRGBFloat: 'bc6h-rgb-float',
  48577. BC7RGBAUnorm: 'bc7-rgba-unorm',
  48578. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  48579. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  48580. // supported by the device/user agent and enabled in requestDevice.
  48581. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  48582. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  48583. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  48584. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  48585. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  48586. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  48587. EACR11Unorm: 'eac-r11unorm',
  48588. EACR11Snorm: 'eac-r11snorm',
  48589. EACRG11Unorm: 'eac-rg11unorm',
  48590. EACRG11Snorm: 'eac-rg11snorm',
  48591. // ASTC compressed formats usable if 'texture-compression-astc' is both
  48592. // supported by the device/user agent and enabled in requestDevice.
  48593. ASTC4x4Unorm: 'astc-4x4-unorm',
  48594. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  48595. ASTC5x4Unorm: 'astc-5x4-unorm',
  48596. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  48597. ASTC5x5Unorm: 'astc-5x5-unorm',
  48598. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  48599. ASTC6x5Unorm: 'astc-6x5-unorm',
  48600. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  48601. ASTC6x6Unorm: 'astc-6x6-unorm',
  48602. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  48603. ASTC8x5Unorm: 'astc-8x5-unorm',
  48604. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  48605. ASTC8x6Unorm: 'astc-8x6-unorm',
  48606. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  48607. ASTC8x8Unorm: 'astc-8x8-unorm',
  48608. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  48609. ASTC10x5Unorm: 'astc-10x5-unorm',
  48610. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  48611. ASTC10x6Unorm: 'astc-10x6-unorm',
  48612. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  48613. ASTC10x8Unorm: 'astc-10x8-unorm',
  48614. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  48615. ASTC10x10Unorm: 'astc-10x10-unorm',
  48616. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  48617. ASTC12x10Unorm: 'astc-12x10-unorm',
  48618. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  48619. ASTC12x12Unorm: 'astc-12x12-unorm',
  48620. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  48621. };
  48622. const GPUAddressMode = {
  48623. ClampToEdge: 'clamp-to-edge',
  48624. Repeat: 'repeat',
  48625. MirrorRepeat: 'mirror-repeat'
  48626. };
  48627. const GPUFilterMode = {
  48628. Linear: 'linear',
  48629. Nearest: 'nearest'
  48630. };
  48631. const GPUBlendFactor = {
  48632. Zero: 'zero',
  48633. One: 'one',
  48634. Src: 'src',
  48635. OneMinusSrc: 'one-minus-src',
  48636. SrcAlpha: 'src-alpha',
  48637. OneMinusSrcAlpha: 'one-minus-src-alpha',
  48638. Dst: 'dst',
  48639. OneMinusDst: 'one-minus-dst',
  48640. DstAlpha: 'dst-alpha',
  48641. OneMinusDstAlpha: 'one-minus-dst-alpha',
  48642. SrcAlphaSaturated: 'src-alpha-saturated',
  48643. Constant: 'constant',
  48644. OneMinusConstant: 'one-minus-constant'
  48645. };
  48646. const GPUBlendOperation = {
  48647. Add: 'add',
  48648. Subtract: 'subtract',
  48649. ReverseSubtract: 'reverse-subtract',
  48650. Min: 'min',
  48651. Max: 'max'
  48652. };
  48653. const GPUColorWriteFlags = {
  48654. None: 0,
  48655. All: 0xF
  48656. };
  48657. const GPUStencilOperation = {
  48658. Keep: 'keep',
  48659. Zero: 'zero',
  48660. Replace: 'replace',
  48661. Invert: 'invert',
  48662. IncrementClamp: 'increment-clamp',
  48663. DecrementClamp: 'decrement-clamp',
  48664. IncrementWrap: 'increment-wrap',
  48665. DecrementWrap: 'decrement-wrap'
  48666. };
  48667. const GPUBufferBindingType = {
  48668. Storage: 'storage',
  48669. ReadOnlyStorage: 'read-only-storage'
  48670. };
  48671. const GPUStorageTextureAccess = {
  48672. WriteOnly: 'write-only',
  48673. ReadOnly: 'read-only',
  48674. ReadWrite: 'read-write',
  48675. };
  48676. const GPUSamplerBindingType = {
  48677. NonFiltering: 'non-filtering',
  48678. Comparison: 'comparison'
  48679. };
  48680. const GPUTextureSampleType = {
  48681. Float: 'float',
  48682. UnfilterableFloat: 'unfilterable-float',
  48683. Depth: 'depth',
  48684. SInt: 'sint',
  48685. UInt: 'uint'
  48686. };
  48687. const GPUTextureDimension = {
  48688. TwoD: '2d',
  48689. ThreeD: '3d'
  48690. };
  48691. const GPUTextureViewDimension = {
  48692. TwoD: '2d',
  48693. TwoDArray: '2d-array',
  48694. Cube: 'cube',
  48695. ThreeD: '3d'
  48696. };
  48697. const GPUTextureAspect = {
  48698. All: 'all'};
  48699. const GPUInputStepMode = {
  48700. Vertex: 'vertex',
  48701. Instance: 'instance'
  48702. };
  48703. const GPUFeatureName = {
  48704. CoreFeaturesAndLimits: 'core-features-and-limits',
  48705. DepthClipControl: 'depth-clip-control',
  48706. Depth32FloatStencil8: 'depth32float-stencil8',
  48707. TextureCompressionBC: 'texture-compression-bc',
  48708. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  48709. TextureCompressionETC2: 'texture-compression-etc2',
  48710. TextureCompressionASTC: 'texture-compression-astc',
  48711. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  48712. TimestampQuery: 'timestamp-query',
  48713. IndirectFirstInstance: 'indirect-first-instance',
  48714. ShaderF16: 'shader-f16',
  48715. RG11B10UFloat: 'rg11b10ufloat-renderable',
  48716. BGRA8UNormStorage: 'bgra8unorm-storage',
  48717. Float32Filterable: 'float32-filterable',
  48718. Float32Blendable: 'float32-blendable',
  48719. ClipDistances: 'clip-distances',
  48720. DualSourceBlending: 'dual-source-blending',
  48721. Subgroups: 'subgroups',
  48722. TextureFormatsTier1: 'texture-formats-tier1',
  48723. TextureFormatsTier2: 'texture-formats-tier2'
  48724. };
  48725. const GPUFeatureMap = {
  48726. 'texture-compression-s3tc': 'texture-compression-bc',
  48727. 'texture-compression-etc1': 'texture-compression-etc2'
  48728. };
  48729. /**
  48730. * A special form of sampler binding type.
  48731. * It's texture value is managed by a node object.
  48732. *
  48733. * @private
  48734. * @augments Sampler
  48735. */
  48736. class NodeSampler extends Sampler {
  48737. /**
  48738. * Constructs a new node-based sampler.
  48739. *
  48740. * @param {string} name - The samplers's name.
  48741. * @param {TextureNode} textureNode - The texture node.
  48742. * @param {UniformGroupNode} groupNode - The uniform group node.
  48743. */
  48744. constructor( name, textureNode, groupNode ) {
  48745. super( name, textureNode ? textureNode.value : null );
  48746. /**
  48747. * The texture node.
  48748. *
  48749. * @type {TextureNode}
  48750. */
  48751. this.textureNode = textureNode;
  48752. /**
  48753. * The uniform group node.
  48754. *
  48755. * @type {UniformGroupNode}
  48756. */
  48757. this.groupNode = groupNode;
  48758. }
  48759. /**
  48760. * Updates the texture value of this sampler.
  48761. *
  48762. * @return {boolean} Whether the sampler needs an update or not.
  48763. */
  48764. update() {
  48765. const { textureNode } = this;
  48766. if ( this.texture !== textureNode.value ) {
  48767. this.texture = textureNode.value;
  48768. return true;
  48769. }
  48770. return super.update();
  48771. }
  48772. }
  48773. /**
  48774. * Represents a storage buffer binding type.
  48775. *
  48776. * @private
  48777. * @augments Buffer
  48778. */
  48779. class StorageBuffer extends Buffer {
  48780. /**
  48781. * Constructs a new uniform buffer.
  48782. *
  48783. * @param {string} name - The buffer's name.
  48784. * @param {BufferAttribute} attribute - The buffer attribute.
  48785. */
  48786. constructor( name, attribute ) {
  48787. super( name, attribute ? attribute.array : null );
  48788. /**
  48789. * This flag can be used for type testing.
  48790. *
  48791. * @type {BufferAttribute}
  48792. */
  48793. this.attribute = attribute;
  48794. /**
  48795. * This flag can be used for type testing.
  48796. *
  48797. * @type {boolean}
  48798. * @readonly
  48799. * @default true
  48800. */
  48801. this.isStorageBuffer = true;
  48802. }
  48803. }
  48804. let _id = 0;
  48805. /**
  48806. * A special form of storage buffer binding type.
  48807. * It's buffer value is managed by a node object.
  48808. *
  48809. * @private
  48810. * @augments StorageBuffer
  48811. */
  48812. class NodeStorageBuffer extends StorageBuffer {
  48813. /**
  48814. * Constructs a new node-based storage buffer.
  48815. *
  48816. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  48817. * @param {UniformGroupNode} groupNode - The uniform group node.
  48818. */
  48819. constructor( nodeUniform, groupNode ) {
  48820. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  48821. /**
  48822. * The node uniform.
  48823. *
  48824. * @type {StorageBufferNode}
  48825. */
  48826. this.nodeUniform = nodeUniform;
  48827. /**
  48828. * The access type.
  48829. *
  48830. * @type {string}
  48831. */
  48832. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  48833. /**
  48834. * The uniform group node.
  48835. *
  48836. * @type {UniformGroupNode}
  48837. */
  48838. this.groupNode = groupNode;
  48839. }
  48840. /**
  48841. * The storage buffer.
  48842. *
  48843. * @type {BufferAttribute}
  48844. */
  48845. get buffer() {
  48846. return this.nodeUniform.value;
  48847. }
  48848. }
  48849. /**
  48850. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  48851. *
  48852. * @private
  48853. */
  48854. class WebGPUTexturePassUtils extends DataMap {
  48855. /**
  48856. * Constructs a new utility object.
  48857. *
  48858. * @param {GPUDevice} device - The WebGPU device.
  48859. */
  48860. constructor( device ) {
  48861. super();
  48862. /**
  48863. * The WebGPU device.
  48864. *
  48865. * @type {GPUDevice}
  48866. */
  48867. this.device = device;
  48868. const mipmapVertexSource = `
  48869. struct VarysStruct {
  48870. @builtin( position ) Position: vec4<f32>,
  48871. @location( 0 ) vTex : vec2<f32>
  48872. };
  48873. @vertex
  48874. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  48875. var Varys : VarysStruct;
  48876. var pos = array< vec2<f32>, 4 >(
  48877. vec2<f32>( -1.0, 1.0 ),
  48878. vec2<f32>( 1.0, 1.0 ),
  48879. vec2<f32>( -1.0, -1.0 ),
  48880. vec2<f32>( 1.0, -1.0 )
  48881. );
  48882. var tex = array< vec2<f32>, 4 >(
  48883. vec2<f32>( 0.0, 0.0 ),
  48884. vec2<f32>( 1.0, 0.0 ),
  48885. vec2<f32>( 0.0, 1.0 ),
  48886. vec2<f32>( 1.0, 1.0 )
  48887. );
  48888. Varys.vTex = tex[ vertexIndex ];
  48889. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  48890. return Varys;
  48891. }
  48892. `;
  48893. const mipmapFragmentSource = `
  48894. @group( 0 ) @binding( 0 )
  48895. var imgSampler : sampler;
  48896. @group( 0 ) @binding( 1 )
  48897. var img : texture_2d<f32>;
  48898. @fragment
  48899. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48900. return textureSample( img, imgSampler, vTex );
  48901. }
  48902. `;
  48903. const flipYFragmentSource = `
  48904. @group( 0 ) @binding( 0 )
  48905. var imgSampler : sampler;
  48906. @group( 0 ) @binding( 1 )
  48907. var img : texture_2d<f32>;
  48908. @fragment
  48909. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48910. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  48911. }
  48912. `;
  48913. /**
  48914. * The mipmap GPU sampler.
  48915. *
  48916. * @type {GPUSampler}
  48917. */
  48918. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  48919. /**
  48920. * The flipY GPU sampler.
  48921. *
  48922. * @type {GPUSampler}
  48923. */
  48924. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  48925. /**
  48926. * A cache for GPU render pipelines used for copy/transfer passes.
  48927. * Every texture format requires a unique pipeline.
  48928. *
  48929. * @type {Object<string,GPURenderPipeline>}
  48930. */
  48931. this.transferPipelines = {};
  48932. /**
  48933. * A cache for GPU render pipelines used for flipY passes.
  48934. * Every texture format requires a unique pipeline.
  48935. *
  48936. * @type {Object<string,GPURenderPipeline>}
  48937. */
  48938. this.flipYPipelines = {};
  48939. /**
  48940. * The mipmap vertex shader module.
  48941. *
  48942. * @type {GPUShaderModule}
  48943. */
  48944. this.mipmapVertexShaderModule = device.createShaderModule( {
  48945. label: 'mipmapVertex',
  48946. code: mipmapVertexSource
  48947. } );
  48948. /**
  48949. * The mipmap fragment shader module.
  48950. *
  48951. * @type {GPUShaderModule}
  48952. */
  48953. this.mipmapFragmentShaderModule = device.createShaderModule( {
  48954. label: 'mipmapFragment',
  48955. code: mipmapFragmentSource
  48956. } );
  48957. /**
  48958. * The flipY fragment shader module.
  48959. *
  48960. * @type {GPUShaderModule}
  48961. */
  48962. this.flipYFragmentShaderModule = device.createShaderModule( {
  48963. label: 'flipYFragment',
  48964. code: flipYFragmentSource
  48965. } );
  48966. }
  48967. /**
  48968. * Returns a render pipeline for the internal copy render pass. The pass
  48969. * requires a unique render pipeline for each texture format.
  48970. *
  48971. * @param {string} format - The GPU texture format
  48972. * @return {GPURenderPipeline} The GPU render pipeline.
  48973. */
  48974. getTransferPipeline( format ) {
  48975. let pipeline = this.transferPipelines[ format ];
  48976. if ( pipeline === undefined ) {
  48977. pipeline = this.device.createRenderPipeline( {
  48978. label: `mipmap-${ format }`,
  48979. vertex: {
  48980. module: this.mipmapVertexShaderModule,
  48981. entryPoint: 'main'
  48982. },
  48983. fragment: {
  48984. module: this.mipmapFragmentShaderModule,
  48985. entryPoint: 'main',
  48986. targets: [ { format } ]
  48987. },
  48988. primitive: {
  48989. topology: GPUPrimitiveTopology.TriangleStrip,
  48990. stripIndexFormat: GPUIndexFormat.Uint32
  48991. },
  48992. layout: 'auto'
  48993. } );
  48994. this.transferPipelines[ format ] = pipeline;
  48995. }
  48996. return pipeline;
  48997. }
  48998. /**
  48999. * Returns a render pipeline for the flipY render pass. The pass
  49000. * requires a unique render pipeline for each texture format.
  49001. *
  49002. * @param {string} format - The GPU texture format
  49003. * @return {GPURenderPipeline} The GPU render pipeline.
  49004. */
  49005. getFlipYPipeline( format ) {
  49006. let pipeline = this.flipYPipelines[ format ];
  49007. if ( pipeline === undefined ) {
  49008. pipeline = this.device.createRenderPipeline( {
  49009. label: `flipY-${ format }`,
  49010. vertex: {
  49011. module: this.mipmapVertexShaderModule,
  49012. entryPoint: 'main'
  49013. },
  49014. fragment: {
  49015. module: this.flipYFragmentShaderModule,
  49016. entryPoint: 'main',
  49017. targets: [ { format } ]
  49018. },
  49019. primitive: {
  49020. topology: GPUPrimitiveTopology.TriangleStrip,
  49021. stripIndexFormat: GPUIndexFormat.Uint32
  49022. },
  49023. layout: 'auto'
  49024. } );
  49025. this.flipYPipelines[ format ] = pipeline;
  49026. }
  49027. return pipeline;
  49028. }
  49029. /**
  49030. * Flip the contents of the given GPU texture along its vertical axis.
  49031. *
  49032. * @param {GPUTexture} textureGPU - The GPU texture object.
  49033. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49034. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49035. */
  49036. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  49037. const format = textureGPUDescriptor.format;
  49038. const { width, height } = textureGPUDescriptor.size;
  49039. const transferPipeline = this.getTransferPipeline( format );
  49040. const flipYPipeline = this.getFlipYPipeline( format );
  49041. const tempTexture = this.device.createTexture( {
  49042. size: { width, height, depthOrArrayLayers: 1 },
  49043. format,
  49044. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  49045. } );
  49046. const srcView = textureGPU.createView( {
  49047. baseMipLevel: 0,
  49048. mipLevelCount: 1,
  49049. dimension: GPUTextureViewDimension.TwoD,
  49050. baseArrayLayer
  49051. } );
  49052. const dstView = tempTexture.createView( {
  49053. baseMipLevel: 0,
  49054. mipLevelCount: 1,
  49055. dimension: GPUTextureViewDimension.TwoD,
  49056. baseArrayLayer: 0
  49057. } );
  49058. const commandEncoder = this.device.createCommandEncoder( {} );
  49059. const pass = ( pipeline, sourceView, destinationView ) => {
  49060. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49061. const bindGroup = this.device.createBindGroup( {
  49062. layout: bindGroupLayout,
  49063. entries: [ {
  49064. binding: 0,
  49065. resource: this.flipYSampler
  49066. }, {
  49067. binding: 1,
  49068. resource: sourceView
  49069. } ]
  49070. } );
  49071. const passEncoder = commandEncoder.beginRenderPass( {
  49072. colorAttachments: [ {
  49073. view: destinationView,
  49074. loadOp: GPULoadOp.Clear,
  49075. storeOp: GPUStoreOp.Store,
  49076. clearValue: [ 0, 0, 0, 0 ]
  49077. } ]
  49078. } );
  49079. passEncoder.setPipeline( pipeline );
  49080. passEncoder.setBindGroup( 0, bindGroup );
  49081. passEncoder.draw( 4, 1, 0, 0 );
  49082. passEncoder.end();
  49083. };
  49084. pass( transferPipeline, srcView, dstView );
  49085. pass( flipYPipeline, dstView, srcView );
  49086. this.device.queue.submit( [ commandEncoder.finish() ] );
  49087. tempTexture.destroy();
  49088. }
  49089. /**
  49090. * Generates mipmaps for the given GPU texture.
  49091. *
  49092. * @param {GPUTexture} textureGPU - The GPU texture object.
  49093. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49094. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49095. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49096. */
  49097. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  49098. const textureData = this.get( textureGPU );
  49099. if ( textureData.layers === undefined ) {
  49100. textureData.layers = [];
  49101. }
  49102. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  49103. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  49104. this._mipmapRunBundles( commandEncoder, passes );
  49105. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  49106. textureData.layers[ baseArrayLayer ] = passes;
  49107. }
  49108. /**
  49109. * Since multiple copy render passes are required to generate mipmaps, the passes
  49110. * are managed as render bundles to improve performance.
  49111. *
  49112. * @param {GPUTexture} textureGPU - The GPU texture object.
  49113. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49114. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  49115. * @return {Array<Object>} An array of render bundles.
  49116. */
  49117. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  49118. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  49119. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49120. let srcView = textureGPU.createView( {
  49121. baseMipLevel: 0,
  49122. mipLevelCount: 1,
  49123. dimension: GPUTextureViewDimension.TwoD,
  49124. baseArrayLayer
  49125. } );
  49126. const passes = [];
  49127. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  49128. const bindGroup = this.device.createBindGroup( {
  49129. layout: bindGroupLayout,
  49130. entries: [ {
  49131. binding: 0,
  49132. resource: this.mipmapSampler
  49133. }, {
  49134. binding: 1,
  49135. resource: srcView
  49136. } ]
  49137. } );
  49138. const dstView = textureGPU.createView( {
  49139. baseMipLevel: i,
  49140. mipLevelCount: 1,
  49141. dimension: GPUTextureViewDimension.TwoD,
  49142. baseArrayLayer
  49143. } );
  49144. const passDescriptor = {
  49145. colorAttachments: [ {
  49146. view: dstView,
  49147. loadOp: GPULoadOp.Clear,
  49148. storeOp: GPUStoreOp.Store,
  49149. clearValue: [ 0, 0, 0, 0 ]
  49150. } ]
  49151. };
  49152. const passEncoder = this.device.createRenderBundleEncoder( {
  49153. colorFormats: [ textureGPUDescriptor.format ]
  49154. } );
  49155. passEncoder.setPipeline( pipeline );
  49156. passEncoder.setBindGroup( 0, bindGroup );
  49157. passEncoder.draw( 4, 1, 0, 0 );
  49158. passes.push( {
  49159. renderBundles: [ passEncoder.finish() ],
  49160. passDescriptor
  49161. } );
  49162. srcView = dstView;
  49163. }
  49164. return passes;
  49165. }
  49166. /**
  49167. * Executes the render bundles.
  49168. *
  49169. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  49170. * @param {Array<Object>} passes - An array of render bundles.
  49171. */
  49172. _mipmapRunBundles( commandEncoder, passes ) {
  49173. const levels = passes.length;
  49174. for ( let i = 0; i < levels; i ++ ) {
  49175. const pass = passes[ i ];
  49176. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  49177. passEncoder.executeBundles( pass.renderBundles );
  49178. passEncoder.end();
  49179. }
  49180. }
  49181. }
  49182. const _compareToWebGPU = {
  49183. [ NeverCompare ]: 'never',
  49184. [ LessCompare ]: 'less',
  49185. [ EqualCompare ]: 'equal',
  49186. [ LessEqualCompare ]: 'less-equal',
  49187. [ GreaterCompare ]: 'greater',
  49188. [ GreaterEqualCompare ]: 'greater-equal',
  49189. [ AlwaysCompare ]: 'always',
  49190. [ NotEqualCompare ]: 'not-equal'
  49191. };
  49192. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  49193. /**
  49194. * A WebGPU backend utility module for managing textures.
  49195. *
  49196. * @private
  49197. */
  49198. class WebGPUTextureUtils {
  49199. /**
  49200. * Constructs a new utility object.
  49201. *
  49202. * @param {WebGPUBackend} backend - The WebGPU backend.
  49203. */
  49204. constructor( backend ) {
  49205. /**
  49206. * A reference to the WebGPU backend.
  49207. *
  49208. * @type {WebGPUBackend}
  49209. */
  49210. this.backend = backend;
  49211. /**
  49212. * A reference to the pass utils.
  49213. *
  49214. * @type {?WebGPUTexturePassUtils}
  49215. * @default null
  49216. */
  49217. this._passUtils = null;
  49218. /**
  49219. * A dictionary for managing default textures. The key
  49220. * is the texture format, the value the texture object.
  49221. *
  49222. * @type {Object<string,Texture>}
  49223. */
  49224. this.defaultTexture = {};
  49225. /**
  49226. * A dictionary for managing default cube textures. The key
  49227. * is the texture format, the value the texture object.
  49228. *
  49229. * @type {Object<string,CubeTexture>}
  49230. */
  49231. this.defaultCubeTexture = {};
  49232. /**
  49233. * A default video frame.
  49234. *
  49235. * @type {?VideoFrame}
  49236. * @default null
  49237. */
  49238. this.defaultVideoFrame = null;
  49239. /**
  49240. * A cache of shared texture samplers.
  49241. *
  49242. * @type {Map<string, Object>}
  49243. */
  49244. this._samplerCache = new Map();
  49245. }
  49246. /**
  49247. * Creates a GPU sampler for the given texture.
  49248. *
  49249. * @param {Texture} texture - The texture to create the sampler for.
  49250. * @return {string} The current sampler key.
  49251. */
  49252. updateSampler( texture ) {
  49253. const backend = this.backend;
  49254. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  49255. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  49256. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  49257. let samplerData = this._samplerCache.get( samplerKey );
  49258. if ( samplerData === undefined ) {
  49259. const samplerDescriptorGPU = {
  49260. addressModeU: this._convertAddressMode( texture.wrapS ),
  49261. addressModeV: this._convertAddressMode( texture.wrapT ),
  49262. addressModeW: this._convertAddressMode( texture.wrapR ),
  49263. magFilter: this._convertFilterMode( texture.magFilter ),
  49264. minFilter: this._convertFilterMode( texture.minFilter ),
  49265. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  49266. maxAnisotropy: 1
  49267. };
  49268. // anisotropy can only be used when all filter modes are set to linear.
  49269. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  49270. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  49271. }
  49272. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  49273. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  49274. }
  49275. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  49276. samplerData = { sampler, usedTimes: 0 };
  49277. this._samplerCache.set( samplerKey, samplerData );
  49278. }
  49279. const textureData = backend.get( texture );
  49280. if ( textureData.sampler !== samplerData.sampler ) {
  49281. // check if previous sampler is unused so it can be deleted
  49282. if ( textureData.sampler !== undefined ) {
  49283. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  49284. oldSamplerData.usedTimes --;
  49285. if ( oldSamplerData.usedTimes === 0 ) {
  49286. this._samplerCache.delete( textureData.samplerKey );
  49287. }
  49288. }
  49289. // update to new sampler data
  49290. textureData.samplerKey = samplerKey;
  49291. textureData.sampler = samplerData.sampler;
  49292. samplerData.usedTimes ++;
  49293. }
  49294. return samplerKey;
  49295. }
  49296. /**
  49297. * Creates a default texture for the given texture that can be used
  49298. * as a placeholder until the actual texture is ready for usage.
  49299. *
  49300. * @param {Texture} texture - The texture to create a default texture for.
  49301. */
  49302. createDefaultTexture( texture ) {
  49303. let textureGPU;
  49304. const format = getFormat( texture );
  49305. if ( texture.isCubeTexture ) {
  49306. textureGPU = this._getDefaultCubeTextureGPU( format );
  49307. } else {
  49308. textureGPU = this._getDefaultTextureGPU( format );
  49309. }
  49310. this.backend.get( texture ).texture = textureGPU;
  49311. }
  49312. /**
  49313. * Defines a texture on the GPU for the given texture object.
  49314. *
  49315. * @param {Texture} texture - The texture.
  49316. * @param {Object} [options={}] - Optional configuration parameter.
  49317. */
  49318. createTexture( texture, options = {} ) {
  49319. const backend = this.backend;
  49320. const textureData = backend.get( texture );
  49321. if ( textureData.initialized ) {
  49322. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  49323. }
  49324. if ( texture.isExternalTexture ) {
  49325. textureData.texture = texture.sourceTexture;
  49326. textureData.initialized = true;
  49327. return;
  49328. }
  49329. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  49330. if ( options.levels === undefined ) options.levels = 1;
  49331. if ( options.depth === undefined ) options.depth = 1;
  49332. const { width, height, depth, levels } = options;
  49333. if ( texture.isFramebufferTexture ) {
  49334. if ( options.renderTarget ) {
  49335. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  49336. } else {
  49337. options.format = this.backend.utils.getPreferredCanvasFormat();
  49338. }
  49339. }
  49340. const dimension = this._getDimension( texture );
  49341. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  49342. textureData.format = format;
  49343. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  49344. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  49345. if ( texture.isStorageTexture === true ) {
  49346. usage |= GPUTextureUsage.STORAGE_BINDING;
  49347. }
  49348. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  49349. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  49350. }
  49351. const textureDescriptorGPU = {
  49352. label: texture.name,
  49353. size: {
  49354. width: width,
  49355. height: height,
  49356. depthOrArrayLayers: depth,
  49357. },
  49358. mipLevelCount: levels,
  49359. sampleCount: primarySamples,
  49360. dimension: dimension,
  49361. format: format,
  49362. usage: usage
  49363. };
  49364. // texture creation
  49365. if ( format === undefined ) {
  49366. warn( 'WebGPURenderer: Texture format not supported.' );
  49367. this.createDefaultTexture( texture );
  49368. return;
  49369. }
  49370. if ( texture.isCubeTexture ) {
  49371. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  49372. }
  49373. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  49374. if ( isMSAA ) {
  49375. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  49376. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  49377. msaaTextureDescriptorGPU.sampleCount = samples;
  49378. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  49379. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  49380. }
  49381. textureData.initialized = true;
  49382. textureData.textureDescriptorGPU = textureDescriptorGPU;
  49383. }
  49384. /**
  49385. * Destroys the GPU data for the given texture object.
  49386. *
  49387. * @param {Texture} texture - The texture.
  49388. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49389. */
  49390. destroyTexture( texture, isDefaultTexture = false ) {
  49391. const backend = this.backend;
  49392. const textureData = backend.get( texture );
  49393. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  49394. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  49395. backend.delete( texture );
  49396. }
  49397. /**
  49398. * Generates mipmaps for the given texture.
  49399. *
  49400. * @param {Texture} texture - The texture.
  49401. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49402. */
  49403. generateMipmaps( texture, encoder = null ) {
  49404. const textureData = this.backend.get( texture );
  49405. if ( texture.isCubeTexture ) {
  49406. for ( let i = 0; i < 6; i ++ ) {
  49407. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  49408. }
  49409. } else {
  49410. const depth = texture.image.depth || 1;
  49411. for ( let i = 0; i < depth; i ++ ) {
  49412. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  49413. }
  49414. }
  49415. }
  49416. /**
  49417. * Returns the color buffer representing the color
  49418. * attachment of the default framebuffer.
  49419. *
  49420. * @return {GPUTexture} The color buffer.
  49421. */
  49422. getColorBuffer() {
  49423. const backend = this.backend;
  49424. const canvasTarget = backend.renderer.getCanvasTarget();
  49425. const { width, height } = backend.getDrawingBufferSize();
  49426. const samples = backend.renderer.currentSamples;
  49427. const colorTexture = canvasTarget.colorTexture;
  49428. const colorTextureData = backend.get( colorTexture );
  49429. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  49430. return colorTextureData.texture;
  49431. }
  49432. // recreate
  49433. let colorBuffer = colorTextureData.texture;
  49434. if ( colorBuffer ) colorBuffer.destroy();
  49435. colorBuffer = backend.device.createTexture( {
  49436. label: 'colorBuffer',
  49437. size: {
  49438. width: width,
  49439. height: height,
  49440. depthOrArrayLayers: 1
  49441. },
  49442. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  49443. format: backend.utils.getPreferredCanvasFormat(),
  49444. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  49445. } );
  49446. //
  49447. colorTexture.source.width = width;
  49448. colorTexture.source.height = height;
  49449. colorTexture.samples = samples;
  49450. colorTextureData.texture = colorBuffer;
  49451. return colorBuffer;
  49452. }
  49453. /**
  49454. * Returns the depth buffer representing the depth
  49455. * attachment of the default framebuffer.
  49456. *
  49457. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  49458. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  49459. * @return {GPUTexture} The depth buffer.
  49460. */
  49461. getDepthBuffer( depth = true, stencil = false ) {
  49462. const backend = this.backend;
  49463. const canvasTarget = backend.renderer.getCanvasTarget();
  49464. const { width, height } = backend.getDrawingBufferSize();
  49465. const samples = backend.renderer.currentSamples;
  49466. const depthTexture = canvasTarget.depthTexture;
  49467. if ( depthTexture.width === width &&
  49468. depthTexture.height === height &&
  49469. depthTexture.samples === samples &&
  49470. depthTexture.depth === depth &&
  49471. depthTexture.stencil === stencil ) {
  49472. return backend.get( depthTexture ).texture;
  49473. }
  49474. //
  49475. const depthTextureGPU = backend.get( depthTexture ).texture;
  49476. let format, type;
  49477. if ( stencil ) {
  49478. format = DepthStencilFormat;
  49479. type = UnsignedInt248Type;
  49480. } else if ( depth ) {
  49481. format = DepthFormat;
  49482. type = UnsignedIntType;
  49483. }
  49484. if ( depthTextureGPU !== undefined ) {
  49485. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  49486. return depthTextureGPU;
  49487. }
  49488. this.destroyTexture( depthTexture );
  49489. }
  49490. // recreate
  49491. depthTexture.name = 'depthBuffer';
  49492. depthTexture.format = format;
  49493. depthTexture.type = type;
  49494. depthTexture.image.width = width;
  49495. depthTexture.image.height = height;
  49496. depthTexture.samples = samples;
  49497. this.createTexture( depthTexture, { width, height } );
  49498. return backend.get( depthTexture ).texture;
  49499. }
  49500. /**
  49501. * Uploads the updated texture data to the GPU.
  49502. *
  49503. * @param {Texture} texture - The texture.
  49504. * @param {Object} [options={}] - Optional configuration parameter.
  49505. */
  49506. updateTexture( texture, options ) {
  49507. const textureData = this.backend.get( texture );
  49508. const mipmaps = texture.mipmaps;
  49509. const { textureDescriptorGPU } = textureData;
  49510. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  49511. return;
  49512. // transfer texture data
  49513. if ( texture.isDataTexture ) {
  49514. if ( mipmaps.length > 0 ) {
  49515. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49516. const mipmap = mipmaps[ i ];
  49517. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  49518. }
  49519. } else {
  49520. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  49521. }
  49522. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49523. for ( let i = 0; i < options.image.depth; i ++ ) {
  49524. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  49525. }
  49526. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  49527. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  49528. } else if ( texture.isCubeTexture ) {
  49529. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  49530. } else {
  49531. if ( mipmaps.length > 0 ) {
  49532. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49533. const mipmap = mipmaps[ i ];
  49534. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  49535. }
  49536. } else {
  49537. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  49538. }
  49539. }
  49540. //
  49541. textureData.version = texture.version;
  49542. }
  49543. /**
  49544. * Returns texture data as a typed array.
  49545. *
  49546. * @async
  49547. * @param {Texture} texture - The texture to copy.
  49548. * @param {number} x - The x coordinate of the copy origin.
  49549. * @param {number} y - The y coordinate of the copy origin.
  49550. * @param {number} width - The width of the copy.
  49551. * @param {number} height - The height of the copy.
  49552. * @param {number} faceIndex - The face index.
  49553. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49554. */
  49555. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49556. const device = this.backend.device;
  49557. const textureData = this.backend.get( texture );
  49558. const textureGPU = textureData.texture;
  49559. const format = textureData.textureDescriptorGPU.format;
  49560. const bytesPerTexel = this._getBytesPerTexel( format );
  49561. let bytesPerRow = width * bytesPerTexel;
  49562. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  49563. const readBuffer = device.createBuffer(
  49564. {
  49565. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  49566. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49567. }
  49568. );
  49569. const encoder = device.createCommandEncoder();
  49570. encoder.copyTextureToBuffer(
  49571. {
  49572. texture: textureGPU,
  49573. origin: { x, y, z: faceIndex },
  49574. },
  49575. {
  49576. buffer: readBuffer,
  49577. bytesPerRow: bytesPerRow
  49578. },
  49579. {
  49580. width: width,
  49581. height: height
  49582. }
  49583. );
  49584. const typedArrayType = this._getTypedArrayType( format );
  49585. device.queue.submit( [ encoder.finish() ] );
  49586. await readBuffer.mapAsync( GPUMapMode.READ );
  49587. const buffer = readBuffer.getMappedRange();
  49588. return new typedArrayType( buffer );
  49589. }
  49590. /**
  49591. * Frees all internal resources.
  49592. */
  49593. dispose() {
  49594. this._samplerCache.clear();
  49595. }
  49596. /**
  49597. * Returns the default GPU texture for the given format.
  49598. *
  49599. * @private
  49600. * @param {string} format - The GPU format.
  49601. * @return {GPUTexture} The GPU texture.
  49602. */
  49603. _getDefaultTextureGPU( format ) {
  49604. let defaultTexture = this.defaultTexture[ format ];
  49605. if ( defaultTexture === undefined ) {
  49606. const texture = new Texture();
  49607. texture.minFilter = NearestFilter;
  49608. texture.magFilter = NearestFilter;
  49609. this.createTexture( texture, { width: 1, height: 1, format } );
  49610. this.defaultTexture[ format ] = defaultTexture = texture;
  49611. }
  49612. return this.backend.get( defaultTexture ).texture;
  49613. }
  49614. /**
  49615. * Returns the default GPU cube texture for the given format.
  49616. *
  49617. * @private
  49618. * @param {string} format - The GPU format.
  49619. * @return {GPUTexture} The GPU texture.
  49620. */
  49621. _getDefaultCubeTextureGPU( format ) {
  49622. let defaultCubeTexture = this.defaultTexture[ format ];
  49623. if ( defaultCubeTexture === undefined ) {
  49624. const texture = new CubeTexture();
  49625. texture.minFilter = NearestFilter;
  49626. texture.magFilter = NearestFilter;
  49627. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  49628. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  49629. }
  49630. return this.backend.get( defaultCubeTexture ).texture;
  49631. }
  49632. /**
  49633. * Uploads cube texture image data to the GPU memory.
  49634. *
  49635. * @private
  49636. * @param {CubeTexture} texture - The cube texture.
  49637. * @param {GPUTexture} textureGPU - The GPU texture.
  49638. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49639. */
  49640. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  49641. const images = texture.images;
  49642. const mipmaps = texture.mipmaps;
  49643. for ( let i = 0; i < 6; i ++ ) {
  49644. const image = images[ i ];
  49645. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  49646. if ( image.isDataTexture ) {
  49647. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  49648. } else {
  49649. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  49650. }
  49651. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49652. const mipmap = mipmaps[ j ];
  49653. const image = mipmap.images[ i ];
  49654. if ( image.isDataTexture ) {
  49655. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  49656. } else {
  49657. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  49658. }
  49659. }
  49660. }
  49661. }
  49662. /**
  49663. * Uploads texture image data to the GPU memory.
  49664. *
  49665. * @private
  49666. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  49667. * @param {GPUTexture} textureGPU - The GPU texture.
  49668. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49669. * @param {number} originDepth - The origin depth.
  49670. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49671. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  49672. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49673. */
  49674. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  49675. const device = this.backend.device;
  49676. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  49677. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  49678. device.queue.copyExternalImageToTexture(
  49679. {
  49680. source: image,
  49681. flipY: flipY
  49682. }, {
  49683. texture: textureGPU,
  49684. mipLevel: mipLevel,
  49685. origin: { x: 0, y: 0, z: originDepth },
  49686. premultipliedAlpha: premultiplyAlpha
  49687. }, {
  49688. width: width,
  49689. height: height,
  49690. depthOrArrayLayers: 1
  49691. }
  49692. );
  49693. }
  49694. /**
  49695. * Returns the pass utils singleton.
  49696. *
  49697. * @private
  49698. * @return {WebGPUTexturePassUtils} The utils instance.
  49699. */
  49700. _getPassUtils() {
  49701. let passUtils = this._passUtils;
  49702. if ( passUtils === null ) {
  49703. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  49704. }
  49705. return passUtils;
  49706. }
  49707. /**
  49708. * Generates mipmaps for the given GPU texture.
  49709. *
  49710. * @private
  49711. * @param {GPUTexture} textureGPU - The GPU texture object.
  49712. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49713. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49714. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49715. */
  49716. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  49717. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  49718. }
  49719. /**
  49720. * Flip the contents of the given GPU texture along its vertical axis.
  49721. *
  49722. * @private
  49723. * @param {GPUTexture} textureGPU - The GPU texture object.
  49724. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49725. * @param {number} [originDepth=0] - The origin depth.
  49726. */
  49727. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  49728. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  49729. }
  49730. /**
  49731. * Uploads texture buffer data to the GPU memory.
  49732. *
  49733. * @private
  49734. * @param {Object} image - An object defining the image buffer data.
  49735. * @param {GPUTexture} textureGPU - The GPU texture.
  49736. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49737. * @param {number} originDepth - The origin depth.
  49738. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49739. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  49740. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49741. */
  49742. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  49743. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49744. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  49745. const device = this.backend.device;
  49746. const data = image.data;
  49747. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  49748. const bytesPerRow = image.width * bytesPerTexel;
  49749. device.queue.writeTexture(
  49750. {
  49751. texture: textureGPU,
  49752. mipLevel: mipLevel,
  49753. origin: { x: 0, y: 0, z: originDepth }
  49754. },
  49755. data,
  49756. {
  49757. offset: image.width * image.height * bytesPerTexel * depth,
  49758. bytesPerRow
  49759. },
  49760. {
  49761. width: image.width,
  49762. height: image.height,
  49763. depthOrArrayLayers: 1
  49764. } );
  49765. if ( flipY === true ) {
  49766. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  49767. }
  49768. }
  49769. /**
  49770. * Uploads compressed texture data to the GPU memory.
  49771. *
  49772. * @private
  49773. * @param {Array<Object>} mipmaps - An array with mipmap data.
  49774. * @param {GPUTexture} textureGPU - The GPU texture.
  49775. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49776. */
  49777. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  49778. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49779. const device = this.backend.device;
  49780. const blockData = this._getBlockData( textureDescriptorGPU.format );
  49781. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  49782. for ( let i = 0; i < mipmaps.length; i ++ ) {
  49783. const mipmap = mipmaps[ i ];
  49784. const width = mipmap.width;
  49785. const height = mipmap.height;
  49786. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  49787. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  49788. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  49789. for ( let j = 0; j < depth; j ++ ) {
  49790. device.queue.writeTexture(
  49791. {
  49792. texture: textureGPU,
  49793. mipLevel: i,
  49794. origin: { x: 0, y: 0, z: j }
  49795. },
  49796. mipmap.data,
  49797. {
  49798. offset: j * bytesPerImage,
  49799. bytesPerRow,
  49800. rowsPerImage: Math.ceil( height / blockData.height )
  49801. },
  49802. {
  49803. width: Math.ceil( width / blockData.width ) * blockData.width,
  49804. height: Math.ceil( height / blockData.height ) * blockData.height,
  49805. depthOrArrayLayers: 1
  49806. }
  49807. );
  49808. }
  49809. }
  49810. }
  49811. /**
  49812. * This method is only relevant for compressed texture formats. It returns a block
  49813. * data descriptor for the given GPU compressed texture format.
  49814. *
  49815. * @private
  49816. * @param {string} format - The GPU compressed texture format.
  49817. * @return {Object} The block data descriptor.
  49818. */
  49819. _getBlockData( format ) {
  49820. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  49821. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  49822. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  49823. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  49824. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  49825. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  49826. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  49827. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49828. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49829. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49830. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  49831. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  49832. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  49833. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  49834. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49835. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  49836. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  49837. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  49838. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  49839. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  49840. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  49841. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  49842. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  49843. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  49844. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  49845. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  49846. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  49847. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  49848. }
  49849. /**
  49850. * Converts the three.js uv wrapping constants to GPU address mode constants.
  49851. *
  49852. * @private
  49853. * @param {number} value - The three.js constant defining a uv wrapping mode.
  49854. * @return {string} The GPU address mode.
  49855. */
  49856. _convertAddressMode( value ) {
  49857. let addressMode = GPUAddressMode.ClampToEdge;
  49858. if ( value === RepeatWrapping ) {
  49859. addressMode = GPUAddressMode.Repeat;
  49860. } else if ( value === MirroredRepeatWrapping ) {
  49861. addressMode = GPUAddressMode.MirrorRepeat;
  49862. }
  49863. return addressMode;
  49864. }
  49865. /**
  49866. * Converts the three.js filter constants to GPU filter constants.
  49867. *
  49868. * @private
  49869. * @param {number} value - The three.js constant defining a filter mode.
  49870. * @return {string} The GPU filter mode.
  49871. */
  49872. _convertFilterMode( value ) {
  49873. let filterMode = GPUFilterMode.Linear;
  49874. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  49875. filterMode = GPUFilterMode.Nearest;
  49876. }
  49877. return filterMode;
  49878. }
  49879. /**
  49880. * Returns the bytes-per-texel value for the given GPU texture format.
  49881. *
  49882. * @private
  49883. * @param {string} format - The GPU texture format.
  49884. * @return {number} The bytes-per-texel.
  49885. */
  49886. _getBytesPerTexel( format ) {
  49887. // 8-bit formats
  49888. if ( format === GPUTextureFormat.R8Unorm ||
  49889. format === GPUTextureFormat.R8Snorm ||
  49890. format === GPUTextureFormat.R8Uint ||
  49891. format === GPUTextureFormat.R8Sint ) return 1;
  49892. // 16-bit formats
  49893. if ( format === GPUTextureFormat.R16Uint ||
  49894. format === GPUTextureFormat.R16Sint ||
  49895. format === GPUTextureFormat.R16Float ||
  49896. format === GPUTextureFormat.RG8Unorm ||
  49897. format === GPUTextureFormat.RG8Snorm ||
  49898. format === GPUTextureFormat.RG8Uint ||
  49899. format === GPUTextureFormat.RG8Sint ) return 2;
  49900. // 32-bit formats
  49901. if ( format === GPUTextureFormat.R32Uint ||
  49902. format === GPUTextureFormat.R32Sint ||
  49903. format === GPUTextureFormat.R32Float ||
  49904. format === GPUTextureFormat.RG16Uint ||
  49905. format === GPUTextureFormat.RG16Sint ||
  49906. format === GPUTextureFormat.RG16Float ||
  49907. format === GPUTextureFormat.RGBA8Unorm ||
  49908. format === GPUTextureFormat.RGBA8UnormSRGB ||
  49909. format === GPUTextureFormat.RGBA8Snorm ||
  49910. format === GPUTextureFormat.RGBA8Uint ||
  49911. format === GPUTextureFormat.RGBA8Sint ||
  49912. format === GPUTextureFormat.BGRA8Unorm ||
  49913. format === GPUTextureFormat.BGRA8UnormSRGB ||
  49914. // Packed 32-bit formats
  49915. format === GPUTextureFormat.RGB9E5UFloat ||
  49916. format === GPUTextureFormat.RGB10A2Unorm ||
  49917. format === GPUTextureFormat.RG11B10UFloat ||
  49918. format === GPUTextureFormat.Depth32Float ||
  49919. format === GPUTextureFormat.Depth24Plus ||
  49920. format === GPUTextureFormat.Depth24PlusStencil8 ||
  49921. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  49922. // 64-bit formats
  49923. if ( format === GPUTextureFormat.RG32Uint ||
  49924. format === GPUTextureFormat.RG32Sint ||
  49925. format === GPUTextureFormat.RG32Float ||
  49926. format === GPUTextureFormat.RGBA16Uint ||
  49927. format === GPUTextureFormat.RGBA16Sint ||
  49928. format === GPUTextureFormat.RGBA16Float ) return 8;
  49929. // 128-bit formats
  49930. if ( format === GPUTextureFormat.RGBA32Uint ||
  49931. format === GPUTextureFormat.RGBA32Sint ||
  49932. format === GPUTextureFormat.RGBA32Float ) return 16;
  49933. }
  49934. /**
  49935. * Returns the corresponding typed array type for the given GPU texture format.
  49936. *
  49937. * @private
  49938. * @param {string} format - The GPU texture format.
  49939. * @return {TypedArray.constructor} The typed array type.
  49940. */
  49941. _getTypedArrayType( format ) {
  49942. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  49943. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  49944. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  49945. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  49946. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  49947. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  49948. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  49949. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  49950. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  49951. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  49952. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  49953. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  49954. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  49955. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  49956. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  49957. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  49958. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  49959. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  49960. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  49961. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  49962. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  49963. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  49964. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  49965. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  49966. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  49967. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  49968. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  49969. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  49970. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  49971. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  49972. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  49973. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  49974. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  49975. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  49976. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  49977. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  49978. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  49979. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  49980. }
  49981. /**
  49982. * Returns the GPU dimensions for the given texture.
  49983. *
  49984. * @private
  49985. * @param {Texture} texture - The texture.
  49986. * @return {string} The GPU dimension.
  49987. */
  49988. _getDimension( texture ) {
  49989. let dimension;
  49990. if ( texture.is3DTexture || texture.isData3DTexture ) {
  49991. dimension = GPUTextureDimension.ThreeD;
  49992. } else {
  49993. dimension = GPUTextureDimension.TwoD;
  49994. }
  49995. return dimension;
  49996. }
  49997. }
  49998. /**
  49999. * Returns the GPU format for the given texture.
  50000. *
  50001. * @param {Texture} texture - The texture.
  50002. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  50003. * It is not necessary to apply the device for most formats.
  50004. * @return {string} The GPU format.
  50005. */
  50006. function getFormat( texture, device = null ) {
  50007. const format = texture.format;
  50008. const type = texture.type;
  50009. const colorSpace = texture.colorSpace;
  50010. const transfer = ColorManagement.getTransfer( colorSpace );
  50011. let formatGPU;
  50012. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  50013. switch ( format ) {
  50014. case RGB_S3TC_DXT1_Format:
  50015. case RGBA_S3TC_DXT1_Format:
  50016. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  50017. break;
  50018. case RGBA_S3TC_DXT3_Format:
  50019. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  50020. break;
  50021. case RGBA_S3TC_DXT5_Format:
  50022. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  50023. break;
  50024. case RED_RGTC1_Format:
  50025. formatGPU = GPUTextureFormat.BC4RUnorm;
  50026. break;
  50027. case SIGNED_RED_RGTC1_Format:
  50028. formatGPU = GPUTextureFormat.BC4RSnorm;
  50029. break;
  50030. case RED_GREEN_RGTC2_Format:
  50031. formatGPU = GPUTextureFormat.BC5RGUnorm;
  50032. break;
  50033. case SIGNED_RED_GREEN_RGTC2_Format:
  50034. formatGPU = GPUTextureFormat.BC5RGSnorm;
  50035. break;
  50036. case RGBA_BPTC_Format:
  50037. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  50038. break;
  50039. case RGB_ETC2_Format:
  50040. case RGB_ETC1_Format:
  50041. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  50042. break;
  50043. case RGBA_ETC2_EAC_Format:
  50044. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  50045. break;
  50046. case RGBA_ASTC_4x4_Format:
  50047. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  50048. break;
  50049. case RGBA_ASTC_5x4_Format:
  50050. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  50051. break;
  50052. case RGBA_ASTC_5x5_Format:
  50053. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  50054. break;
  50055. case RGBA_ASTC_6x5_Format:
  50056. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  50057. break;
  50058. case RGBA_ASTC_6x6_Format:
  50059. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  50060. break;
  50061. case RGBA_ASTC_8x5_Format:
  50062. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  50063. break;
  50064. case RGBA_ASTC_8x6_Format:
  50065. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  50066. break;
  50067. case RGBA_ASTC_8x8_Format:
  50068. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  50069. break;
  50070. case RGBA_ASTC_10x5_Format:
  50071. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  50072. break;
  50073. case RGBA_ASTC_10x6_Format:
  50074. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  50075. break;
  50076. case RGBA_ASTC_10x8_Format:
  50077. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  50078. break;
  50079. case RGBA_ASTC_10x10_Format:
  50080. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  50081. break;
  50082. case RGBA_ASTC_12x10_Format:
  50083. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  50084. break;
  50085. case RGBA_ASTC_12x12_Format:
  50086. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  50087. break;
  50088. case RGBAFormat:
  50089. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50090. break;
  50091. default:
  50092. error( 'WebGPURenderer: Unsupported texture format.', format );
  50093. }
  50094. } else {
  50095. switch ( format ) {
  50096. case RGBAFormat:
  50097. switch ( type ) {
  50098. case ByteType:
  50099. formatGPU = GPUTextureFormat.RGBA8Snorm;
  50100. break;
  50101. case ShortType:
  50102. formatGPU = GPUTextureFormat.RGBA16Sint;
  50103. break;
  50104. case UnsignedShortType:
  50105. formatGPU = GPUTextureFormat.RGBA16Uint;
  50106. break;
  50107. case UnsignedIntType:
  50108. formatGPU = GPUTextureFormat.RGBA32Uint;
  50109. break;
  50110. case IntType:
  50111. formatGPU = GPUTextureFormat.RGBA32Sint;
  50112. break;
  50113. case UnsignedByteType:
  50114. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50115. break;
  50116. case HalfFloatType:
  50117. formatGPU = GPUTextureFormat.RGBA16Float;
  50118. break;
  50119. case FloatType:
  50120. formatGPU = GPUTextureFormat.RGBA32Float;
  50121. break;
  50122. default:
  50123. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  50124. }
  50125. break;
  50126. case RGBFormat:
  50127. switch ( type ) {
  50128. case UnsignedInt5999Type:
  50129. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  50130. break;
  50131. case UnsignedInt101111Type:
  50132. formatGPU = GPUTextureFormat.RG11B10UFloat;
  50133. break;
  50134. default:
  50135. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  50136. }
  50137. break;
  50138. case RedFormat:
  50139. switch ( type ) {
  50140. case ByteType:
  50141. formatGPU = GPUTextureFormat.R8Snorm;
  50142. break;
  50143. case ShortType:
  50144. formatGPU = GPUTextureFormat.R16Sint;
  50145. break;
  50146. case UnsignedShortType:
  50147. formatGPU = GPUTextureFormat.R16Uint;
  50148. break;
  50149. case UnsignedIntType:
  50150. formatGPU = GPUTextureFormat.R32Uint;
  50151. break;
  50152. case IntType:
  50153. formatGPU = GPUTextureFormat.R32Sint;
  50154. break;
  50155. case UnsignedByteType:
  50156. formatGPU = GPUTextureFormat.R8Unorm;
  50157. break;
  50158. case HalfFloatType:
  50159. formatGPU = GPUTextureFormat.R16Float;
  50160. break;
  50161. case FloatType:
  50162. formatGPU = GPUTextureFormat.R32Float;
  50163. break;
  50164. default:
  50165. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  50166. }
  50167. break;
  50168. case RGFormat:
  50169. switch ( type ) {
  50170. case ByteType:
  50171. formatGPU = GPUTextureFormat.RG8Snorm;
  50172. break;
  50173. case ShortType:
  50174. formatGPU = GPUTextureFormat.RG16Sint;
  50175. break;
  50176. case UnsignedShortType:
  50177. formatGPU = GPUTextureFormat.RG16Uint;
  50178. break;
  50179. case UnsignedIntType:
  50180. formatGPU = GPUTextureFormat.RG32Uint;
  50181. break;
  50182. case IntType:
  50183. formatGPU = GPUTextureFormat.RG32Sint;
  50184. break;
  50185. case UnsignedByteType:
  50186. formatGPU = GPUTextureFormat.RG8Unorm;
  50187. break;
  50188. case HalfFloatType:
  50189. formatGPU = GPUTextureFormat.RG16Float;
  50190. break;
  50191. case FloatType:
  50192. formatGPU = GPUTextureFormat.RG32Float;
  50193. break;
  50194. default:
  50195. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  50196. }
  50197. break;
  50198. case DepthFormat:
  50199. switch ( type ) {
  50200. case UnsignedShortType:
  50201. formatGPU = GPUTextureFormat.Depth16Unorm;
  50202. break;
  50203. case UnsignedIntType:
  50204. formatGPU = GPUTextureFormat.Depth24Plus;
  50205. break;
  50206. case FloatType:
  50207. formatGPU = GPUTextureFormat.Depth32Float;
  50208. break;
  50209. default:
  50210. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  50211. }
  50212. break;
  50213. case DepthStencilFormat:
  50214. switch ( type ) {
  50215. case UnsignedInt248Type:
  50216. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  50217. break;
  50218. case FloatType:
  50219. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  50220. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  50221. }
  50222. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  50223. break;
  50224. default:
  50225. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  50226. }
  50227. break;
  50228. case RedIntegerFormat:
  50229. switch ( type ) {
  50230. case IntType:
  50231. formatGPU = GPUTextureFormat.R32Sint;
  50232. break;
  50233. case UnsignedIntType:
  50234. formatGPU = GPUTextureFormat.R32Uint;
  50235. break;
  50236. default:
  50237. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  50238. }
  50239. break;
  50240. case RGIntegerFormat:
  50241. switch ( type ) {
  50242. case IntType:
  50243. formatGPU = GPUTextureFormat.RG32Sint;
  50244. break;
  50245. case UnsignedIntType:
  50246. formatGPU = GPUTextureFormat.RG32Uint;
  50247. break;
  50248. default:
  50249. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  50250. }
  50251. break;
  50252. case RGBAIntegerFormat:
  50253. switch ( type ) {
  50254. case IntType:
  50255. formatGPU = GPUTextureFormat.RGBA32Sint;
  50256. break;
  50257. case UnsignedIntType:
  50258. formatGPU = GPUTextureFormat.RGBA32Uint;
  50259. break;
  50260. default:
  50261. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  50262. }
  50263. break;
  50264. default:
  50265. error( 'WebGPURenderer: Unsupported texture format.', format );
  50266. }
  50267. }
  50268. return formatGPU;
  50269. }
  50270. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  50271. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  50272. const wgslTypeLib$1 = {
  50273. 'f32': 'float',
  50274. 'i32': 'int',
  50275. 'u32': 'uint',
  50276. 'bool': 'bool',
  50277. 'vec2<f32>': 'vec2',
  50278. 'vec2<i32>': 'ivec2',
  50279. 'vec2<u32>': 'uvec2',
  50280. 'vec2<bool>': 'bvec2',
  50281. 'vec2f': 'vec2',
  50282. 'vec2i': 'ivec2',
  50283. 'vec2u': 'uvec2',
  50284. 'vec2b': 'bvec2',
  50285. 'vec3<f32>': 'vec3',
  50286. 'vec3<i32>': 'ivec3',
  50287. 'vec3<u32>': 'uvec3',
  50288. 'vec3<bool>': 'bvec3',
  50289. 'vec3f': 'vec3',
  50290. 'vec3i': 'ivec3',
  50291. 'vec3u': 'uvec3',
  50292. 'vec3b': 'bvec3',
  50293. 'vec4<f32>': 'vec4',
  50294. 'vec4<i32>': 'ivec4',
  50295. 'vec4<u32>': 'uvec4',
  50296. 'vec4<bool>': 'bvec4',
  50297. 'vec4f': 'vec4',
  50298. 'vec4i': 'ivec4',
  50299. 'vec4u': 'uvec4',
  50300. 'vec4b': 'bvec4',
  50301. 'mat2x2<f32>': 'mat2',
  50302. 'mat2x2f': 'mat2',
  50303. 'mat3x3<f32>': 'mat3',
  50304. 'mat3x3f': 'mat3',
  50305. 'mat4x4<f32>': 'mat4',
  50306. 'mat4x4f': 'mat4',
  50307. 'sampler': 'sampler',
  50308. 'texture_1d': 'texture',
  50309. 'texture_2d': 'texture',
  50310. 'texture_2d_array': 'texture',
  50311. 'texture_multisampled_2d': 'cubeTexture',
  50312. 'texture_depth_2d': 'depthTexture',
  50313. 'texture_depth_2d_array': 'depthTexture',
  50314. 'texture_depth_multisampled_2d': 'depthTexture',
  50315. 'texture_depth_cube': 'depthTexture',
  50316. 'texture_depth_cube_array': 'depthTexture',
  50317. 'texture_3d': 'texture3D',
  50318. 'texture_cube': 'cubeTexture',
  50319. 'texture_cube_array': 'cubeTexture',
  50320. 'texture_storage_1d': 'storageTexture',
  50321. 'texture_storage_2d': 'storageTexture',
  50322. 'texture_storage_2d_array': 'storageTexture',
  50323. 'texture_storage_3d': 'storageTexture'
  50324. };
  50325. const parse = ( source ) => {
  50326. source = source.trim();
  50327. const declaration = source.match( declarationRegexp );
  50328. if ( declaration !== null && declaration.length === 4 ) {
  50329. const inputsCode = declaration[ 2 ];
  50330. const propsMatches = [];
  50331. let match = null;
  50332. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  50333. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  50334. }
  50335. // Process matches to correctly pair names and types
  50336. const inputs = [];
  50337. for ( let i = 0; i < propsMatches.length; i ++ ) {
  50338. const { name, type } = propsMatches[ i ];
  50339. let resolvedType = type;
  50340. if ( resolvedType.startsWith( 'ptr' ) ) {
  50341. resolvedType = 'pointer';
  50342. } else {
  50343. if ( resolvedType.startsWith( 'texture' ) ) {
  50344. resolvedType = type.split( '<' )[ 0 ];
  50345. }
  50346. resolvedType = wgslTypeLib$1[ resolvedType ];
  50347. }
  50348. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  50349. }
  50350. const blockCode = source.substring( declaration[ 0 ].length );
  50351. const outputType = declaration[ 3 ] || 'void';
  50352. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  50353. const type = wgslTypeLib$1[ outputType ] || outputType;
  50354. return {
  50355. type,
  50356. inputs,
  50357. name,
  50358. inputsCode,
  50359. blockCode,
  50360. outputType
  50361. };
  50362. } else {
  50363. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  50364. }
  50365. };
  50366. /**
  50367. * This class represents a WSL node function.
  50368. *
  50369. * @augments NodeFunction
  50370. */
  50371. class WGSLNodeFunction extends NodeFunction {
  50372. /**
  50373. * Constructs a new WGSL node function.
  50374. *
  50375. * @param {string} source - The WGSL source.
  50376. */
  50377. constructor( source ) {
  50378. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  50379. super( type, inputs, name );
  50380. this.inputsCode = inputsCode;
  50381. this.blockCode = blockCode;
  50382. this.outputType = outputType;
  50383. }
  50384. /**
  50385. * This method returns the WGSL code of the node function.
  50386. *
  50387. * @param {string} [name=this.name] - The function's name.
  50388. * @return {string} The shader code.
  50389. */
  50390. getCode( name = this.name ) {
  50391. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  50392. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  50393. }
  50394. }
  50395. /**
  50396. * A WGSL node parser.
  50397. *
  50398. * @augments NodeParser
  50399. */
  50400. class WGSLNodeParser extends NodeParser {
  50401. /**
  50402. * The method parses the given WGSL code an returns a node function.
  50403. *
  50404. * @param {string} source - The WGSL code.
  50405. * @return {WGSLNodeFunction} A node function.
  50406. */
  50407. parseFunction( source ) {
  50408. return new WGSLNodeFunction( source );
  50409. }
  50410. }
  50411. // GPUShaderStage is not defined in browsers not supporting WebGPU
  50412. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50413. const accessNames = {
  50414. [ NodeAccess.READ_ONLY ]: 'read',
  50415. [ NodeAccess.WRITE_ONLY ]: 'write',
  50416. [ NodeAccess.READ_WRITE ]: 'read_write'
  50417. };
  50418. const wrapNames = {
  50419. [ RepeatWrapping ]: 'repeat',
  50420. [ ClampToEdgeWrapping ]: 'clamp',
  50421. [ MirroredRepeatWrapping ]: 'mirror'
  50422. };
  50423. const gpuShaderStageLib = {
  50424. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  50425. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  50426. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  50427. };
  50428. const supports = {
  50429. instance: true,
  50430. swizzleAssign: false,
  50431. storageBuffer: true
  50432. };
  50433. const wgslFnOpLib = {
  50434. '^^': 'tsl_xor'
  50435. };
  50436. const wgslTypeLib = {
  50437. float: 'f32',
  50438. int: 'i32',
  50439. uint: 'u32',
  50440. bool: 'bool',
  50441. color: 'vec3<f32>',
  50442. vec2: 'vec2<f32>',
  50443. ivec2: 'vec2<i32>',
  50444. uvec2: 'vec2<u32>',
  50445. bvec2: 'vec2<bool>',
  50446. vec3: 'vec3<f32>',
  50447. ivec3: 'vec3<i32>',
  50448. uvec3: 'vec3<u32>',
  50449. bvec3: 'vec3<bool>',
  50450. vec4: 'vec4<f32>',
  50451. ivec4: 'vec4<i32>',
  50452. uvec4: 'vec4<u32>',
  50453. bvec4: 'vec4<bool>',
  50454. mat2: 'mat2x2<f32>',
  50455. mat3: 'mat3x3<f32>',
  50456. mat4: 'mat4x4<f32>'
  50457. };
  50458. const wgslCodeCache = {};
  50459. const wgslPolyfill = {
  50460. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  50461. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  50462. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  50463. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  50464. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  50465. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  50466. 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 ); }' ),
  50467. 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 ); }' ),
  50468. 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 ); }' ),
  50469. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  50470. 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 ); }' ),
  50471. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  50472. biquadraticTexture: new CodeNode( /* wgsl */`
  50473. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  50474. let res = vec2f( iRes );
  50475. let uvScaled = coord * res;
  50476. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  50477. // https://www.shadertoy.com/view/WtyXRy
  50478. let uv = uvWrapping - 0.5;
  50479. let iuv = floor( uv );
  50480. let f = fract( uv );
  50481. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  50482. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  50483. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  50484. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  50485. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  50486. }
  50487. ` )
  50488. };
  50489. const wgslMethods = {
  50490. dFdx: 'dpdx',
  50491. dFdy: '- dpdy',
  50492. mod_float: 'tsl_mod_float',
  50493. mod_vec2: 'tsl_mod_vec2',
  50494. mod_vec3: 'tsl_mod_vec3',
  50495. mod_vec4: 'tsl_mod_vec4',
  50496. equals_bool: 'tsl_equals_bool',
  50497. equals_bvec2: 'tsl_equals_bvec2',
  50498. equals_bvec3: 'tsl_equals_bvec3',
  50499. equals_bvec4: 'tsl_equals_bvec4',
  50500. inversesqrt: 'inverseSqrt',
  50501. bitcast: 'bitcast<f32>'
  50502. };
  50503. //
  50504. let diagnostics = '';
  50505. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  50506. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  50507. }
  50508. /**
  50509. * A node builder targeting WGSL.
  50510. *
  50511. * This module generates WGSL shader code from node materials and also
  50512. * generates the respective bindings and vertex buffer definitions. These
  50513. * data are later used by the renderer to create render and compute pipelines
  50514. * for render objects.
  50515. *
  50516. * @augments NodeBuilder
  50517. */
  50518. class WGSLNodeBuilder extends NodeBuilder {
  50519. /**
  50520. * Constructs a new WGSL node builder renderer.
  50521. *
  50522. * @param {Object3D} object - The 3D object.
  50523. * @param {Renderer} renderer - The renderer.
  50524. */
  50525. constructor( object, renderer ) {
  50526. super( object, renderer, new WGSLNodeParser() );
  50527. /**
  50528. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  50529. * another dictionary which manages UBOs per group ('render','frame','object').
  50530. *
  50531. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  50532. */
  50533. this.uniformGroups = {};
  50534. /**
  50535. * A dictionary that holds for each shader stage a Map of builtins.
  50536. *
  50537. * @type {Object<string,Map<string,Object>>}
  50538. */
  50539. this.builtins = {};
  50540. /**
  50541. * A dictionary that holds for each shader stage a Set of directives.
  50542. *
  50543. * @type {Object<string,Set<string>>}
  50544. */
  50545. this.directives = {};
  50546. /**
  50547. * A map for managing scope arrays. Only relevant for when using
  50548. * {@link WorkgroupInfoNode} in context of compute shaders.
  50549. *
  50550. * @type {Map<string,Object>}
  50551. */
  50552. this.scopedArrays = new Map();
  50553. }
  50554. /**
  50555. * Generates the WGSL snippet for sampled textures.
  50556. *
  50557. * @private
  50558. * @param {Texture} texture - The texture.
  50559. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50560. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50561. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50562. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50563. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50564. * @return {string} The WGSL snippet.
  50565. */
  50566. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50567. if ( shaderStage === 'fragment' ) {
  50568. if ( depthSnippet ) {
  50569. if ( offsetSnippet ) {
  50570. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  50571. }
  50572. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  50573. } else {
  50574. if ( offsetSnippet ) {
  50575. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  50576. }
  50577. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  50578. }
  50579. } else {
  50580. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  50581. }
  50582. }
  50583. /**
  50584. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50585. *
  50586. * @private
  50587. * @param {Texture} texture - The texture.
  50588. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50589. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50590. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50591. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50592. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50593. * @return {string} The WGSL snippet.
  50594. */
  50595. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50596. if ( this.isUnfilterable( texture ) === false ) {
  50597. if ( offsetSnippet ) {
  50598. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50599. }
  50600. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50601. } else if ( this.isFilteredTexture( texture ) ) {
  50602. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50603. } else {
  50604. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50605. }
  50606. }
  50607. /**
  50608. * Generates a wrap function used in context of textures.
  50609. *
  50610. * @param {Texture} texture - The texture to generate the function for.
  50611. * @return {string} The name of the generated function.
  50612. */
  50613. generateWrapFunction( texture ) {
  50614. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  50615. let nodeCode = wgslCodeCache[ functionName ];
  50616. if ( nodeCode === undefined ) {
  50617. const includes = [];
  50618. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  50619. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  50620. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  50621. const addWrapSnippet = ( wrap, axis ) => {
  50622. if ( wrap === RepeatWrapping ) {
  50623. includes.push( wgslPolyfill.repeatWrapping_float );
  50624. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  50625. } else if ( wrap === ClampToEdgeWrapping ) {
  50626. includes.push( wgslPolyfill.clampWrapping_float );
  50627. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  50628. } else if ( wrap === MirroredRepeatWrapping ) {
  50629. includes.push( wgslPolyfill.mirrorWrapping_float );
  50630. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  50631. } else {
  50632. code += `\t\tcoord.${ axis }`;
  50633. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  50634. }
  50635. };
  50636. addWrapSnippet( texture.wrapS, 'x' );
  50637. code += ',\n';
  50638. addWrapSnippet( texture.wrapT, 'y' );
  50639. if ( texture.isData3DTexture ) {
  50640. code += ',\n';
  50641. addWrapSnippet( texture.wrapR, 'z' );
  50642. }
  50643. code += '\n\t);\n\n}\n';
  50644. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  50645. }
  50646. nodeCode.build( this );
  50647. return functionName;
  50648. }
  50649. /**
  50650. * Generates the array declaration string.
  50651. *
  50652. * @param {string} type - The type.
  50653. * @param {?number} [count] - The count.
  50654. * @return {string} The generated value as a shader string.
  50655. */
  50656. generateArrayDeclaration( type, count ) {
  50657. return `array< ${ this.getType( type ) }, ${ count } >`;
  50658. }
  50659. /**
  50660. * Generates a WGSL variable that holds the texture dimension of the given texture.
  50661. * It also returns information about the number of layers (elements) of an arrayed
  50662. * texture as well as the cube face count of cube textures.
  50663. *
  50664. * @param {Texture} texture - The texture to generate the function for.
  50665. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  50666. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50667. * @return {string} The name of the dimension variable.
  50668. */
  50669. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  50670. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  50671. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  50672. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  50673. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  50674. let textureDimensionsParams;
  50675. let dimensionType;
  50676. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50677. const isMultisampled = primarySamples > 1;
  50678. if ( texture.isData3DTexture ) {
  50679. dimensionType = 'vec3<u32>';
  50680. } else {
  50681. // Regular 2D textures, depth textures, etc.
  50682. dimensionType = 'vec2<u32>';
  50683. }
  50684. // Build parameters string based on texture type and multisampling
  50685. if ( isMultisampled || texture.isStorageTexture ) {
  50686. textureDimensionsParams = textureProperty;
  50687. } else {
  50688. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  50689. }
  50690. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  50691. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  50692. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50693. textureData.arrayLayerCount = new VarNode(
  50694. new ExpressionNode(
  50695. `textureNumLayers(${textureProperty})`,
  50696. 'u32'
  50697. )
  50698. );
  50699. }
  50700. // For cube textures, we know it's always 6 faces
  50701. if ( texture.isTextureCube ) {
  50702. textureData.cubeFaceCount = new VarNode(
  50703. new ExpressionNode( '6u', 'u32' )
  50704. );
  50705. }
  50706. }
  50707. return textureDimensionNode.build( this );
  50708. }
  50709. /**
  50710. * Generates the WGSL snippet for a manual filtered texture.
  50711. *
  50712. * @param {Texture} texture - The texture.
  50713. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50714. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50715. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50716. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50717. * @return {string} The WGSL snippet.
  50718. */
  50719. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50720. this._include( 'biquadraticTexture' );
  50721. const wrapFunction = this.generateWrapFunction( texture );
  50722. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50723. if ( offsetSnippet ) {
  50724. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  50725. }
  50726. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  50727. }
  50728. /**
  50729. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  50730. * Since it's a lookup, no sampling or filtering is applied.
  50731. *
  50732. * @param {Texture} texture - The texture.
  50733. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50734. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50735. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50736. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50737. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50738. * @return {string} The WGSL snippet.
  50739. */
  50740. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50741. const wrapFunction = this.generateWrapFunction( texture );
  50742. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50743. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  50744. if ( offsetSnippet ) {
  50745. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  50746. }
  50747. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  50748. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  50749. }
  50750. /**
  50751. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  50752. *
  50753. * @param {Texture} texture - The texture.
  50754. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50755. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50756. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50757. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50758. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50759. * @return {string} The WGSL snippet.
  50760. */
  50761. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50762. if ( levelSnippet === null ) levelSnippet = '0u';
  50763. if ( offsetSnippet ) {
  50764. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  50765. }
  50766. let snippet;
  50767. if ( depthSnippet ) {
  50768. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  50769. } else {
  50770. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  50771. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  50772. snippet += '.x';
  50773. }
  50774. }
  50775. return snippet;
  50776. }
  50777. /**
  50778. * Generates the WGSL snippet that writes a single texel to a texture.
  50779. *
  50780. * @param {Texture} texture - The texture.
  50781. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50782. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50783. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50784. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  50785. * @return {string} The WGSL snippet.
  50786. */
  50787. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  50788. let snippet;
  50789. if ( depthSnippet ) {
  50790. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  50791. } else {
  50792. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  50793. }
  50794. return snippet;
  50795. }
  50796. /**
  50797. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  50798. *
  50799. * @param {Texture} texture - The texture.
  50800. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  50801. */
  50802. isSampleCompare( texture ) {
  50803. return texture.isDepthTexture === true && texture.compareFunction !== null;
  50804. }
  50805. /**
  50806. * Returns `true` if the given texture is unfilterable.
  50807. *
  50808. * @param {Texture} texture - The texture.
  50809. * @return {boolean} Whether the given texture is unfilterable or not.
  50810. */
  50811. isUnfilterable( texture ) {
  50812. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  50813. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  50814. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  50815. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  50816. }
  50817. /**
  50818. * Generates the WGSL snippet for sampling/loading the given texture.
  50819. *
  50820. * @param {Texture} texture - The texture.
  50821. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50822. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50823. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50824. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50825. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50826. * @return {string} The WGSL snippet.
  50827. */
  50828. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50829. let snippet = null;
  50830. if ( this.isUnfilterable( texture ) ) {
  50831. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  50832. } else {
  50833. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  50834. }
  50835. return snippet;
  50836. }
  50837. /**
  50838. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  50839. *
  50840. * @param {Texture} texture - The texture.
  50841. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50842. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50843. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  50844. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50845. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50846. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50847. * @return {string} The WGSL snippet.
  50848. */
  50849. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50850. if ( shaderStage === 'fragment' ) {
  50851. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  50852. if ( offsetSnippet ) {
  50853. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  50854. }
  50855. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  50856. } else {
  50857. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  50858. }
  50859. }
  50860. /**
  50861. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  50862. * against a reference value.
  50863. *
  50864. * @param {Texture} texture - The texture.
  50865. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50866. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50867. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  50868. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50869. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50870. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50871. * @return {string} The WGSL snippet.
  50872. */
  50873. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50874. if ( shaderStage === 'fragment' ) {
  50875. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  50876. if ( offsetSnippet ) {
  50877. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50878. }
  50879. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  50880. }
  50881. if ( offsetSnippet ) {
  50882. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50883. }
  50884. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  50885. } else {
  50886. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  50887. }
  50888. }
  50889. /**
  50890. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50891. *
  50892. * @param {Texture} texture - The texture.
  50893. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50894. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50895. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50896. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50897. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50898. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50899. * @return {string} The WGSL snippet.
  50900. */
  50901. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50902. if ( this.isUnfilterable( texture ) === false ) {
  50903. if ( offsetSnippet ) {
  50904. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50905. }
  50906. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50907. } else if ( this.isFilteredTexture( texture ) ) {
  50908. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50909. } else {
  50910. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50911. }
  50912. }
  50913. /**
  50914. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  50915. *
  50916. * @param {Texture} texture - The texture.
  50917. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50918. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50919. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  50920. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50921. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50922. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50923. * @return {string} The WGSL snippet.
  50924. */
  50925. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50926. if ( shaderStage === 'fragment' ) {
  50927. if ( offsetSnippet ) {
  50928. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  50929. }
  50930. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  50931. } else {
  50932. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  50933. }
  50934. }
  50935. /**
  50936. * Returns a WGSL snippet that represents the property name of the given node.
  50937. *
  50938. * @param {Node} node - The node.
  50939. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50940. * @return {string} The property name.
  50941. */
  50942. getPropertyName( node, shaderStage = this.shaderStage ) {
  50943. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  50944. if ( shaderStage === 'vertex' ) {
  50945. return `varyings.${ node.name }`;
  50946. }
  50947. } else if ( node.isNodeUniform === true ) {
  50948. const name = node.name;
  50949. const type = node.type;
  50950. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50951. return name;
  50952. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  50953. if ( this.isCustomStruct( node ) ) {
  50954. return name;
  50955. }
  50956. return name + '.value';
  50957. } else {
  50958. return node.groupNode.name + '.' + name;
  50959. }
  50960. }
  50961. return super.getPropertyName( node );
  50962. }
  50963. /**
  50964. * Returns the output struct name.
  50965. *
  50966. * @return {string} The name of the output struct.
  50967. */
  50968. getOutputStructName() {
  50969. return 'output';
  50970. }
  50971. /**
  50972. * Returns the native shader operator name for a given generic name.
  50973. *
  50974. * @param {string} op - The operator name to resolve.
  50975. * @return {?string} The resolved operator name.
  50976. */
  50977. getFunctionOperator( op ) {
  50978. const fnOp = wgslFnOpLib[ op ];
  50979. if ( fnOp !== undefined ) {
  50980. this._include( fnOp );
  50981. return fnOp;
  50982. }
  50983. return null;
  50984. }
  50985. /**
  50986. * Returns the node access for the given node and shader stage.
  50987. *
  50988. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50989. * @param {string} shaderStage - The shader stage.
  50990. * @return {string} The node access.
  50991. */
  50992. getNodeAccess( node, shaderStage ) {
  50993. if ( shaderStage !== 'compute' ) {
  50994. if ( node.isAtomic === true ) {
  50995. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  50996. return NodeAccess.READ_WRITE;
  50997. }
  50998. return NodeAccess.READ_ONLY;
  50999. }
  51000. return node.access;
  51001. }
  51002. /**
  51003. * Returns A WGSL snippet representing the storage access.
  51004. *
  51005. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  51006. * @param {string} shaderStage - The shader stage.
  51007. * @return {string} The WGSL snippet representing the storage access.
  51008. */
  51009. getStorageAccess( node, shaderStage ) {
  51010. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  51011. }
  51012. /**
  51013. * This method is one of the more important ones since it's responsible
  51014. * for generating a matching binding instance for the given uniform node.
  51015. *
  51016. * These bindings are later used in the renderer to create bind groups
  51017. * and layouts.
  51018. *
  51019. * @param {UniformNode} node - The uniform node.
  51020. * @param {string} type - The node data type.
  51021. * @param {string} shaderStage - The shader stage.
  51022. * @param {?string} [name=null] - An optional uniform name.
  51023. * @return {NodeUniform} The node uniform object.
  51024. */
  51025. getUniformFromNode( node, type, shaderStage, name = null ) {
  51026. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  51027. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  51028. if ( nodeData.uniformGPU === undefined ) {
  51029. let uniformGPU;
  51030. const group = node.groupNode;
  51031. const groupName = group.name;
  51032. const bindings = this.getBindGroupArray( groupName, shaderStage );
  51033. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  51034. let texture = null;
  51035. const access = this.getNodeAccess( node, shaderStage );
  51036. if ( type === 'texture' || type === 'storageTexture' ) {
  51037. if ( node.value.is3DTexture === true ) {
  51038. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51039. } else {
  51040. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  51041. }
  51042. } else if ( type === 'cubeTexture' ) {
  51043. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  51044. } else if ( type === 'texture3D' ) {
  51045. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51046. }
  51047. texture.store = node.isStorageTextureNode === true;
  51048. texture.mipLevel = texture.store ? node.mipLevel : 0;
  51049. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51050. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  51051. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  51052. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51053. bindings.push( sampler, texture );
  51054. uniformGPU = [ sampler, texture ];
  51055. } else {
  51056. bindings.push( texture );
  51057. uniformGPU = [ texture ];
  51058. }
  51059. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51060. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  51061. const buffer = new bufferClass( node, group );
  51062. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51063. bindings.push( buffer );
  51064. uniformGPU = buffer;
  51065. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  51066. } else {
  51067. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  51068. let uniformsGroup = uniformsStage[ groupName ];
  51069. if ( uniformsGroup === undefined ) {
  51070. uniformsGroup = new NodeUniformsGroup( groupName, group );
  51071. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51072. uniformsStage[ groupName ] = uniformsGroup;
  51073. bindings.push( uniformsGroup );
  51074. }
  51075. uniformGPU = this.getNodeUniform( uniformNode, type );
  51076. uniformsGroup.addUniform( uniformGPU );
  51077. }
  51078. nodeData.uniformGPU = uniformGPU;
  51079. }
  51080. return uniformNode;
  51081. }
  51082. /**
  51083. * This method should be used whenever builtins are required in nodes.
  51084. * The internal builtins data structure will make sure builtins are
  51085. * defined in the WGSL source.
  51086. *
  51087. * @param {string} name - The builtin name.
  51088. * @param {string} property - The property name.
  51089. * @param {string} type - The node data type.
  51090. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51091. * @return {string} The property name.
  51092. */
  51093. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  51094. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  51095. if ( map.has( name ) === false ) {
  51096. map.set( name, {
  51097. name,
  51098. property,
  51099. type
  51100. } );
  51101. }
  51102. return property;
  51103. }
  51104. /**
  51105. * Returns `true` if the given builtin is defined in the given shader stage.
  51106. *
  51107. * @param {string} name - The builtin name.
  51108. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51109. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  51110. */
  51111. hasBuiltin( name, shaderStage = this.shaderStage ) {
  51112. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  51113. }
  51114. /**
  51115. * Returns the vertex index builtin.
  51116. *
  51117. * @return {string} The vertex index.
  51118. */
  51119. getVertexIndex() {
  51120. if ( this.shaderStage === 'vertex' ) {
  51121. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  51122. }
  51123. return 'vertexIndex';
  51124. }
  51125. /**
  51126. * Builds the given shader node.
  51127. *
  51128. * @param {ShaderNodeInternal} shaderNode - The shader node.
  51129. * @return {string} The WGSL function code.
  51130. */
  51131. buildFunctionCode( shaderNode ) {
  51132. const layout = shaderNode.layout;
  51133. const flowData = this.flowShaderNode( shaderNode );
  51134. const parameters = [];
  51135. for ( const input of layout.inputs ) {
  51136. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  51137. }
  51138. //
  51139. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  51140. ${ flowData.vars }
  51141. ${ flowData.code }
  51142. `;
  51143. if ( flowData.result ) {
  51144. code += `\treturn ${ flowData.result };\n`;
  51145. }
  51146. code += '\n}\n';
  51147. //
  51148. return code;
  51149. }
  51150. /**
  51151. * Contextually returns either the vertex stage instance index builtin
  51152. * or the linearized index of an compute invocation within a grid of workgroups.
  51153. *
  51154. * @return {string} The instance index.
  51155. */
  51156. getInstanceIndex() {
  51157. if ( this.shaderStage === 'vertex' ) {
  51158. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  51159. }
  51160. return 'instanceIndex';
  51161. }
  51162. /**
  51163. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  51164. *
  51165. * @return {string} The invocation local index.
  51166. */
  51167. getInvocationLocalIndex() {
  51168. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  51169. }
  51170. /**
  51171. * Returns a builtin representing the size of a subgroup within the current shader.
  51172. *
  51173. * @return {string} The subgroup size.
  51174. */
  51175. getSubgroupSize() {
  51176. this.enableSubGroups();
  51177. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51178. }
  51179. /**
  51180. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  51181. *
  51182. * @return {string} The invocation subgroup index.
  51183. */
  51184. getInvocationSubgroupIndex() {
  51185. this.enableSubGroups();
  51186. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  51187. }
  51188. /**
  51189. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  51190. *
  51191. * @return {string} The subgroup index.
  51192. */
  51193. getSubgroupIndex() {
  51194. this.enableSubGroups();
  51195. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  51196. }
  51197. /**
  51198. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  51199. *
  51200. * @return {null} Null.
  51201. */
  51202. getDrawIndex() {
  51203. return null;
  51204. }
  51205. /**
  51206. * Returns the front facing builtin.
  51207. *
  51208. * @return {string} The front facing builtin.
  51209. */
  51210. getFrontFacing() {
  51211. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  51212. }
  51213. /**
  51214. * Returns the frag coord builtin.
  51215. *
  51216. * @return {string} The frag coord builtin.
  51217. */
  51218. getFragCoord() {
  51219. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  51220. }
  51221. /**
  51222. * Returns the frag depth builtin.
  51223. *
  51224. * @return {string} The frag depth builtin.
  51225. */
  51226. getFragDepth() {
  51227. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  51228. }
  51229. /**
  51230. * Returns the clip distances builtin.
  51231. *
  51232. * @return {string} The clip distances builtin.
  51233. */
  51234. getClipDistance() {
  51235. return 'varyings.hw_clip_distances';
  51236. }
  51237. /**
  51238. * Whether to flip texture data along its vertical axis or not.
  51239. *
  51240. * @return {boolean} Returns always `false` in context of WGSL.
  51241. */
  51242. isFlipY() {
  51243. return false;
  51244. }
  51245. /**
  51246. * Enables the given directive for the given shader stage.
  51247. *
  51248. * @param {string} name - The directive name.
  51249. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  51250. */
  51251. enableDirective( name, shaderStage = this.shaderStage ) {
  51252. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  51253. stage.add( name );
  51254. }
  51255. /**
  51256. * Returns the directives of the given shader stage as a WGSL string.
  51257. *
  51258. * @param {string} shaderStage - The shader stage.
  51259. * @return {string} A WGSL snippet that enables the directives of the given stage.
  51260. */
  51261. getDirectives( shaderStage ) {
  51262. const snippets = [];
  51263. const directives = this.directives[ shaderStage ];
  51264. if ( directives !== undefined ) {
  51265. for ( const directive of directives ) {
  51266. snippets.push( `enable ${directive};` );
  51267. }
  51268. }
  51269. return snippets.join( '\n' );
  51270. }
  51271. /**
  51272. * Enables the 'subgroups' directive.
  51273. */
  51274. enableSubGroups() {
  51275. this.enableDirective( 'subgroups' );
  51276. }
  51277. /**
  51278. * Enables the 'subgroups-f16' directive.
  51279. */
  51280. enableSubgroupsF16() {
  51281. this.enableDirective( 'subgroups-f16' );
  51282. }
  51283. /**
  51284. * Enables the 'clip_distances' directive.
  51285. */
  51286. enableClipDistances() {
  51287. this.enableDirective( 'clip_distances' );
  51288. }
  51289. /**
  51290. * Enables the 'f16' directive.
  51291. */
  51292. enableShaderF16() {
  51293. this.enableDirective( 'f16' );
  51294. }
  51295. /**
  51296. * Enables the 'dual_source_blending' directive.
  51297. */
  51298. enableDualSourceBlending() {
  51299. this.enableDirective( 'dual_source_blending' );
  51300. }
  51301. /**
  51302. * Enables hardware clipping.
  51303. *
  51304. * @param {string} planeCount - The clipping plane count.
  51305. */
  51306. enableHardwareClipping( planeCount ) {
  51307. this.enableClipDistances();
  51308. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  51309. }
  51310. /**
  51311. * Returns the builtins of the given shader stage as a WGSL string.
  51312. *
  51313. * @param {string} shaderStage - The shader stage.
  51314. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  51315. */
  51316. getBuiltins( shaderStage ) {
  51317. const snippets = [];
  51318. const builtins = this.builtins[ shaderStage ];
  51319. if ( builtins !== undefined ) {
  51320. for ( const { name, property, type } of builtins.values() ) {
  51321. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  51322. }
  51323. }
  51324. return snippets.join( ',\n\t' );
  51325. }
  51326. /**
  51327. * This method should be used when a new scoped buffer is used in context of
  51328. * compute shaders. It adds the array to the internal data structure which is
  51329. * later used to generate the respective WGSL.
  51330. *
  51331. * @param {string} name - The array name.
  51332. * @param {string} scope - The scope.
  51333. * @param {string} bufferType - The buffer type.
  51334. * @param {string} bufferCount - The buffer count.
  51335. * @return {string} The array name.
  51336. */
  51337. getScopedArray( name, scope, bufferType, bufferCount ) {
  51338. if ( this.scopedArrays.has( name ) === false ) {
  51339. this.scopedArrays.set( name, {
  51340. name,
  51341. scope,
  51342. bufferType,
  51343. bufferCount
  51344. } );
  51345. }
  51346. return name;
  51347. }
  51348. /**
  51349. * Returns the scoped arrays of the given shader stage as a WGSL string.
  51350. *
  51351. * @param {string} shaderStage - The shader stage.
  51352. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  51353. * Returns `undefined` when used in the vertex or fragment stage.
  51354. */
  51355. getScopedArrays( shaderStage ) {
  51356. if ( shaderStage !== 'compute' ) {
  51357. return;
  51358. }
  51359. const snippets = [];
  51360. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  51361. const type = this.getType( bufferType );
  51362. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  51363. }
  51364. return snippets.join( '\n' );
  51365. }
  51366. /**
  51367. * Returns the shader attributes of the given shader stage as a WGSL string.
  51368. *
  51369. * @param {string} shaderStage - The shader stage.
  51370. * @return {string} The WGSL snippet that defines the shader attributes.
  51371. */
  51372. getAttributes( shaderStage ) {
  51373. const snippets = [];
  51374. if ( shaderStage === 'compute' ) {
  51375. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  51376. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  51377. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  51378. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  51379. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  51380. this.enableDirective( 'subgroups', shaderStage );
  51381. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51382. }
  51383. }
  51384. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  51385. const builtins = this.getBuiltins( 'attribute' );
  51386. if ( builtins ) snippets.push( builtins );
  51387. const attributes = this.getAttributesArray();
  51388. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  51389. const attribute = attributes[ index ];
  51390. const name = attribute.name;
  51391. const type = this.getType( attribute.type );
  51392. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  51393. }
  51394. }
  51395. return snippets.join( ',\n\t' );
  51396. }
  51397. /**
  51398. * Returns the members of the given struct type node as a WGSL string.
  51399. *
  51400. * @param {StructTypeNode} struct - The struct type node.
  51401. * @return {string} The WGSL snippet that defines the struct members.
  51402. */
  51403. getStructMembers( struct ) {
  51404. const snippets = [];
  51405. for ( const member of struct.members ) {
  51406. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  51407. let type = this.getType( member.type );
  51408. if ( member.atomic ) {
  51409. type = 'atomic< ' + type + ' >';
  51410. }
  51411. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  51412. }
  51413. if ( struct.output ) {
  51414. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  51415. }
  51416. return snippets.join( ',\n' );
  51417. }
  51418. /**
  51419. * Returns the structs of the given shader stage as a WGSL string.
  51420. *
  51421. * @param {string} shaderStage - The shader stage.
  51422. * @return {string} The WGSL snippet that defines the structs.
  51423. */
  51424. getStructs( shaderStage ) {
  51425. let result = '';
  51426. const structs = this.structs[ shaderStage ];
  51427. if ( structs.length > 0 ) {
  51428. const snippets = [];
  51429. for ( const struct of structs ) {
  51430. let snippet = `struct ${ struct.name } {\n`;
  51431. snippet += this.getStructMembers( struct );
  51432. snippet += '\n};';
  51433. snippets.push( snippet );
  51434. }
  51435. result = '\n' + snippets.join( '\n\n' ) + '\n';
  51436. }
  51437. return result;
  51438. }
  51439. /**
  51440. * Returns a WGSL string representing a variable.
  51441. *
  51442. * @param {string} type - The variable's type.
  51443. * @param {string} name - The variable's name.
  51444. * @param {?number} [count=null] - The array length.
  51445. * @return {string} The WGSL snippet that defines a variable.
  51446. */
  51447. getVar( type, name, count = null ) {
  51448. let snippet = `var ${ name } : `;
  51449. if ( count !== null ) {
  51450. snippet += this.generateArrayDeclaration( type, count );
  51451. } else {
  51452. snippet += this.getType( type );
  51453. }
  51454. return snippet;
  51455. }
  51456. /**
  51457. * Returns the variables of the given shader stage as a WGSL string.
  51458. *
  51459. * @param {string} shaderStage - The shader stage.
  51460. * @return {string} The WGSL snippet that defines the variables.
  51461. */
  51462. getVars( shaderStage ) {
  51463. const snippets = [];
  51464. const vars = this.vars[ shaderStage ];
  51465. if ( vars !== undefined ) {
  51466. for ( const variable of vars ) {
  51467. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  51468. }
  51469. }
  51470. return `\n${ snippets.join( '\n' ) }\n`;
  51471. }
  51472. /**
  51473. * Returns the varyings of the given shader stage as a WGSL string.
  51474. *
  51475. * @param {string} shaderStage - The shader stage.
  51476. * @return {string} The WGSL snippet that defines the varyings.
  51477. */
  51478. getVaryings( shaderStage ) {
  51479. const snippets = [];
  51480. if ( shaderStage === 'vertex' ) {
  51481. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  51482. }
  51483. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  51484. const varyings = this.varyings;
  51485. const vars = this.vars[ shaderStage ];
  51486. for ( let index = 0; index < varyings.length; index ++ ) {
  51487. const varying = varyings[ index ];
  51488. if ( varying.needsInterpolation ) {
  51489. let attributesSnippet = `@location( ${index} )`;
  51490. if ( varying.interpolationType ) {
  51491. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  51492. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  51493. // Otherwise, optimize interpolation when sensible
  51494. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  51495. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  51496. }
  51497. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  51498. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  51499. vars.push( varying );
  51500. }
  51501. }
  51502. }
  51503. const builtins = this.getBuiltins( shaderStage );
  51504. if ( builtins ) snippets.push( builtins );
  51505. const code = snippets.join( ',\n\t' );
  51506. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  51507. }
  51508. isCustomStruct( nodeUniform ) {
  51509. const attribute = nodeUniform.value;
  51510. const bufferNode = nodeUniform.node;
  51511. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  51512. const isStructArray =
  51513. ( bufferNode.value && bufferNode.value.array ) &&
  51514. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  51515. return isAttributeStructType && ! isStructArray;
  51516. }
  51517. /**
  51518. * Returns the uniforms of the given shader stage as a WGSL string.
  51519. *
  51520. * @param {string} shaderStage - The shader stage.
  51521. * @return {string} The WGSL snippet that defines the uniforms.
  51522. */
  51523. getUniforms( shaderStage ) {
  51524. const uniforms = this.uniforms[ shaderStage ];
  51525. const bindingSnippets = [];
  51526. const bufferSnippets = [];
  51527. const structSnippets = [];
  51528. const uniformGroups = {};
  51529. for ( const uniform of uniforms ) {
  51530. const groupName = uniform.groupNode.name;
  51531. const uniformIndexes = this.bindingsIndexes[ groupName ];
  51532. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  51533. const texture = uniform.node.value;
  51534. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  51535. if ( this.isSampleCompare( texture ) ) {
  51536. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  51537. } else {
  51538. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  51539. }
  51540. }
  51541. let textureType;
  51542. let multisampled = '';
  51543. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51544. if ( primarySamples > 1 ) {
  51545. multisampled = '_multisampled';
  51546. }
  51547. if ( texture.isCubeTexture === true ) {
  51548. textureType = 'texture_cube<f32>';
  51549. } else if ( texture.isDepthTexture === true ) {
  51550. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  51551. textureType = `texture${ multisampled }_2d<f32>`;
  51552. } else {
  51553. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  51554. }
  51555. } else if ( uniform.node.isStorageTextureNode === true ) {
  51556. const format = getFormat( texture );
  51557. const access = this.getStorageAccess( uniform.node, shaderStage );
  51558. const is3D = uniform.node.value.is3DTexture;
  51559. const isArrayTexture = uniform.node.value.isArrayTexture;
  51560. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  51561. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  51562. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  51563. textureType = 'texture_2d_array<f32>';
  51564. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  51565. textureType = 'texture_3d<f32>';
  51566. } else {
  51567. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  51568. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  51569. }
  51570. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  51571. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  51572. const bufferNode = uniform.node;
  51573. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  51574. const bufferCount = bufferNode.bufferCount;
  51575. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  51576. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  51577. if ( this.isCustomStruct( uniform ) ) {
  51578. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  51579. } else {
  51580. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  51581. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  51582. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  51583. }
  51584. } else {
  51585. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  51586. const groupName = uniform.groupNode.name;
  51587. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  51588. index: uniformIndexes.binding ++,
  51589. id: uniformIndexes.group,
  51590. snippets: []
  51591. } );
  51592. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  51593. }
  51594. }
  51595. for ( const name in uniformGroups ) {
  51596. const group = uniformGroups[ name ];
  51597. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  51598. }
  51599. let code = bindingSnippets.join( '\n' );
  51600. code += bufferSnippets.join( '\n' );
  51601. code += structSnippets.join( '\n' );
  51602. return code;
  51603. }
  51604. /**
  51605. * Controls the code build of the shader stages.
  51606. */
  51607. buildCode() {
  51608. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  51609. this.sortBindingGroups();
  51610. for ( const shaderStage in shadersData ) {
  51611. this.shaderStage = shaderStage;
  51612. const stageData = shadersData[ shaderStage ];
  51613. stageData.uniforms = this.getUniforms( shaderStage );
  51614. stageData.attributes = this.getAttributes( shaderStage );
  51615. stageData.varyings = this.getVaryings( shaderStage );
  51616. stageData.structs = this.getStructs( shaderStage );
  51617. stageData.vars = this.getVars( shaderStage );
  51618. stageData.codes = this.getCodes( shaderStage );
  51619. stageData.directives = this.getDirectives( shaderStage );
  51620. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  51621. //
  51622. let flow = '// code\n\n';
  51623. flow += this.flowCode[ shaderStage ];
  51624. const flowNodes = this.flowNodes[ shaderStage ];
  51625. const mainNode = flowNodes[ flowNodes.length - 1 ];
  51626. const outputNode = mainNode.outputNode;
  51627. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  51628. for ( const node of flowNodes ) {
  51629. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  51630. const slotName = node.name;
  51631. if ( slotName ) {
  51632. if ( flow.length > 0 ) flow += '\n';
  51633. flow += `\t// flow -> ${ slotName }\n`;
  51634. }
  51635. flow += `${ flowSlotData.code }\n\t`;
  51636. if ( node === mainNode && shaderStage !== 'compute' ) {
  51637. flow += '// result\n\n\t';
  51638. if ( shaderStage === 'vertex' ) {
  51639. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  51640. } else if ( shaderStage === 'fragment' ) {
  51641. if ( isOutputStruct ) {
  51642. stageData.returnType = outputNode.getNodeType( this );
  51643. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  51644. flow += `return ${ flowSlotData.result };`;
  51645. } else {
  51646. let structSnippet = '\t@location(0) color: vec4<f32>';
  51647. const builtins = this.getBuiltins( 'output' );
  51648. if ( builtins ) structSnippet += ',\n\t' + builtins;
  51649. stageData.returnType = 'OutputStruct';
  51650. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  51651. stageData.structs += '\nvar<private> output : OutputStruct;';
  51652. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  51653. }
  51654. }
  51655. }
  51656. }
  51657. stageData.flow = flow;
  51658. }
  51659. this.shaderStage = null;
  51660. if ( this.material !== null ) {
  51661. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  51662. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  51663. } else {
  51664. // Early strictly validated in computeNode
  51665. const workgroupSize = this.object.workgroupSize;
  51666. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  51667. }
  51668. }
  51669. /**
  51670. * Returns the native shader method name for a given generic name.
  51671. *
  51672. * @param {string} method - The method name to resolve.
  51673. * @param {?string} [output=null] - An optional output.
  51674. * @return {string} The resolved WGSL method name.
  51675. */
  51676. getMethod( method, output = null ) {
  51677. let wgslMethod;
  51678. if ( output !== null ) {
  51679. wgslMethod = this._getWGSLMethod( method + '_' + output );
  51680. }
  51681. if ( wgslMethod === undefined ) {
  51682. wgslMethod = this._getWGSLMethod( method );
  51683. }
  51684. return wgslMethod || method;
  51685. }
  51686. /**
  51687. * Returns the bitcast method name for a given input and outputType.
  51688. *
  51689. * @param {string} type - The output type to bitcast to.
  51690. * @return {string} The resolved WGSL bitcast invocation.
  51691. */
  51692. getBitcastMethod( type ) {
  51693. const dataType = this.getType( type );
  51694. return `bitcast<${ dataType }>`;
  51695. }
  51696. /**
  51697. * Returns the native snippet for a ternary operation.
  51698. *
  51699. * @param {string} condSnippet - The condition determining which expression gets resolved.
  51700. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  51701. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  51702. * @return {string} The resolved method name.
  51703. */
  51704. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  51705. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  51706. }
  51707. /**
  51708. * Returns the WGSL type of the given node data type.
  51709. *
  51710. * @param {string} type - The node data type.
  51711. * @return {string} The WGSL type.
  51712. */
  51713. getType( type ) {
  51714. return wgslTypeLib[ type ] || type;
  51715. }
  51716. /**
  51717. * Whether the requested feature is available or not.
  51718. *
  51719. * @param {string} name - The requested feature.
  51720. * @return {boolean} Whether the requested feature is supported or not.
  51721. */
  51722. isAvailable( name ) {
  51723. let result = supports[ name ];
  51724. if ( result === undefined ) {
  51725. if ( name === 'float32Filterable' ) {
  51726. result = this.renderer.hasFeature( 'float32-filterable' );
  51727. } else if ( name === 'clipDistance' ) {
  51728. result = this.renderer.hasFeature( 'clip-distances' );
  51729. }
  51730. supports[ name ] = result;
  51731. }
  51732. return result;
  51733. }
  51734. /**
  51735. * Returns the native shader method name for a given generic name.
  51736. *
  51737. * @private
  51738. * @param {string} method - The method name to resolve.
  51739. * @return {string} The resolved WGSL method name.
  51740. */
  51741. _getWGSLMethod( method ) {
  51742. if ( wgslPolyfill[ method ] !== undefined ) {
  51743. this._include( method );
  51744. }
  51745. return wgslMethods[ method ];
  51746. }
  51747. /**
  51748. * Includes the given method name into the current
  51749. * function node.
  51750. *
  51751. * @private
  51752. * @param {string} name - The method name to include.
  51753. * @return {CodeNode} The respective code node.
  51754. */
  51755. _include( name ) {
  51756. const codeNode = wgslPolyfill[ name ];
  51757. codeNode.build( this );
  51758. this.addInclude( codeNode );
  51759. return codeNode;
  51760. }
  51761. /**
  51762. * Returns a WGSL vertex shader based on the given shader data.
  51763. *
  51764. * @private
  51765. * @param {Object} shaderData - The shader data.
  51766. * @return {string} The vertex shader.
  51767. */
  51768. _getWGSLVertexCode( shaderData ) {
  51769. return `${ this.getSignature() }
  51770. // directives
  51771. ${shaderData.directives}
  51772. // structs
  51773. ${shaderData.structs}
  51774. // uniforms
  51775. ${shaderData.uniforms}
  51776. // varyings
  51777. ${shaderData.varyings}
  51778. var<private> varyings : VaryingsStruct;
  51779. // codes
  51780. ${shaderData.codes}
  51781. @vertex
  51782. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  51783. // vars
  51784. ${shaderData.vars}
  51785. // flow
  51786. ${shaderData.flow}
  51787. return varyings;
  51788. }
  51789. `;
  51790. }
  51791. /**
  51792. * Returns a WGSL fragment shader based on the given shader data.
  51793. *
  51794. * @private
  51795. * @param {Object} shaderData - The shader data.
  51796. * @return {string} The vertex shader.
  51797. */
  51798. _getWGSLFragmentCode( shaderData ) {
  51799. return `${ this.getSignature() }
  51800. // global
  51801. ${ diagnostics }
  51802. // structs
  51803. ${shaderData.structs}
  51804. // uniforms
  51805. ${shaderData.uniforms}
  51806. // codes
  51807. ${shaderData.codes}
  51808. @fragment
  51809. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  51810. // vars
  51811. ${shaderData.vars}
  51812. // flow
  51813. ${shaderData.flow}
  51814. }
  51815. `;
  51816. }
  51817. /**
  51818. * Returns a WGSL compute shader based on the given shader data.
  51819. *
  51820. * @private
  51821. * @param {Object} shaderData - The shader data.
  51822. * @param {string} workgroupSize - The workgroup size.
  51823. * @return {string} The vertex shader.
  51824. */
  51825. _getWGSLComputeCode( shaderData, workgroupSize ) {
  51826. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  51827. return `${ this.getSignature() }
  51828. // directives
  51829. ${ shaderData.directives }
  51830. // system
  51831. var<private> instanceIndex : u32;
  51832. // locals
  51833. ${ shaderData.scopedArrays }
  51834. // structs
  51835. ${ shaderData.structs }
  51836. // uniforms
  51837. ${ shaderData.uniforms }
  51838. // codes
  51839. ${ shaderData.codes }
  51840. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  51841. fn main( ${ shaderData.attributes } ) {
  51842. // system
  51843. instanceIndex = globalId.x
  51844. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  51845. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  51846. // vars
  51847. ${ shaderData.vars }
  51848. // flow
  51849. ${ shaderData.flow }
  51850. }
  51851. `;
  51852. }
  51853. /**
  51854. * Returns a WGSL struct based on the given name and variables.
  51855. *
  51856. * @private
  51857. * @param {string} name - The struct name.
  51858. * @param {string} vars - The struct variables.
  51859. * @return {string} The WGSL snippet representing a struct.
  51860. */
  51861. _getWGSLStruct( name, vars ) {
  51862. return `
  51863. struct ${name} {
  51864. ${vars}
  51865. };`;
  51866. }
  51867. /**
  51868. * Returns a WGSL struct binding.
  51869. *
  51870. * @private
  51871. * @param {string} name - The struct name.
  51872. * @param {string} vars - The struct variables.
  51873. * @param {string} access - The access.
  51874. * @param {number} [binding=0] - The binding index.
  51875. * @param {number} [group=0] - The group index.
  51876. * @return {string} The WGSL snippet representing a struct binding.
  51877. */
  51878. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  51879. const structName = name + 'Struct';
  51880. const structSnippet = this._getWGSLStruct( structName, vars );
  51881. return `${structSnippet}
  51882. @binding( ${ binding } ) @group( ${ group } )
  51883. var<${access}> ${ name } : ${ structName };`;
  51884. }
  51885. }
  51886. /**
  51887. * A WebGPU backend utility module with common helpers.
  51888. *
  51889. * @private
  51890. */
  51891. class WebGPUUtils {
  51892. /**
  51893. * Constructs a new utility object.
  51894. *
  51895. * @param {WebGPUBackend} backend - The WebGPU backend.
  51896. */
  51897. constructor( backend ) {
  51898. /**
  51899. * A reference to the WebGPU backend.
  51900. *
  51901. * @type {WebGPUBackend}
  51902. */
  51903. this.backend = backend;
  51904. }
  51905. /**
  51906. * Returns the depth/stencil GPU format for the given render context.
  51907. *
  51908. * @param {RenderContext} renderContext - The render context.
  51909. * @return {string} The depth/stencil GPU texture format.
  51910. */
  51911. getCurrentDepthStencilFormat( renderContext ) {
  51912. let format;
  51913. if ( renderContext.depthTexture !== null ) {
  51914. format = this.getTextureFormatGPU( renderContext.depthTexture );
  51915. } else if ( renderContext.depth && renderContext.stencil ) {
  51916. format = GPUTextureFormat.Depth24PlusStencil8;
  51917. } else if ( renderContext.depth ) {
  51918. format = GPUTextureFormat.Depth24Plus;
  51919. }
  51920. return format;
  51921. }
  51922. /**
  51923. * Returns the GPU format for the given texture.
  51924. *
  51925. * @param {Texture} texture - The texture.
  51926. * @return {string} The GPU texture format.
  51927. */
  51928. getTextureFormatGPU( texture ) {
  51929. return this.backend.get( texture ).format;
  51930. }
  51931. /**
  51932. * Returns an object that defines the multi-sampling state of the given texture.
  51933. *
  51934. * @param {Texture} texture - The texture.
  51935. * @return {Object} The multi-sampling state.
  51936. */
  51937. getTextureSampleData( texture ) {
  51938. let samples;
  51939. if ( texture.isFramebufferTexture ) {
  51940. samples = 1;
  51941. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  51942. const renderer = this.backend.renderer;
  51943. const renderTarget = renderer.getRenderTarget();
  51944. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  51945. } else if ( texture.renderTarget ) {
  51946. samples = texture.renderTarget.samples;
  51947. }
  51948. samples = samples || 1;
  51949. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  51950. const primarySamples = isMSAA ? 1 : samples;
  51951. return { samples, primarySamples, isMSAA };
  51952. }
  51953. /**
  51954. * Returns the default color attachment's GPU format of the current render context.
  51955. *
  51956. * @param {RenderContext} renderContext - The render context.
  51957. * @return {string} The GPU texture format of the default color attachment.
  51958. */
  51959. getCurrentColorFormat( renderContext ) {
  51960. let format;
  51961. if ( renderContext.textures !== null ) {
  51962. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  51963. } else {
  51964. format = this.getPreferredCanvasFormat(); // default context format
  51965. }
  51966. return format;
  51967. }
  51968. /**
  51969. * Returns the GPU formats of all color attachments of the current render context.
  51970. *
  51971. * @param {RenderContext} renderContext - The render context.
  51972. * @return {Array<string>} The GPU texture formats of all color attachments.
  51973. */
  51974. getCurrentColorFormats( renderContext ) {
  51975. if ( renderContext.textures !== null ) {
  51976. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  51977. } else {
  51978. return [ this.getPreferredCanvasFormat() ]; // default context format
  51979. }
  51980. }
  51981. /**
  51982. * Returns the output color space of the current render context.
  51983. *
  51984. * @param {RenderContext} renderContext - The render context.
  51985. * @return {string} The output color space.
  51986. */
  51987. getCurrentColorSpace( renderContext ) {
  51988. if ( renderContext.textures !== null ) {
  51989. return renderContext.textures[ 0 ].colorSpace;
  51990. }
  51991. return this.backend.renderer.outputColorSpace;
  51992. }
  51993. /**
  51994. * Returns GPU primitive topology for the given object and material.
  51995. *
  51996. * @param {Object3D} object - The 3D object.
  51997. * @param {Material} material - The material.
  51998. * @return {string} The GPU primitive topology.
  51999. */
  52000. getPrimitiveTopology( object, material ) {
  52001. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  52002. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  52003. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  52004. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  52005. }
  52006. /**
  52007. * Returns a modified sample count from the given sample count value.
  52008. *
  52009. * That is required since WebGPU only supports either 1 or 4.
  52010. *
  52011. * @param {number} sampleCount - The input sample count.
  52012. * @return {number} The (potentially updated) output sample count.
  52013. */
  52014. getSampleCount( sampleCount ) {
  52015. return sampleCount >= 4 ? 4 : 1;
  52016. }
  52017. /**
  52018. * Returns the sample count of the given render context.
  52019. *
  52020. * @param {RenderContext} renderContext - The render context.
  52021. * @return {number} The sample count.
  52022. */
  52023. getSampleCountRenderContext( renderContext ) {
  52024. if ( renderContext.textures !== null ) {
  52025. return this.getSampleCount( renderContext.sampleCount );
  52026. }
  52027. return this.getSampleCount( this.backend.renderer.currentSamples );
  52028. }
  52029. /**
  52030. * Returns the preferred canvas format.
  52031. *
  52032. * There is a separate method for this so it's possible to
  52033. * honor edge cases for specific devices.
  52034. *
  52035. * @return {string} The GPU texture format of the canvas.
  52036. */
  52037. getPreferredCanvasFormat() {
  52038. const outputType = this.backend.parameters.outputType;
  52039. if ( outputType === undefined ) {
  52040. return navigator.gpu.getPreferredCanvasFormat();
  52041. } else if ( outputType === UnsignedByteType ) {
  52042. return GPUTextureFormat.BGRA8Unorm;
  52043. } else if ( outputType === HalfFloatType ) {
  52044. return GPUTextureFormat.RGBA16Float;
  52045. } else {
  52046. throw new Error( 'Unsupported outputType' );
  52047. }
  52048. }
  52049. }
  52050. const typedArraysToVertexFormatPrefix = new Map( [
  52051. [ Int8Array, [ 'sint8', 'snorm8' ]],
  52052. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  52053. [ Int16Array, [ 'sint16', 'snorm16' ]],
  52054. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  52055. [ Int32Array, [ 'sint32', 'snorm32' ]],
  52056. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  52057. [ Float32Array, [ 'float32', ]],
  52058. ] );
  52059. if ( typeof Float16Array !== 'undefined' ) {
  52060. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  52061. }
  52062. const typedAttributeToVertexFormatPrefix = new Map( [
  52063. [ Float16BufferAttribute, [ 'float16', ]],
  52064. ] );
  52065. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  52066. [ Int32Array, 'sint32' ],
  52067. [ Int16Array, 'sint32' ], // patch for INT16
  52068. [ Uint32Array, 'uint32' ],
  52069. [ Uint16Array, 'uint32' ], // patch for UINT16
  52070. [ Float32Array, 'float32' ]
  52071. ] );
  52072. /**
  52073. * A WebGPU backend utility module for managing shader attributes.
  52074. *
  52075. * @private
  52076. */
  52077. class WebGPUAttributeUtils {
  52078. /**
  52079. * Constructs a new utility object.
  52080. *
  52081. * @param {WebGPUBackend} backend - The WebGPU backend.
  52082. */
  52083. constructor( backend ) {
  52084. /**
  52085. * A reference to the WebGPU backend.
  52086. *
  52087. * @type {WebGPUBackend}
  52088. */
  52089. this.backend = backend;
  52090. }
  52091. /**
  52092. * Creates the GPU buffer for the given buffer attribute.
  52093. *
  52094. * @param {BufferAttribute} attribute - The buffer attribute.
  52095. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  52096. */
  52097. createAttribute( attribute, usage ) {
  52098. const bufferAttribute = this._getBufferAttribute( attribute );
  52099. const backend = this.backend;
  52100. const bufferData = backend.get( bufferAttribute );
  52101. let buffer = bufferData.buffer;
  52102. if ( buffer === undefined ) {
  52103. const device = backend.device;
  52104. let array = bufferAttribute.array;
  52105. // patch for INT16 and UINT16
  52106. if ( attribute.normalized === false ) {
  52107. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  52108. array = new Int32Array( array );
  52109. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  52110. array = new Uint32Array( array );
  52111. if ( usage & GPUBufferUsage.INDEX ) {
  52112. for ( let i = 0; i < array.length; i ++ ) {
  52113. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  52114. }
  52115. }
  52116. }
  52117. }
  52118. bufferAttribute.array = array;
  52119. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  52120. array = new array.constructor( bufferAttribute.count * 4 );
  52121. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52122. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52123. }
  52124. // Update BufferAttribute
  52125. bufferAttribute.itemSize = 4;
  52126. bufferAttribute.array = array;
  52127. bufferData._force3to4BytesAlignment = true;
  52128. }
  52129. // ensure 4 byte alignment
  52130. const byteLength = array.byteLength;
  52131. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  52132. buffer = device.createBuffer( {
  52133. label: bufferAttribute.name,
  52134. size: size,
  52135. usage: usage,
  52136. mappedAtCreation: true
  52137. } );
  52138. new array.constructor( buffer.getMappedRange() ).set( array );
  52139. buffer.unmap();
  52140. bufferData.buffer = buffer;
  52141. }
  52142. }
  52143. /**
  52144. * Updates the GPU buffer of the given buffer attribute.
  52145. *
  52146. * @param {BufferAttribute} attribute - The buffer attribute.
  52147. */
  52148. updateAttribute( attribute ) {
  52149. const bufferAttribute = this._getBufferAttribute( attribute );
  52150. const backend = this.backend;
  52151. const device = backend.device;
  52152. const bufferData = backend.get( bufferAttribute );
  52153. const buffer = backend.get( bufferAttribute ).buffer;
  52154. let array = bufferAttribute.array;
  52155. // if storage buffer ensure 4 byte alignment
  52156. if ( bufferData._force3to4BytesAlignment === true ) {
  52157. array = new array.constructor( bufferAttribute.count * 4 );
  52158. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52159. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52160. }
  52161. bufferAttribute.array = array;
  52162. }
  52163. const isTypedArray = this._isTypedArray( array );
  52164. const updateRanges = bufferAttribute.updateRanges;
  52165. if ( updateRanges.length === 0 ) {
  52166. // Not using update ranges
  52167. device.queue.writeBuffer(
  52168. buffer,
  52169. 0,
  52170. array,
  52171. 0
  52172. );
  52173. } else {
  52174. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  52175. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52176. const range = updateRanges[ i ];
  52177. let dataOffset, size;
  52178. if ( bufferData._force3to4BytesAlignment === true ) {
  52179. const vertexStart = Math.floor( range.start / 3 );
  52180. const vertexCount = Math.ceil( range.count / 3 );
  52181. dataOffset = vertexStart * 4 * byteOffsetFactor;
  52182. size = vertexCount * 4 * byteOffsetFactor;
  52183. } else {
  52184. dataOffset = range.start * byteOffsetFactor;
  52185. size = range.count * byteOffsetFactor;
  52186. }
  52187. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52188. device.queue.writeBuffer(
  52189. buffer,
  52190. bufferOffset,
  52191. array,
  52192. dataOffset,
  52193. size
  52194. );
  52195. }
  52196. bufferAttribute.clearUpdateRanges();
  52197. }
  52198. }
  52199. /**
  52200. * This method creates the vertex buffer layout data which are
  52201. * require when creating a render pipeline for the given render object.
  52202. *
  52203. * @param {RenderObject} renderObject - The render object.
  52204. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  52205. */
  52206. createShaderVertexBuffers( renderObject ) {
  52207. const attributes = renderObject.getAttributes();
  52208. const vertexBuffers = new Map();
  52209. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  52210. const geometryAttribute = attributes[ slot ];
  52211. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  52212. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  52213. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  52214. if ( vertexBufferLayout === undefined ) {
  52215. let arrayStride, stepMode;
  52216. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  52217. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  52218. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52219. } else {
  52220. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  52221. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52222. }
  52223. // patch for INT16 and UINT16
  52224. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  52225. arrayStride = 4;
  52226. }
  52227. vertexBufferLayout = {
  52228. arrayStride,
  52229. attributes: [],
  52230. stepMode
  52231. };
  52232. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  52233. }
  52234. const format = this._getVertexFormat( geometryAttribute );
  52235. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  52236. vertexBufferLayout.attributes.push( {
  52237. shaderLocation: slot,
  52238. offset,
  52239. format
  52240. } );
  52241. }
  52242. return Array.from( vertexBuffers.values() );
  52243. }
  52244. /**
  52245. * Destroys the GPU buffer of the given buffer attribute.
  52246. *
  52247. * @param {BufferAttribute} attribute - The buffer attribute.
  52248. */
  52249. destroyAttribute( attribute ) {
  52250. const backend = this.backend;
  52251. const data = backend.get( this._getBufferAttribute( attribute ) );
  52252. data.buffer.destroy();
  52253. backend.delete( attribute );
  52254. }
  52255. /**
  52256. * This method performs a readback operation by moving buffer data from
  52257. * a storage buffer attribute from the GPU to the CPU.
  52258. *
  52259. * @async
  52260. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52261. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52262. */
  52263. async getArrayBufferAsync( attribute ) {
  52264. const backend = this.backend;
  52265. const device = backend.device;
  52266. const data = backend.get( this._getBufferAttribute( attribute ) );
  52267. const bufferGPU = data.buffer;
  52268. const size = bufferGPU.size;
  52269. const readBufferGPU = device.createBuffer( {
  52270. label: `${ attribute.name }_readback`,
  52271. size,
  52272. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52273. } );
  52274. const cmdEncoder = device.createCommandEncoder( {
  52275. label: `readback_encoder_${ attribute.name }`
  52276. } );
  52277. cmdEncoder.copyBufferToBuffer(
  52278. bufferGPU,
  52279. 0,
  52280. readBufferGPU,
  52281. 0,
  52282. size
  52283. );
  52284. const gpuCommands = cmdEncoder.finish();
  52285. device.queue.submit( [ gpuCommands ] );
  52286. await readBufferGPU.mapAsync( GPUMapMode.READ );
  52287. const arrayBuffer = readBufferGPU.getMappedRange();
  52288. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  52289. readBufferGPU.unmap();
  52290. return dstBuffer.buffer;
  52291. }
  52292. /**
  52293. * Returns the vertex format of the given buffer attribute.
  52294. *
  52295. * @private
  52296. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  52297. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  52298. */
  52299. _getVertexFormat( geometryAttribute ) {
  52300. const { itemSize, normalized } = geometryAttribute;
  52301. const ArrayType = geometryAttribute.array.constructor;
  52302. const AttributeType = geometryAttribute.constructor;
  52303. let format;
  52304. if ( itemSize === 1 ) {
  52305. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  52306. } else {
  52307. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  52308. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  52309. if ( prefix ) {
  52310. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  52311. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  52312. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  52313. if ( paddedItemSize % 1 ) {
  52314. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  52315. }
  52316. format = `${prefix}x${paddedItemSize}`;
  52317. }
  52318. }
  52319. if ( ! format ) {
  52320. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  52321. }
  52322. return format;
  52323. }
  52324. /**
  52325. * Returns `true` if the given array is a typed array.
  52326. *
  52327. * @private
  52328. * @param {any} array - The array.
  52329. * @return {boolean} Whether the given array is a typed array or not.
  52330. */
  52331. _isTypedArray( array ) {
  52332. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  52333. }
  52334. /**
  52335. * Utility method for handling interleaved buffer attributes correctly.
  52336. * To process them, their `InterleavedBuffer` is returned.
  52337. *
  52338. * @private
  52339. * @param {BufferAttribute} attribute - The attribute.
  52340. * @return {BufferAttribute|InterleavedBuffer}
  52341. */
  52342. _getBufferAttribute( attribute ) {
  52343. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  52344. return attribute;
  52345. }
  52346. }
  52347. /**
  52348. * A WebGPU backend utility module for managing bindings.
  52349. *
  52350. * When reading the documentation it's helpful to keep in mind that
  52351. * all class definitions starting with 'GPU*' are modules from the
  52352. * WebGPU API. So for example `BindGroup` is a class from the engine
  52353. * whereas `GPUBindGroup` is a class from WebGPU.
  52354. *
  52355. * @private
  52356. */
  52357. class WebGPUBindingUtils {
  52358. /**
  52359. * Constructs a new utility object.
  52360. *
  52361. * @param {WebGPUBackend} backend - The WebGPU backend.
  52362. */
  52363. constructor( backend ) {
  52364. /**
  52365. * A reference to the WebGPU backend.
  52366. *
  52367. * @type {WebGPUBackend}
  52368. */
  52369. this.backend = backend;
  52370. /**
  52371. * A cache for managing bind group layouts.
  52372. *
  52373. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  52374. */
  52375. this.bindGroupLayoutCache = new WeakMap();
  52376. }
  52377. /**
  52378. * Creates a GPU bind group layout for the given bind group.
  52379. *
  52380. * @param {BindGroup} bindGroup - The bind group.
  52381. * @return {GPUBindGroupLayout} The GPU bind group layout.
  52382. */
  52383. createBindingsLayout( bindGroup ) {
  52384. const backend = this.backend;
  52385. const device = backend.device;
  52386. const entries = [];
  52387. let index = 0;
  52388. for ( const binding of bindGroup.bindings ) {
  52389. const bindingGPU = {
  52390. binding: index ++,
  52391. visibility: binding.visibility
  52392. };
  52393. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  52394. const buffer = {}; // GPUBufferBindingLayout
  52395. if ( binding.isStorageBuffer ) {
  52396. if ( binding.visibility & 4 ) {
  52397. // compute
  52398. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  52399. buffer.type = GPUBufferBindingType.Storage;
  52400. } else {
  52401. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52402. }
  52403. } else {
  52404. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52405. }
  52406. }
  52407. bindingGPU.buffer = buffer;
  52408. } else if ( binding.isSampledTexture && binding.store ) {
  52409. const storageTexture = {}; // GPUStorageTextureBindingLayout
  52410. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  52411. const access = binding.access;
  52412. if ( access === NodeAccess.READ_WRITE ) {
  52413. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  52414. } else if ( access === NodeAccess.WRITE_ONLY ) {
  52415. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  52416. } else {
  52417. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  52418. }
  52419. if ( binding.texture.isArrayTexture ) {
  52420. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52421. } else if ( binding.texture.is3DTexture ) {
  52422. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  52423. }
  52424. bindingGPU.storageTexture = storageTexture;
  52425. } else if ( binding.isSampledTexture ) {
  52426. const texture = {}; // GPUTextureBindingLayout
  52427. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  52428. if ( primarySamples > 1 ) {
  52429. texture.multisampled = true;
  52430. if ( ! binding.texture.isDepthTexture ) {
  52431. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52432. }
  52433. }
  52434. if ( binding.texture.isDepthTexture ) {
  52435. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  52436. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52437. } else {
  52438. texture.sampleType = GPUTextureSampleType.Depth;
  52439. }
  52440. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  52441. const type = binding.texture.type;
  52442. if ( type === IntType ) {
  52443. texture.sampleType = GPUTextureSampleType.SInt;
  52444. } else if ( type === UnsignedIntType ) {
  52445. texture.sampleType = GPUTextureSampleType.UInt;
  52446. } else if ( type === FloatType ) {
  52447. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  52448. texture.sampleType = GPUTextureSampleType.Float;
  52449. } else {
  52450. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52451. }
  52452. }
  52453. }
  52454. if ( binding.isSampledCubeTexture ) {
  52455. texture.viewDimension = GPUTextureViewDimension.Cube;
  52456. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52457. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52458. } else if ( binding.isSampledTexture3D ) {
  52459. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  52460. }
  52461. bindingGPU.texture = texture;
  52462. } else if ( binding.isSampler ) {
  52463. const sampler = {}; // GPUSamplerBindingLayout
  52464. if ( binding.texture.isDepthTexture ) {
  52465. if ( binding.texture.compareFunction !== null ) {
  52466. sampler.type = GPUSamplerBindingType.Comparison;
  52467. } else if ( backend.compatibilityMode ) {
  52468. sampler.type = GPUSamplerBindingType.NonFiltering;
  52469. }
  52470. }
  52471. bindingGPU.sampler = sampler;
  52472. } else {
  52473. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  52474. }
  52475. entries.push( bindingGPU );
  52476. }
  52477. return device.createBindGroupLayout( { entries } );
  52478. }
  52479. /**
  52480. * Creates bindings from the given bind group definition.
  52481. *
  52482. * @param {BindGroup} bindGroup - The bind group.
  52483. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52484. * @param {number} cacheIndex - The cache index.
  52485. * @param {number} version - The version.
  52486. */
  52487. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  52488. const { backend, bindGroupLayoutCache } = this;
  52489. const bindingsData = backend.get( bindGroup );
  52490. // setup (static) binding layout and (dynamic) binding group
  52491. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  52492. if ( bindLayoutGPU === undefined ) {
  52493. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  52494. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  52495. }
  52496. let bindGroupGPU;
  52497. if ( cacheIndex > 0 ) {
  52498. if ( bindingsData.groups === undefined ) {
  52499. bindingsData.groups = [];
  52500. bindingsData.versions = [];
  52501. }
  52502. if ( bindingsData.versions[ cacheIndex ] === version ) {
  52503. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  52504. }
  52505. }
  52506. if ( bindGroupGPU === undefined ) {
  52507. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  52508. if ( cacheIndex > 0 ) {
  52509. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  52510. bindingsData.versions[ cacheIndex ] = version;
  52511. }
  52512. }
  52513. bindingsData.group = bindGroupGPU;
  52514. bindingsData.layout = bindLayoutGPU;
  52515. }
  52516. /**
  52517. * Updates a buffer binding.
  52518. *
  52519. * @param {Buffer} binding - The buffer binding to update.
  52520. */
  52521. updateBinding( binding ) {
  52522. const backend = this.backend;
  52523. const device = backend.device;
  52524. const buffer = binding.buffer;
  52525. const bufferGPU = backend.get( binding ).buffer;
  52526. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  52527. }
  52528. /**
  52529. * Creates a GPU bind group for the camera index.
  52530. *
  52531. * @param {Uint32Array} data - The index data.
  52532. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  52533. * @return {GPUBindGroup} The GPU bind group.
  52534. */
  52535. createBindGroupIndex( data, layout ) {
  52536. const backend = this.backend;
  52537. const device = backend.device;
  52538. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52539. const index = data[ 0 ];
  52540. const buffer = device.createBuffer( {
  52541. label: 'bindingCameraIndex_' + index,
  52542. size: 16, // uint(4) * 4
  52543. usage: usage
  52544. } );
  52545. device.queue.writeBuffer( buffer, 0, data, 0 );
  52546. const entries = [ { binding: 0, resource: { buffer } } ];
  52547. return device.createBindGroup( {
  52548. label: 'bindGroupCameraIndex_' + index,
  52549. layout,
  52550. entries
  52551. } );
  52552. }
  52553. /**
  52554. * Creates a GPU bind group for the given bind group and GPU layout.
  52555. *
  52556. * @param {BindGroup} bindGroup - The bind group.
  52557. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  52558. * @return {GPUBindGroup} The GPU bind group.
  52559. */
  52560. createBindGroup( bindGroup, layoutGPU ) {
  52561. const backend = this.backend;
  52562. const device = backend.device;
  52563. let bindingPoint = 0;
  52564. const entriesGPU = [];
  52565. for ( const binding of bindGroup.bindings ) {
  52566. if ( binding.isUniformBuffer ) {
  52567. const bindingData = backend.get( binding );
  52568. if ( bindingData.buffer === undefined ) {
  52569. const byteLength = binding.byteLength;
  52570. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52571. const bufferGPU = device.createBuffer( {
  52572. label: 'bindingBuffer_' + binding.name,
  52573. size: byteLength,
  52574. usage: usage
  52575. } );
  52576. bindingData.buffer = bufferGPU;
  52577. }
  52578. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52579. } else if ( binding.isStorageBuffer ) {
  52580. const bindingData = backend.get( binding );
  52581. if ( bindingData.buffer === undefined ) {
  52582. const attribute = binding.attribute;
  52583. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  52584. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  52585. bindingData.buffer = backend.get( attribute ).buffer;
  52586. }
  52587. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52588. } else if ( binding.isSampledTexture ) {
  52589. const textureData = backend.get( binding.texture );
  52590. let resourceGPU;
  52591. if ( textureData.externalTexture !== undefined ) {
  52592. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  52593. } else {
  52594. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  52595. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  52596. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  52597. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  52598. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  52599. }
  52600. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  52601. resourceGPU = textureData[ propertyName ];
  52602. if ( resourceGPU === undefined ) {
  52603. const aspectGPU = GPUTextureAspect.All;
  52604. let dimensionViewGPU;
  52605. if ( binding.isSampledCubeTexture ) {
  52606. dimensionViewGPU = GPUTextureViewDimension.Cube;
  52607. } else if ( binding.isSampledTexture3D ) {
  52608. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  52609. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52610. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  52611. } else {
  52612. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  52613. }
  52614. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  52615. }
  52616. }
  52617. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  52618. } else if ( binding.isSampler ) {
  52619. const textureGPU = backend.get( binding.texture );
  52620. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  52621. }
  52622. bindingPoint ++;
  52623. }
  52624. return device.createBindGroup( {
  52625. label: 'bindGroup_' + bindGroup.name,
  52626. layout: layoutGPU,
  52627. entries: entriesGPU
  52628. } );
  52629. }
  52630. }
  52631. /**
  52632. * A WebGPU backend utility module for managing pipelines.
  52633. *
  52634. * @private
  52635. */
  52636. class WebGPUPipelineUtils {
  52637. /**
  52638. * Constructs a new utility object.
  52639. *
  52640. * @param {WebGPUBackend} backend - The WebGPU backend.
  52641. */
  52642. constructor( backend ) {
  52643. /**
  52644. * A reference to the WebGPU backend.
  52645. *
  52646. * @type {WebGPUBackend}
  52647. */
  52648. this.backend = backend;
  52649. /**
  52650. * A Weak Map that tracks the active pipeline for render or compute passes.
  52651. *
  52652. * @private
  52653. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  52654. */
  52655. this._activePipelines = new WeakMap();
  52656. }
  52657. /**
  52658. * Sets the given pipeline for the given pass. The method makes sure to only set the
  52659. * pipeline when necessary.
  52660. *
  52661. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  52662. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  52663. */
  52664. setPipeline( pass, pipeline ) {
  52665. const currentPipeline = this._activePipelines.get( pass );
  52666. if ( currentPipeline !== pipeline ) {
  52667. pass.setPipeline( pipeline );
  52668. this._activePipelines.set( pass, pipeline );
  52669. }
  52670. }
  52671. /**
  52672. * Returns the sample count derived from the given render context.
  52673. *
  52674. * @private
  52675. * @param {RenderContext} renderContext - The render context.
  52676. * @return {number} The sample count.
  52677. */
  52678. _getSampleCount( renderContext ) {
  52679. return this.backend.utils.getSampleCountRenderContext( renderContext );
  52680. }
  52681. /**
  52682. * Creates a render pipeline for the given render object.
  52683. *
  52684. * @param {RenderObject} renderObject - The render object.
  52685. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52686. */
  52687. createRenderPipeline( renderObject, promises ) {
  52688. const { object, material, geometry, pipeline } = renderObject;
  52689. const { vertexProgram, fragmentProgram } = pipeline;
  52690. const backend = this.backend;
  52691. const device = backend.device;
  52692. const utils = backend.utils;
  52693. const pipelineData = backend.get( pipeline );
  52694. // bind group layouts
  52695. const bindGroupLayouts = [];
  52696. for ( const bindGroup of renderObject.getBindings() ) {
  52697. const bindingsData = backend.get( bindGroup );
  52698. bindGroupLayouts.push( bindingsData.layout );
  52699. }
  52700. // vertex buffers
  52701. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  52702. // blending
  52703. let blending;
  52704. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  52705. blending = this._getBlending( material );
  52706. }
  52707. // stencil
  52708. let stencilFront = {};
  52709. if ( material.stencilWrite === true ) {
  52710. stencilFront = {
  52711. compare: this._getStencilCompare( material ),
  52712. failOp: this._getStencilOperation( material.stencilFail ),
  52713. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  52714. passOp: this._getStencilOperation( material.stencilZPass )
  52715. };
  52716. }
  52717. const colorWriteMask = this._getColorWriteMask( material );
  52718. const targets = [];
  52719. if ( renderObject.context.textures !== null ) {
  52720. const textures = renderObject.context.textures;
  52721. for ( let i = 0; i < textures.length; i ++ ) {
  52722. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  52723. targets.push( {
  52724. format: colorFormat,
  52725. blend: blending,
  52726. writeMask: colorWriteMask
  52727. } );
  52728. }
  52729. } else {
  52730. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52731. targets.push( {
  52732. format: colorFormat,
  52733. blend: blending,
  52734. writeMask: colorWriteMask
  52735. } );
  52736. }
  52737. const vertexModule = backend.get( vertexProgram ).module;
  52738. const fragmentModule = backend.get( fragmentProgram ).module;
  52739. const primitiveState = this._getPrimitiveState( object, geometry, material );
  52740. const depthCompare = this._getDepthCompare( material );
  52741. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52742. const sampleCount = this._getSampleCount( renderObject.context );
  52743. const pipelineDescriptor = {
  52744. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  52745. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  52746. fragment: Object.assign( {}, fragmentModule, { targets } ),
  52747. primitive: primitiveState,
  52748. multisample: {
  52749. count: sampleCount,
  52750. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  52751. },
  52752. layout: device.createPipelineLayout( {
  52753. bindGroupLayouts
  52754. } )
  52755. };
  52756. const depthStencil = {};
  52757. const renderDepth = renderObject.context.depth;
  52758. const renderStencil = renderObject.context.stencil;
  52759. if ( renderDepth === true || renderStencil === true ) {
  52760. if ( renderDepth === true ) {
  52761. depthStencil.format = depthStencilFormat;
  52762. depthStencil.depthWriteEnabled = material.depthWrite;
  52763. depthStencil.depthCompare = depthCompare;
  52764. }
  52765. if ( renderStencil === true ) {
  52766. depthStencil.stencilFront = stencilFront;
  52767. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  52768. depthStencil.stencilReadMask = material.stencilFuncMask;
  52769. depthStencil.stencilWriteMask = material.stencilWriteMask;
  52770. }
  52771. if ( material.polygonOffset === true ) {
  52772. depthStencil.depthBias = material.polygonOffsetUnits;
  52773. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  52774. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  52775. }
  52776. pipelineDescriptor.depthStencil = depthStencil;
  52777. }
  52778. if ( promises === null ) {
  52779. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  52780. } else {
  52781. const p = new Promise( ( resolve /*, reject*/ ) => {
  52782. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  52783. pipelineData.pipeline = pipeline;
  52784. resolve();
  52785. } );
  52786. } );
  52787. promises.push( p );
  52788. }
  52789. }
  52790. /**
  52791. * Creates GPU render bundle encoder for the given render context.
  52792. *
  52793. * @param {RenderContext} renderContext - The render context.
  52794. * @param {?string} [label='renderBundleEncoder'] - The label.
  52795. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  52796. */
  52797. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  52798. const backend = this.backend;
  52799. const { utils, device } = backend;
  52800. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  52801. const colorFormats = utils.getCurrentColorFormats( renderContext );
  52802. const sampleCount = this._getSampleCount( renderContext );
  52803. const descriptor = {
  52804. label,
  52805. colorFormats,
  52806. depthStencilFormat,
  52807. sampleCount
  52808. };
  52809. return device.createRenderBundleEncoder( descriptor );
  52810. }
  52811. /**
  52812. * Creates a compute pipeline for the given compute node.
  52813. *
  52814. * @param {ComputePipeline} pipeline - The compute pipeline.
  52815. * @param {Array<BindGroup>} bindings - The bindings.
  52816. */
  52817. createComputePipeline( pipeline, bindings ) {
  52818. const backend = this.backend;
  52819. const device = backend.device;
  52820. const computeProgram = backend.get( pipeline.computeProgram ).module;
  52821. const pipelineGPU = backend.get( pipeline );
  52822. // bind group layouts
  52823. const bindGroupLayouts = [];
  52824. for ( const bindingsGroup of bindings ) {
  52825. const bindingsData = backend.get( bindingsGroup );
  52826. bindGroupLayouts.push( bindingsData.layout );
  52827. }
  52828. pipelineGPU.pipeline = device.createComputePipeline( {
  52829. compute: computeProgram,
  52830. layout: device.createPipelineLayout( {
  52831. bindGroupLayouts
  52832. } )
  52833. } );
  52834. }
  52835. /**
  52836. * Returns the blending state as a descriptor object required
  52837. * for the pipeline creation.
  52838. *
  52839. * @private
  52840. * @param {Material} material - The material.
  52841. * @return {Object} The blending state.
  52842. */
  52843. _getBlending( material ) {
  52844. let color, alpha;
  52845. const blending = material.blending;
  52846. const blendSrc = material.blendSrc;
  52847. const blendDst = material.blendDst;
  52848. const blendEquation = material.blendEquation;
  52849. if ( blending === CustomBlending ) {
  52850. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  52851. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  52852. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  52853. color = {
  52854. srcFactor: this._getBlendFactor( blendSrc ),
  52855. dstFactor: this._getBlendFactor( blendDst ),
  52856. operation: this._getBlendOperation( blendEquation )
  52857. };
  52858. alpha = {
  52859. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  52860. dstFactor: this._getBlendFactor( blendDstAlpha ),
  52861. operation: this._getBlendOperation( blendEquationAlpha )
  52862. };
  52863. } else {
  52864. const premultipliedAlpha = material.premultipliedAlpha;
  52865. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  52866. color = {
  52867. srcFactor: srcRGB,
  52868. dstFactor: dstRGB,
  52869. operation: GPUBlendOperation.Add
  52870. };
  52871. alpha = {
  52872. srcFactor: srcAlpha,
  52873. dstFactor: dstAlpha,
  52874. operation: GPUBlendOperation.Add
  52875. };
  52876. };
  52877. if ( premultipliedAlpha ) {
  52878. switch ( blending ) {
  52879. case NormalBlending:
  52880. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52881. break;
  52882. case AdditiveBlending:
  52883. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52884. break;
  52885. case SubtractiveBlending:
  52886. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52887. break;
  52888. case MultiplyBlending:
  52889. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52890. break;
  52891. }
  52892. } else {
  52893. switch ( blending ) {
  52894. case NormalBlending:
  52895. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52896. break;
  52897. case AdditiveBlending:
  52898. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52899. break;
  52900. case SubtractiveBlending:
  52901. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  52902. break;
  52903. case MultiplyBlending:
  52904. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  52905. break;
  52906. }
  52907. }
  52908. }
  52909. if ( color !== undefined && alpha !== undefined ) {
  52910. return { color, alpha };
  52911. } else {
  52912. error( 'WebGPURenderer: Invalid blending: ', blending );
  52913. }
  52914. }
  52915. /**
  52916. * Returns the GPU blend factor which is required for the pipeline creation.
  52917. *
  52918. * @private
  52919. * @param {number} blend - The blend factor as a three.js constant.
  52920. * @return {string} The GPU blend factor.
  52921. */
  52922. _getBlendFactor( blend ) {
  52923. let blendFactor;
  52924. switch ( blend ) {
  52925. case ZeroFactor:
  52926. blendFactor = GPUBlendFactor.Zero;
  52927. break;
  52928. case OneFactor:
  52929. blendFactor = GPUBlendFactor.One;
  52930. break;
  52931. case SrcColorFactor:
  52932. blendFactor = GPUBlendFactor.Src;
  52933. break;
  52934. case OneMinusSrcColorFactor:
  52935. blendFactor = GPUBlendFactor.OneMinusSrc;
  52936. break;
  52937. case SrcAlphaFactor:
  52938. blendFactor = GPUBlendFactor.SrcAlpha;
  52939. break;
  52940. case OneMinusSrcAlphaFactor:
  52941. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  52942. break;
  52943. case DstColorFactor:
  52944. blendFactor = GPUBlendFactor.Dst;
  52945. break;
  52946. case OneMinusDstColorFactor:
  52947. blendFactor = GPUBlendFactor.OneMinusDst;
  52948. break;
  52949. case DstAlphaFactor:
  52950. blendFactor = GPUBlendFactor.DstAlpha;
  52951. break;
  52952. case OneMinusDstAlphaFactor:
  52953. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  52954. break;
  52955. case SrcAlphaSaturateFactor:
  52956. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  52957. break;
  52958. case BlendColorFactor:
  52959. blendFactor = GPUBlendFactor.Constant;
  52960. break;
  52961. case OneMinusBlendColorFactor:
  52962. blendFactor = GPUBlendFactor.OneMinusConstant;
  52963. break;
  52964. default:
  52965. error( 'WebGPURenderer: Blend factor not supported.', blend );
  52966. }
  52967. return blendFactor;
  52968. }
  52969. /**
  52970. * Returns the GPU stencil compare function which is required for the pipeline creation.
  52971. *
  52972. * @private
  52973. * @param {Material} material - The material.
  52974. * @return {string} The GPU stencil compare function.
  52975. */
  52976. _getStencilCompare( material ) {
  52977. let stencilCompare;
  52978. const stencilFunc = material.stencilFunc;
  52979. switch ( stencilFunc ) {
  52980. case NeverStencilFunc:
  52981. stencilCompare = GPUCompareFunction.Never;
  52982. break;
  52983. case AlwaysStencilFunc:
  52984. stencilCompare = GPUCompareFunction.Always;
  52985. break;
  52986. case LessStencilFunc:
  52987. stencilCompare = GPUCompareFunction.Less;
  52988. break;
  52989. case LessEqualStencilFunc:
  52990. stencilCompare = GPUCompareFunction.LessEqual;
  52991. break;
  52992. case EqualStencilFunc:
  52993. stencilCompare = GPUCompareFunction.Equal;
  52994. break;
  52995. case GreaterEqualStencilFunc:
  52996. stencilCompare = GPUCompareFunction.GreaterEqual;
  52997. break;
  52998. case GreaterStencilFunc:
  52999. stencilCompare = GPUCompareFunction.Greater;
  53000. break;
  53001. case NotEqualStencilFunc:
  53002. stencilCompare = GPUCompareFunction.NotEqual;
  53003. break;
  53004. default:
  53005. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  53006. }
  53007. return stencilCompare;
  53008. }
  53009. /**
  53010. * Returns the GPU stencil operation which is required for the pipeline creation.
  53011. *
  53012. * @private
  53013. * @param {number} op - A three.js constant defining the stencil operation.
  53014. * @return {string} The GPU stencil operation.
  53015. */
  53016. _getStencilOperation( op ) {
  53017. let stencilOperation;
  53018. switch ( op ) {
  53019. case KeepStencilOp:
  53020. stencilOperation = GPUStencilOperation.Keep;
  53021. break;
  53022. case ZeroStencilOp:
  53023. stencilOperation = GPUStencilOperation.Zero;
  53024. break;
  53025. case ReplaceStencilOp:
  53026. stencilOperation = GPUStencilOperation.Replace;
  53027. break;
  53028. case InvertStencilOp:
  53029. stencilOperation = GPUStencilOperation.Invert;
  53030. break;
  53031. case IncrementStencilOp:
  53032. stencilOperation = GPUStencilOperation.IncrementClamp;
  53033. break;
  53034. case DecrementStencilOp:
  53035. stencilOperation = GPUStencilOperation.DecrementClamp;
  53036. break;
  53037. case IncrementWrapStencilOp:
  53038. stencilOperation = GPUStencilOperation.IncrementWrap;
  53039. break;
  53040. case DecrementWrapStencilOp:
  53041. stencilOperation = GPUStencilOperation.DecrementWrap;
  53042. break;
  53043. default:
  53044. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  53045. }
  53046. return stencilOperation;
  53047. }
  53048. /**
  53049. * Returns the GPU blend operation which is required for the pipeline creation.
  53050. *
  53051. * @private
  53052. * @param {number} blendEquation - A three.js constant defining the blend equation.
  53053. * @return {string} The GPU blend operation.
  53054. */
  53055. _getBlendOperation( blendEquation ) {
  53056. let blendOperation;
  53057. switch ( blendEquation ) {
  53058. case AddEquation:
  53059. blendOperation = GPUBlendOperation.Add;
  53060. break;
  53061. case SubtractEquation:
  53062. blendOperation = GPUBlendOperation.Subtract;
  53063. break;
  53064. case ReverseSubtractEquation:
  53065. blendOperation = GPUBlendOperation.ReverseSubtract;
  53066. break;
  53067. case MinEquation:
  53068. blendOperation = GPUBlendOperation.Min;
  53069. break;
  53070. case MaxEquation:
  53071. blendOperation = GPUBlendOperation.Max;
  53072. break;
  53073. default:
  53074. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  53075. }
  53076. return blendOperation;
  53077. }
  53078. /**
  53079. * Returns the primitive state as a descriptor object required
  53080. * for the pipeline creation.
  53081. *
  53082. * @private
  53083. * @param {Object3D} object - The 3D object.
  53084. * @param {BufferGeometry} geometry - The geometry.
  53085. * @param {Material} material - The material.
  53086. * @return {Object} The primitive state.
  53087. */
  53088. _getPrimitiveState( object, geometry, material ) {
  53089. const descriptor = {};
  53090. const utils = this.backend.utils;
  53091. //
  53092. descriptor.topology = utils.getPrimitiveTopology( object, material );
  53093. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  53094. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53095. }
  53096. //
  53097. let flipSided = ( material.side === BackSide );
  53098. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  53099. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  53100. //
  53101. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  53102. return descriptor;
  53103. }
  53104. /**
  53105. * Returns the GPU color write mask which is required for the pipeline creation.
  53106. *
  53107. * @private
  53108. * @param {Material} material - The material.
  53109. * @return {number} The GPU color write mask.
  53110. */
  53111. _getColorWriteMask( material ) {
  53112. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  53113. }
  53114. /**
  53115. * Returns the GPU depth compare function which is required for the pipeline creation.
  53116. *
  53117. * @private
  53118. * @param {Material} material - The material.
  53119. * @return {string} The GPU depth compare function.
  53120. */
  53121. _getDepthCompare( material ) {
  53122. let depthCompare;
  53123. if ( material.depthTest === false ) {
  53124. depthCompare = GPUCompareFunction.Always;
  53125. } else {
  53126. const depthFunc = material.depthFunc;
  53127. switch ( depthFunc ) {
  53128. case NeverDepth:
  53129. depthCompare = GPUCompareFunction.Never;
  53130. break;
  53131. case AlwaysDepth:
  53132. depthCompare = GPUCompareFunction.Always;
  53133. break;
  53134. case LessDepth:
  53135. depthCompare = GPUCompareFunction.Less;
  53136. break;
  53137. case LessEqualDepth:
  53138. depthCompare = GPUCompareFunction.LessEqual;
  53139. break;
  53140. case EqualDepth:
  53141. depthCompare = GPUCompareFunction.Equal;
  53142. break;
  53143. case GreaterEqualDepth:
  53144. depthCompare = GPUCompareFunction.GreaterEqual;
  53145. break;
  53146. case GreaterDepth:
  53147. depthCompare = GPUCompareFunction.Greater;
  53148. break;
  53149. case NotEqualDepth:
  53150. depthCompare = GPUCompareFunction.NotEqual;
  53151. break;
  53152. default:
  53153. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  53154. }
  53155. }
  53156. return depthCompare;
  53157. }
  53158. }
  53159. /**
  53160. * Manages a pool of WebGPU timestamp queries for performance measurement.
  53161. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  53162. *
  53163. * @augments TimestampQueryPool
  53164. */
  53165. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  53166. /**
  53167. * Creates a new WebGPU timestamp query pool.
  53168. *
  53169. * @param {GPUDevice} device - The WebGPU device to create queries on.
  53170. * @param {string} type - The type identifier for this query pool.
  53171. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  53172. */
  53173. constructor( device, type, maxQueries = 2048 ) {
  53174. super( maxQueries );
  53175. this.device = device;
  53176. this.type = type;
  53177. this.querySet = this.device.createQuerySet( {
  53178. type: 'timestamp',
  53179. count: this.maxQueries,
  53180. label: `queryset_global_timestamp_${type}`
  53181. } );
  53182. const bufferSize = this.maxQueries * 8;
  53183. this.resolveBuffer = this.device.createBuffer( {
  53184. label: `buffer_timestamp_resolve_${type}`,
  53185. size: bufferSize,
  53186. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53187. } );
  53188. this.resultBuffer = this.device.createBuffer( {
  53189. label: `buffer_timestamp_result_${type}`,
  53190. size: bufferSize,
  53191. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53192. } );
  53193. }
  53194. /**
  53195. * Allocates a pair of queries for a given render context.
  53196. *
  53197. * @param {string} uid - A unique identifier for the render context.
  53198. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  53199. */
  53200. allocateQueriesForContext( uid ) {
  53201. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  53202. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  53203. 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() } ).` );
  53204. return null;
  53205. }
  53206. const baseOffset = this.currentQueryIndex;
  53207. this.currentQueryIndex += 2;
  53208. this.queryOffsets.set( uid, baseOffset );
  53209. return baseOffset;
  53210. }
  53211. /**
  53212. * Asynchronously resolves all pending queries and returns the total duration.
  53213. * If there's already a pending resolve operation, returns that promise instead.
  53214. *
  53215. * @async
  53216. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  53217. */
  53218. async resolveQueriesAsync() {
  53219. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  53220. return this.lastValue;
  53221. }
  53222. if ( this.pendingResolve ) {
  53223. return this.pendingResolve;
  53224. }
  53225. this.pendingResolve = this._resolveQueries();
  53226. try {
  53227. const result = await this.pendingResolve;
  53228. return result;
  53229. } finally {
  53230. this.pendingResolve = null;
  53231. }
  53232. }
  53233. /**
  53234. * Internal method to resolve queries and calculate total duration.
  53235. *
  53236. * @async
  53237. * @private
  53238. * @returns {Promise<number>} The total duration in milliseconds.
  53239. */
  53240. async _resolveQueries() {
  53241. if ( this.isDisposed ) {
  53242. return this.lastValue;
  53243. }
  53244. try {
  53245. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53246. return this.lastValue;
  53247. }
  53248. const currentOffsets = new Map( this.queryOffsets );
  53249. const queryCount = this.currentQueryIndex;
  53250. const bytesUsed = queryCount * 8;
  53251. // Reset state before GPU work
  53252. this.currentQueryIndex = 0;
  53253. this.queryOffsets.clear();
  53254. const commandEncoder = this.device.createCommandEncoder();
  53255. commandEncoder.resolveQuerySet(
  53256. this.querySet,
  53257. 0,
  53258. queryCount,
  53259. this.resolveBuffer,
  53260. 0
  53261. );
  53262. commandEncoder.copyBufferToBuffer(
  53263. this.resolveBuffer,
  53264. 0,
  53265. this.resultBuffer,
  53266. 0,
  53267. bytesUsed
  53268. );
  53269. const commandBuffer = commandEncoder.finish();
  53270. this.device.queue.submit( [ commandBuffer ] );
  53271. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53272. return this.lastValue;
  53273. }
  53274. // Create and track the mapping operation
  53275. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  53276. if ( this.isDisposed ) {
  53277. if ( this.resultBuffer.mapState === 'mapped' ) {
  53278. this.resultBuffer.unmap();
  53279. }
  53280. return this.lastValue;
  53281. }
  53282. //
  53283. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  53284. const framesDuration = {};
  53285. const frames = [];
  53286. for ( const [ uid, baseOffset ] of currentOffsets ) {
  53287. const match = uid.match( /^(.*):f(\d+)$/ );
  53288. const frame = parseInt( match[ 2 ] );
  53289. if ( frames.includes( frame ) === false ) {
  53290. frames.push( frame );
  53291. }
  53292. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  53293. const startTime = times[ baseOffset ];
  53294. const endTime = times[ baseOffset + 1 ];
  53295. const duration = Number( endTime - startTime ) / 1e6;
  53296. this.timestamps.set( uid, duration );
  53297. framesDuration[ frame ] += duration;
  53298. }
  53299. // Return the total duration of the last frame
  53300. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  53301. this.resultBuffer.unmap();
  53302. this.lastValue = totalDuration;
  53303. this.frames = frames;
  53304. return totalDuration;
  53305. } catch ( error ) {
  53306. error( 'Error resolving queries:', error );
  53307. if ( this.resultBuffer.mapState === 'mapped' ) {
  53308. this.resultBuffer.unmap();
  53309. }
  53310. return this.lastValue;
  53311. }
  53312. }
  53313. /**
  53314. * Dispose of the query pool.
  53315. *
  53316. * @async
  53317. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  53318. */
  53319. async dispose() {
  53320. if ( this.isDisposed ) {
  53321. return;
  53322. }
  53323. this.isDisposed = true;
  53324. // Wait for pending resolve operation
  53325. if ( this.pendingResolve ) {
  53326. try {
  53327. await this.pendingResolve;
  53328. } catch ( error ) {
  53329. error( 'Error waiting for pending resolve:', error );
  53330. }
  53331. }
  53332. // Ensure buffer is unmapped before destroying
  53333. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  53334. try {
  53335. this.resultBuffer.unmap();
  53336. } catch ( error ) {
  53337. error( 'Error unmapping buffer:', error );
  53338. }
  53339. }
  53340. // Destroy resources
  53341. if ( this.querySet ) {
  53342. this.querySet.destroy();
  53343. this.querySet = null;
  53344. }
  53345. if ( this.resolveBuffer ) {
  53346. this.resolveBuffer.destroy();
  53347. this.resolveBuffer = null;
  53348. }
  53349. if ( this.resultBuffer ) {
  53350. this.resultBuffer.destroy();
  53351. this.resultBuffer = null;
  53352. }
  53353. this.queryOffsets.clear();
  53354. this.pendingResolve = null;
  53355. }
  53356. }
  53357. /*// debugger tools
  53358. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  53359. //*/
  53360. /**
  53361. * A backend implementation targeting WebGPU.
  53362. *
  53363. * @private
  53364. * @augments Backend
  53365. */
  53366. class WebGPUBackend extends Backend {
  53367. /**
  53368. * WebGPUBackend options.
  53369. *
  53370. * @typedef {Object} WebGPUBackend~Options
  53371. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53372. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53373. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  53374. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53375. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53376. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53377. * @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.
  53378. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53379. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  53380. * @property {string} [powerPreference=undefined] - The power preference.
  53381. * @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.
  53382. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  53383. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53384. */
  53385. /**
  53386. * Constructs a new WebGPU backend.
  53387. *
  53388. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  53389. */
  53390. constructor( parameters = {} ) {
  53391. super( parameters );
  53392. /**
  53393. * This flag can be used for type testing.
  53394. *
  53395. * @type {boolean}
  53396. * @readonly
  53397. * @default true
  53398. */
  53399. this.isWebGPUBackend = true;
  53400. // some parameters require default values other than "undefined"
  53401. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  53402. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  53403. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  53404. /**
  53405. * Indicates whether the backend is in compatibility mode or not.
  53406. * @type {boolean}
  53407. * @default false
  53408. */
  53409. this.compatibilityMode = this.parameters.compatibilityMode;
  53410. /**
  53411. * A reference to the device.
  53412. *
  53413. * @type {?GPUDevice}
  53414. * @default null
  53415. */
  53416. this.device = null;
  53417. /**
  53418. * A reference to the default render pass descriptor.
  53419. *
  53420. * @type {?Object}
  53421. * @default null
  53422. */
  53423. this.defaultRenderPassdescriptor = null;
  53424. /**
  53425. * A reference to a backend module holding common utility functions.
  53426. *
  53427. * @type {WebGPUUtils}
  53428. */
  53429. this.utils = new WebGPUUtils( this );
  53430. /**
  53431. * A reference to a backend module holding shader attribute-related
  53432. * utility functions.
  53433. *
  53434. * @type {WebGPUAttributeUtils}
  53435. */
  53436. this.attributeUtils = new WebGPUAttributeUtils( this );
  53437. /**
  53438. * A reference to a backend module holding shader binding-related
  53439. * utility functions.
  53440. *
  53441. * @type {WebGPUBindingUtils}
  53442. */
  53443. this.bindingUtils = new WebGPUBindingUtils( this );
  53444. /**
  53445. * A reference to a backend module holding shader pipeline-related
  53446. * utility functions.
  53447. *
  53448. * @type {WebGPUPipelineUtils}
  53449. */
  53450. this.pipelineUtils = new WebGPUPipelineUtils( this );
  53451. /**
  53452. * A reference to a backend module holding shader texture-related
  53453. * utility functions.
  53454. *
  53455. * @type {WebGPUTextureUtils}
  53456. */
  53457. this.textureUtils = new WebGPUTextureUtils( this );
  53458. /**
  53459. * A map that manages the resolve buffers for occlusion queries.
  53460. *
  53461. * @type {Map<number,GPUBuffer>}
  53462. */
  53463. this.occludedResolveCache = new Map();
  53464. }
  53465. /**
  53466. * Initializes the backend so it is ready for usage.
  53467. *
  53468. * @async
  53469. * @param {Renderer} renderer - The renderer.
  53470. * @return {Promise} A Promise that resolves when the backend has been initialized.
  53471. */
  53472. async init( renderer ) {
  53473. await super.init( renderer );
  53474. //
  53475. const parameters = this.parameters;
  53476. // create the device if it is not passed with parameters
  53477. let device;
  53478. if ( parameters.device === undefined ) {
  53479. const adapterOptions = {
  53480. powerPreference: parameters.powerPreference,
  53481. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  53482. };
  53483. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  53484. if ( adapter === null ) {
  53485. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  53486. }
  53487. // feature support
  53488. const features = Object.values( GPUFeatureName );
  53489. const supportedFeatures = [];
  53490. for ( const name of features ) {
  53491. if ( adapter.features.has( name ) ) {
  53492. supportedFeatures.push( name );
  53493. }
  53494. }
  53495. const deviceDescriptor = {
  53496. requiredFeatures: supportedFeatures,
  53497. requiredLimits: parameters.requiredLimits
  53498. };
  53499. device = await adapter.requestDevice( deviceDescriptor );
  53500. } else {
  53501. device = parameters.device;
  53502. }
  53503. device.lost.then( ( info ) => {
  53504. const deviceLossInfo = {
  53505. api: 'WebGPU',
  53506. message: info.message || 'Unknown reason',
  53507. reason: info.reason || null,
  53508. originalEvent: info
  53509. };
  53510. renderer.onDeviceLost( deviceLossInfo );
  53511. } );
  53512. this.device = device;
  53513. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  53514. this.updateSize();
  53515. }
  53516. /**
  53517. * A reference to the context.
  53518. *
  53519. * @type {?GPUCanvasContext}
  53520. * @default null
  53521. */
  53522. get context() {
  53523. const canvasTarget = this.renderer.getCanvasTarget();
  53524. const canvasData = this.get( canvasTarget );
  53525. let context = canvasData.context;
  53526. if ( context === undefined ) {
  53527. const parameters = this.parameters;
  53528. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  53529. context = parameters.context;
  53530. } else {
  53531. context = canvasTarget.domElement.getContext( 'webgpu' );
  53532. }
  53533. // OffscreenCanvas does not have setAttribute, see #22811
  53534. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  53535. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  53536. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  53537. context.configure( {
  53538. device: this.device,
  53539. format: this.utils.getPreferredCanvasFormat(),
  53540. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  53541. alphaMode: alphaMode,
  53542. toneMapping: {
  53543. mode: toneMappingMode
  53544. }
  53545. } );
  53546. canvasData.context = context;
  53547. }
  53548. return context;
  53549. }
  53550. /**
  53551. * The coordinate system of the backend.
  53552. *
  53553. * @type {number}
  53554. * @readonly
  53555. */
  53556. get coordinateSystem() {
  53557. return WebGPUCoordinateSystem;
  53558. }
  53559. /**
  53560. * This method performs a readback operation by moving buffer data from
  53561. * a storage buffer attribute from the GPU to the CPU.
  53562. *
  53563. * @async
  53564. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53565. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53566. */
  53567. async getArrayBufferAsync( attribute ) {
  53568. return await this.attributeUtils.getArrayBufferAsync( attribute );
  53569. }
  53570. /**
  53571. * Returns the backend's rendering context.
  53572. *
  53573. * @return {GPUCanvasContext} The rendering context.
  53574. */
  53575. getContext() {
  53576. return this.context;
  53577. }
  53578. /**
  53579. * Returns the default render pass descriptor.
  53580. *
  53581. * In WebGPU, the default framebuffer must be configured
  53582. * like custom framebuffers so the backend needs a render
  53583. * pass descriptor even when rendering directly to screen.
  53584. *
  53585. * @private
  53586. * @return {Object} The render pass descriptor.
  53587. */
  53588. _getDefaultRenderPassDescriptor() {
  53589. const renderer = this.renderer;
  53590. const canvasTarget = renderer.getCanvasTarget();
  53591. const canvasData = this.get( canvasTarget );
  53592. const samples = renderer.currentSamples;
  53593. let descriptor = canvasData.descriptor;
  53594. if ( descriptor === undefined || canvasData.samples !== samples ) {
  53595. descriptor = {
  53596. colorAttachments: [ {
  53597. view: null
  53598. } ]
  53599. };
  53600. if ( renderer.depth === true || renderer.stencil === true ) {
  53601. descriptor.depthStencilAttachment = {
  53602. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  53603. };
  53604. }
  53605. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53606. if ( samples > 0 ) {
  53607. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  53608. } else {
  53609. colorAttachment.resolveTarget = undefined;
  53610. }
  53611. canvasData.descriptor = descriptor;
  53612. canvasData.samples = samples;
  53613. }
  53614. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53615. if ( samples > 0 ) {
  53616. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  53617. } else {
  53618. colorAttachment.view = this.context.getCurrentTexture().createView();
  53619. }
  53620. return descriptor;
  53621. }
  53622. /**
  53623. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  53624. *
  53625. * @param {RenderContext} renderContext - The render context.
  53626. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  53627. *
  53628. * @private
  53629. */
  53630. _isRenderCameraDepthArray( renderContext ) {
  53631. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  53632. }
  53633. /**
  53634. * Returns the render pass descriptor for the given render context.
  53635. *
  53636. * @private
  53637. * @param {RenderContext} renderContext - The render context.
  53638. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  53639. * @return {Object} The render pass descriptor.
  53640. */
  53641. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  53642. const renderTarget = renderContext.renderTarget;
  53643. const renderTargetData = this.get( renderTarget );
  53644. let descriptors = renderTargetData.descriptors;
  53645. if ( descriptors === undefined ||
  53646. renderTargetData.width !== renderTarget.width ||
  53647. renderTargetData.height !== renderTarget.height ||
  53648. renderTargetData.samples !== renderTarget.samples
  53649. ) {
  53650. descriptors = {};
  53651. renderTargetData.descriptors = descriptors;
  53652. }
  53653. const cacheKey = renderContext.getCacheKey();
  53654. let descriptorBase = descriptors[ cacheKey ];
  53655. if ( descriptorBase === undefined ) {
  53656. const textures = renderContext.textures;
  53657. const textureViews = [];
  53658. let sliceIndex;
  53659. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  53660. for ( let i = 0; i < textures.length; i ++ ) {
  53661. const textureData = this.get( textures[ i ] );
  53662. const viewDescriptor = {
  53663. label: `colorAttachment_${ i }`,
  53664. baseMipLevel: renderContext.activeMipmapLevel,
  53665. mipLevelCount: 1,
  53666. baseArrayLayer: renderContext.activeCubeFace,
  53667. arrayLayerCount: 1,
  53668. dimension: GPUTextureViewDimension.TwoD
  53669. };
  53670. if ( renderTarget.isRenderTarget3D ) {
  53671. sliceIndex = renderContext.activeCubeFace;
  53672. viewDescriptor.baseArrayLayer = 0;
  53673. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  53674. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53675. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  53676. if ( isRenderCameraDepthArray === true ) {
  53677. const cameras = renderContext.camera.cameras;
  53678. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  53679. const layerViewDescriptor = {
  53680. ...viewDescriptor,
  53681. baseArrayLayer: layer,
  53682. arrayLayerCount: 1,
  53683. dimension: GPUTextureViewDimension.TwoD
  53684. };
  53685. const textureView = textureData.texture.createView( layerViewDescriptor );
  53686. textureViews.push( {
  53687. view: textureView,
  53688. resolveTarget: undefined,
  53689. depthSlice: undefined
  53690. } );
  53691. }
  53692. } else {
  53693. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  53694. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53695. }
  53696. }
  53697. if ( isRenderCameraDepthArray !== true ) {
  53698. const textureView = textureData.texture.createView( viewDescriptor );
  53699. let view, resolveTarget;
  53700. if ( textureData.msaaTexture !== undefined ) {
  53701. view = textureData.msaaTexture.createView();
  53702. resolveTarget = textureView;
  53703. } else {
  53704. view = textureView;
  53705. resolveTarget = undefined;
  53706. }
  53707. textureViews.push( {
  53708. view,
  53709. resolveTarget,
  53710. depthSlice: sliceIndex
  53711. } );
  53712. }
  53713. }
  53714. descriptorBase = { textureViews };
  53715. if ( renderContext.depth ) {
  53716. const depthTextureData = this.get( renderContext.depthTexture );
  53717. const options = {};
  53718. if ( renderContext.depthTexture.isArrayTexture ) {
  53719. options.dimension = GPUTextureViewDimension.TwoD;
  53720. options.arrayLayerCount = 1;
  53721. options.baseArrayLayer = renderContext.activeCubeFace;
  53722. }
  53723. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  53724. }
  53725. descriptors[ cacheKey ] = descriptorBase;
  53726. renderTargetData.width = renderTarget.width;
  53727. renderTargetData.height = renderTarget.height;
  53728. renderTargetData.samples = renderTarget.samples;
  53729. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  53730. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  53731. }
  53732. const descriptor = {
  53733. colorAttachments: []
  53734. };
  53735. // Apply dynamic properties to cached views
  53736. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  53737. const viewInfo = descriptorBase.textureViews[ i ];
  53738. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  53739. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  53740. clearValue = colorAttachmentsConfig.clearValue;
  53741. }
  53742. descriptor.colorAttachments.push( {
  53743. view: viewInfo.view,
  53744. depthSlice: viewInfo.depthSlice,
  53745. resolveTarget: viewInfo.resolveTarget,
  53746. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  53747. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  53748. clearValue: clearValue
  53749. } );
  53750. }
  53751. if ( descriptorBase.depthStencilView ) {
  53752. descriptor.depthStencilAttachment = {
  53753. view: descriptorBase.depthStencilView
  53754. };
  53755. }
  53756. return descriptor;
  53757. }
  53758. /**
  53759. * This method is executed at the beginning of a render call and prepares
  53760. * the WebGPU state for upcoming render calls
  53761. *
  53762. * @param {RenderContext} renderContext - The render context.
  53763. */
  53764. beginRender( renderContext ) {
  53765. const renderContextData = this.get( renderContext );
  53766. //
  53767. const device = this.device;
  53768. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53769. let occlusionQuerySet;
  53770. if ( occlusionQueryCount > 0 ) {
  53771. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  53772. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  53773. // Get a reference to the array of objects with queries. The renderContextData property
  53774. // can be changed by another render pass before the buffer.mapAsyc() completes.
  53775. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  53776. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  53777. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  53778. //
  53779. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  53780. renderContextData.occlusionQuerySet = occlusionQuerySet;
  53781. renderContextData.occlusionQueryIndex = 0;
  53782. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  53783. renderContextData.lastOcclusionObject = null;
  53784. }
  53785. let descriptor;
  53786. if ( renderContext.textures === null ) {
  53787. descriptor = this._getDefaultRenderPassDescriptor();
  53788. } else {
  53789. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  53790. }
  53791. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  53792. descriptor.occlusionQuerySet = occlusionQuerySet;
  53793. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53794. if ( renderContext.textures !== null ) {
  53795. const colorAttachments = descriptor.colorAttachments;
  53796. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  53797. const colorAttachment = colorAttachments[ i ];
  53798. if ( renderContext.clearColor ) {
  53799. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  53800. colorAttachment.loadOp = GPULoadOp.Clear;
  53801. } else {
  53802. colorAttachment.loadOp = GPULoadOp.Load;
  53803. }
  53804. colorAttachment.storeOp = GPUStoreOp.Store;
  53805. }
  53806. } else {
  53807. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53808. if ( renderContext.clearColor ) {
  53809. colorAttachment.clearValue = renderContext.clearColorValue;
  53810. colorAttachment.loadOp = GPULoadOp.Clear;
  53811. } else {
  53812. colorAttachment.loadOp = GPULoadOp.Load;
  53813. }
  53814. colorAttachment.storeOp = GPUStoreOp.Store;
  53815. }
  53816. //
  53817. if ( renderContext.depth ) {
  53818. if ( renderContext.clearDepth ) {
  53819. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  53820. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  53821. } else {
  53822. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53823. }
  53824. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53825. }
  53826. if ( renderContext.stencil ) {
  53827. if ( renderContext.clearStencil ) {
  53828. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  53829. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  53830. } else {
  53831. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53832. }
  53833. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53834. }
  53835. //
  53836. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  53837. // shadow arrays - prepare bundle encoders for each camera in an array camera
  53838. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53839. const cameras = renderContext.camera.cameras;
  53840. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  53841. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  53842. } else {
  53843. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  53844. }
  53845. // Create bundle encoders for each layer
  53846. renderContextData.bundleEncoders = [];
  53847. renderContextData.bundleSets = [];
  53848. // Create separate bundle encoders for each camera in the array
  53849. for ( let i = 0; i < cameras.length; i ++ ) {
  53850. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  53851. renderContext,
  53852. 'renderBundleArrayCamera_' + i
  53853. );
  53854. // Initialize state tracking for this bundle
  53855. const bundleSets = {
  53856. attributes: {},
  53857. bindingGroups: [],
  53858. pipeline: null,
  53859. index: null
  53860. };
  53861. renderContextData.bundleEncoders.push( bundleEncoder );
  53862. renderContextData.bundleSets.push( bundleSets );
  53863. }
  53864. // We'll complete the bundles in finishRender
  53865. renderContextData.currentPass = null;
  53866. } else {
  53867. const currentPass = encoder.beginRenderPass( descriptor );
  53868. renderContextData.currentPass = currentPass;
  53869. if ( renderContext.viewport ) {
  53870. this.updateViewport( renderContext );
  53871. }
  53872. if ( renderContext.scissor ) {
  53873. this.updateScissor( renderContext );
  53874. }
  53875. }
  53876. //
  53877. renderContextData.descriptor = descriptor;
  53878. renderContextData.encoder = encoder;
  53879. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53880. renderContextData.renderBundles = [];
  53881. }
  53882. /**
  53883. * This method creates layer descriptors for each camera in an array camera
  53884. * to prepare for rendering to a depth array texture.
  53885. *
  53886. * @param {RenderContext} renderContext - The render context.
  53887. * @param {Object} renderContextData - The render context data.
  53888. * @param {Object} descriptor - The render pass descriptor.
  53889. * @param {ArrayCamera} cameras - The array camera.
  53890. *
  53891. * @private
  53892. */
  53893. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  53894. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53895. renderContextData.layerDescriptors = [];
  53896. const depthTextureData = this.get( renderContext.depthTexture );
  53897. if ( ! depthTextureData.viewCache ) {
  53898. depthTextureData.viewCache = [];
  53899. }
  53900. for ( let i = 0; i < cameras.length; i ++ ) {
  53901. const layerDescriptor = {
  53902. ...descriptor,
  53903. colorAttachments: [ {
  53904. ...descriptor.colorAttachments[ 0 ],
  53905. view: descriptor.colorAttachments[ i ].view
  53906. } ]
  53907. };
  53908. if ( descriptor.depthStencilAttachment ) {
  53909. const layerIndex = i;
  53910. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  53911. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  53912. dimension: GPUTextureViewDimension.TwoD,
  53913. baseArrayLayer: i,
  53914. arrayLayerCount: 1
  53915. } );
  53916. }
  53917. layerDescriptor.depthStencilAttachment = {
  53918. view: depthTextureData.viewCache[ layerIndex ],
  53919. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  53920. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  53921. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  53922. };
  53923. if ( renderContext.stencil ) {
  53924. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  53925. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  53926. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  53927. }
  53928. } else {
  53929. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  53930. }
  53931. renderContextData.layerDescriptors.push( layerDescriptor );
  53932. }
  53933. }
  53934. /**
  53935. * This method updates the layer descriptors for each camera in an array camera
  53936. * to prepare for rendering to a depth array texture.
  53937. *
  53938. * @param {RenderContext} renderContext - The render context.
  53939. * @param {Object} renderContextData - The render context data.
  53940. * @param {ArrayCamera} cameras - The array camera.
  53941. *
  53942. */
  53943. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  53944. for ( let i = 0; i < cameras.length; i ++ ) {
  53945. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53946. if ( layerDescriptor.depthStencilAttachment ) {
  53947. const depthAttachment = layerDescriptor.depthStencilAttachment;
  53948. if ( renderContext.depth ) {
  53949. if ( renderContext.clearDepth ) {
  53950. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  53951. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  53952. } else {
  53953. depthAttachment.depthLoadOp = GPULoadOp.Load;
  53954. }
  53955. }
  53956. if ( renderContext.stencil ) {
  53957. if ( renderContext.clearStencil ) {
  53958. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  53959. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  53960. } else {
  53961. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  53962. }
  53963. }
  53964. }
  53965. }
  53966. }
  53967. /**
  53968. * This method is executed at the end of a render call and finalizes work
  53969. * after draw calls.
  53970. *
  53971. * @param {RenderContext} renderContext - The render context.
  53972. */
  53973. finishRender( renderContext ) {
  53974. const renderContextData = this.get( renderContext );
  53975. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53976. if ( renderContextData.renderBundles.length > 0 ) {
  53977. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  53978. }
  53979. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  53980. renderContextData.currentPass.endOcclusionQuery();
  53981. }
  53982. // shadow arrays - Execute bundles for each layer
  53983. const encoder = renderContextData.encoder;
  53984. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53985. const bundles = [];
  53986. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  53987. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  53988. bundles.push( bundleEncoder.finish() );
  53989. }
  53990. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  53991. if ( i < bundles.length ) {
  53992. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53993. const renderPass = encoder.beginRenderPass( layerDescriptor );
  53994. if ( renderContext.viewport ) {
  53995. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  53996. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  53997. }
  53998. if ( renderContext.scissor ) {
  53999. const { x, y, width, height } = renderContext.scissorValue;
  54000. renderPass.setScissorRect( x, y, width, height );
  54001. }
  54002. renderPass.executeBundles( [ bundles[ i ] ] );
  54003. renderPass.end();
  54004. }
  54005. }
  54006. } else if ( renderContextData.currentPass ) {
  54007. renderContextData.currentPass.end();
  54008. }
  54009. if ( occlusionQueryCount > 0 ) {
  54010. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  54011. //
  54012. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  54013. if ( queryResolveBuffer === undefined ) {
  54014. queryResolveBuffer = this.device.createBuffer(
  54015. {
  54016. size: bufferSize,
  54017. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  54018. }
  54019. );
  54020. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  54021. }
  54022. //
  54023. const readBuffer = this.device.createBuffer(
  54024. {
  54025. size: bufferSize,
  54026. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54027. }
  54028. );
  54029. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  54030. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  54031. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  54032. renderContextData.occlusionQueryBuffer = readBuffer;
  54033. //
  54034. this.resolveOccludedAsync( renderContext );
  54035. }
  54036. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  54037. //
  54038. if ( renderContext.textures !== null ) {
  54039. const textures = renderContext.textures;
  54040. for ( let i = 0; i < textures.length; i ++ ) {
  54041. const texture = textures[ i ];
  54042. if ( texture.generateMipmaps === true ) {
  54043. this.textureUtils.generateMipmaps( texture );
  54044. }
  54045. }
  54046. }
  54047. }
  54048. /**
  54049. * Returns `true` if the given 3D object is fully occluded by other
  54050. * 3D objects in the scene.
  54051. *
  54052. * @param {RenderContext} renderContext - The render context.
  54053. * @param {Object3D} object - The 3D object to test.
  54054. * @return {boolean} Whether the 3D object is fully occluded or not.
  54055. */
  54056. isOccluded( renderContext, object ) {
  54057. const renderContextData = this.get( renderContext );
  54058. return renderContextData.occluded && renderContextData.occluded.has( object );
  54059. }
  54060. /**
  54061. * This method processes the result of occlusion queries and writes it
  54062. * into render context data.
  54063. *
  54064. * @async
  54065. * @param {RenderContext} renderContext - The render context.
  54066. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  54067. */
  54068. async resolveOccludedAsync( renderContext ) {
  54069. const renderContextData = this.get( renderContext );
  54070. // handle occlusion query results
  54071. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  54072. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  54073. const occluded = new WeakSet();
  54074. renderContextData.currentOcclusionQueryObjects = null;
  54075. renderContextData.currentOcclusionQueryBuffer = null;
  54076. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  54077. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  54078. const results = new BigUint64Array( buffer );
  54079. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  54080. if ( results[ i ] === BigInt( 0 ) ) {
  54081. occluded.add( currentOcclusionQueryObjects[ i ] );
  54082. }
  54083. }
  54084. currentOcclusionQueryBuffer.destroy();
  54085. renderContextData.occluded = occluded;
  54086. }
  54087. }
  54088. /**
  54089. * Updates the viewport with the values from the given render context.
  54090. *
  54091. * @param {RenderContext} renderContext - The render context.
  54092. */
  54093. updateViewport( renderContext ) {
  54094. const { currentPass } = this.get( renderContext );
  54095. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54096. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54097. }
  54098. /**
  54099. * Updates the scissor with the values from the given render context.
  54100. *
  54101. * @param {RenderContext} renderContext - The render context.
  54102. */
  54103. updateScissor( renderContext ) {
  54104. const { currentPass } = this.get( renderContext );
  54105. const { x, y, width, height } = renderContext.scissorValue;
  54106. currentPass.setScissorRect( x, y, width, height );
  54107. }
  54108. /**
  54109. * Returns the clear color and alpha into a single
  54110. * color object.
  54111. *
  54112. * @return {Color4} The clear color.
  54113. */
  54114. getClearColor() {
  54115. const clearColor = super.getClearColor();
  54116. // only premultiply alpha when alphaMode is "premultiplied"
  54117. if ( this.renderer.alpha === true ) {
  54118. clearColor.r *= clearColor.a;
  54119. clearColor.g *= clearColor.a;
  54120. clearColor.b *= clearColor.a;
  54121. }
  54122. return clearColor;
  54123. }
  54124. /**
  54125. * Performs a clear operation.
  54126. *
  54127. * @param {boolean} color - Whether the color buffer should be cleared or not.
  54128. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  54129. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  54130. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  54131. */
  54132. clear( color, depth, stencil, renderTargetContext = null ) {
  54133. const device = this.device;
  54134. const renderer = this.renderer;
  54135. let colorAttachments = [];
  54136. let depthStencilAttachment;
  54137. let clearValue;
  54138. let supportsDepth;
  54139. let supportsStencil;
  54140. if ( color ) {
  54141. const clearColor = this.getClearColor();
  54142. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  54143. }
  54144. if ( renderTargetContext === null ) {
  54145. supportsDepth = renderer.depth;
  54146. supportsStencil = renderer.stencil;
  54147. const descriptor = this._getDefaultRenderPassDescriptor();
  54148. if ( color ) {
  54149. colorAttachments = descriptor.colorAttachments;
  54150. const colorAttachment = colorAttachments[ 0 ];
  54151. colorAttachment.clearValue = clearValue;
  54152. colorAttachment.loadOp = GPULoadOp.Clear;
  54153. colorAttachment.storeOp = GPUStoreOp.Store;
  54154. }
  54155. if ( supportsDepth || supportsStencil ) {
  54156. depthStencilAttachment = descriptor.depthStencilAttachment;
  54157. }
  54158. } else {
  54159. supportsDepth = renderTargetContext.depth;
  54160. supportsStencil = renderTargetContext.stencil;
  54161. const clearConfig = {
  54162. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  54163. clearValue: color ? clearValue : undefined
  54164. };
  54165. if ( supportsDepth ) {
  54166. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  54167. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  54168. clearConfig.depthStoreOp = GPUStoreOp.Store;
  54169. }
  54170. if ( supportsStencil ) {
  54171. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  54172. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  54173. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  54174. }
  54175. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  54176. colorAttachments = descriptor.colorAttachments;
  54177. depthStencilAttachment = descriptor.depthStencilAttachment;
  54178. }
  54179. if ( supportsDepth && depthStencilAttachment ) {
  54180. if ( depth ) {
  54181. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54182. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  54183. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54184. } else {
  54185. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54186. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54187. }
  54188. }
  54189. //
  54190. if ( supportsStencil && depthStencilAttachment ) {
  54191. if ( stencil ) {
  54192. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54193. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  54194. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54195. } else {
  54196. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54197. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54198. }
  54199. }
  54200. //
  54201. const encoder = device.createCommandEncoder( { label: 'clear' } );
  54202. const currentPass = encoder.beginRenderPass( {
  54203. colorAttachments,
  54204. depthStencilAttachment
  54205. } );
  54206. currentPass.end();
  54207. device.queue.submit( [ encoder.finish() ] );
  54208. }
  54209. // compute
  54210. /**
  54211. * This method is executed at the beginning of a compute call and
  54212. * prepares the state for upcoming compute tasks.
  54213. *
  54214. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54215. */
  54216. beginCompute( computeGroup ) {
  54217. const groupGPU = this.get( computeGroup );
  54218. //
  54219. const descriptor = {
  54220. label: 'computeGroup_' + computeGroup.id
  54221. };
  54222. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  54223. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  54224. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  54225. }
  54226. /**
  54227. * Executes a compute command for the given compute node.
  54228. *
  54229. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  54230. * @param {Node} computeNode - The compute node.
  54231. * @param {Array<BindGroup>} bindings - The bindings.
  54232. * @param {ComputePipeline} pipeline - The compute pipeline.
  54233. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  54234. */
  54235. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  54236. const computeNodeData = this.get( computeNode );
  54237. const { passEncoderGPU } = this.get( computeGroup );
  54238. // pipeline
  54239. const pipelineGPU = this.get( pipeline ).pipeline;
  54240. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54241. // bind groups
  54242. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54243. const bindGroup = bindings[ i ];
  54244. const bindingsData = this.get( bindGroup );
  54245. passEncoderGPU.setBindGroup( i, bindingsData.group );
  54246. }
  54247. let dispatchSize;
  54248. if ( dispatchSizeOrCount === null ) {
  54249. dispatchSizeOrCount = computeNode.count;
  54250. }
  54251. if ( typeof dispatchSizeOrCount === 'number' ) {
  54252. // If a single number is given, we calculate the dispatch size based on the workgroup size
  54253. const count = dispatchSizeOrCount;
  54254. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  54255. // cache dispatch size to avoid recalculating it every time
  54256. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  54257. computeNodeData.count = count;
  54258. const workgroupSize = computeNode.workgroupSize;
  54259. let size = workgroupSize[ 0 ];
  54260. for ( let i = 1; i < workgroupSize.length; i ++ )
  54261. size *= workgroupSize[ i ];
  54262. const dispatchCount = Math.ceil( count / size );
  54263. //
  54264. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  54265. dispatchSize = [ dispatchCount, 1, 1 ];
  54266. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  54267. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  54268. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  54269. }
  54270. computeNodeData.dispatchSize = dispatchSize;
  54271. }
  54272. dispatchSize = computeNodeData.dispatchSize;
  54273. } else {
  54274. dispatchSize = dispatchSizeOrCount;
  54275. }
  54276. //
  54277. passEncoderGPU.dispatchWorkgroups(
  54278. dispatchSize[ 0 ],
  54279. dispatchSize[ 1 ] || 1,
  54280. dispatchSize[ 2 ] || 1
  54281. );
  54282. }
  54283. /**
  54284. * This method is executed at the end of a compute call and
  54285. * finalizes work after compute tasks.
  54286. *
  54287. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54288. */
  54289. finishCompute( computeGroup ) {
  54290. const groupData = this.get( computeGroup );
  54291. groupData.passEncoderGPU.end();
  54292. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  54293. }
  54294. // render object
  54295. /**
  54296. * Executes a draw command for the given render object.
  54297. *
  54298. * @param {RenderObject} renderObject - The render object to draw.
  54299. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  54300. */
  54301. draw( renderObject, info ) {
  54302. const { object, material, context, pipeline } = renderObject;
  54303. const bindings = renderObject.getBindings();
  54304. const renderContextData = this.get( context );
  54305. const pipelineGPU = this.get( pipeline ).pipeline;
  54306. const index = renderObject.getIndex();
  54307. const hasIndex = ( index !== null );
  54308. const drawParams = renderObject.getDrawParameters();
  54309. if ( drawParams === null ) return;
  54310. // pipeline
  54311. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  54312. // pipeline
  54313. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54314. currentSets.pipeline = pipelineGPU;
  54315. // bind groups
  54316. const currentBindingGroups = currentSets.bindingGroups;
  54317. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54318. const bindGroup = bindings[ i ];
  54319. const bindingsData = this.get( bindGroup );
  54320. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  54321. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  54322. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  54323. }
  54324. }
  54325. // attributes
  54326. // index
  54327. if ( hasIndex === true ) {
  54328. if ( currentSets.index !== index ) {
  54329. const buffer = this.get( index ).buffer;
  54330. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54331. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  54332. currentSets.index = index;
  54333. }
  54334. }
  54335. // vertex buffers
  54336. const vertexBuffers = renderObject.getVertexBuffers();
  54337. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  54338. const vertexBuffer = vertexBuffers[ i ];
  54339. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  54340. const buffer = this.get( vertexBuffer ).buffer;
  54341. passEncoderGPU.setVertexBuffer( i, buffer );
  54342. currentSets.attributes[ i ] = vertexBuffer;
  54343. }
  54344. }
  54345. // stencil
  54346. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  54347. passEncoderGPU.setStencilReference( material.stencilRef );
  54348. renderContextData.currentStencilRef = material.stencilRef;
  54349. }
  54350. };
  54351. // Define draw function
  54352. const draw = ( passEncoderGPU, currentSets ) => {
  54353. setPipelineAndBindings( passEncoderGPU, currentSets );
  54354. if ( object.isBatchedMesh === true ) {
  54355. const starts = object._multiDrawStarts;
  54356. const counts = object._multiDrawCounts;
  54357. const drawCount = object._multiDrawCount;
  54358. const drawInstances = object._multiDrawInstances;
  54359. if ( drawInstances !== null ) {
  54360. // @deprecated, r174
  54361. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  54362. }
  54363. for ( let i = 0; i < drawCount; i ++ ) {
  54364. const count = drawInstances ? drawInstances[ i ] : 1;
  54365. const firstInstance = count > 1 ? 0 : i;
  54366. if ( hasIndex === true ) {
  54367. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  54368. } else {
  54369. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  54370. }
  54371. info.update( object, counts[ i ], count );
  54372. }
  54373. } else if ( hasIndex === true ) {
  54374. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  54375. const indirect = renderObject.getIndirect();
  54376. if ( indirect !== null ) {
  54377. const buffer = this.get( indirect ).buffer;
  54378. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  54379. } else {
  54380. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  54381. }
  54382. info.update( object, indexCount, instanceCount );
  54383. } else {
  54384. const { vertexCount, instanceCount, firstVertex } = drawParams;
  54385. const indirect = renderObject.getIndirect();
  54386. if ( indirect !== null ) {
  54387. const buffer = this.get( indirect ).buffer;
  54388. passEncoderGPU.drawIndirect( buffer, 0 );
  54389. } else {
  54390. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  54391. }
  54392. info.update( object, vertexCount, instanceCount );
  54393. }
  54394. };
  54395. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  54396. const cameraData = this.get( renderObject.camera );
  54397. const cameras = renderObject.camera.cameras;
  54398. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  54399. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  54400. const bindingsData = this.get( cameraIndex );
  54401. const indexesGPU = [];
  54402. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  54403. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54404. data[ 0 ] = i;
  54405. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  54406. indexesGPU.push( bindGroupIndex );
  54407. }
  54408. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  54409. }
  54410. const pixelRatio = this.renderer.getPixelRatio();
  54411. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54412. const subCamera = cameras[ i ];
  54413. if ( object.layers.test( subCamera.layers ) ) {
  54414. const vp = subCamera.viewport;
  54415. let pass = renderContextData.currentPass;
  54416. let sets = renderContextData.currentSets;
  54417. if ( renderContextData.bundleEncoders ) {
  54418. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54419. const bundleSets = renderContextData.bundleSets[ i ];
  54420. pass = bundleEncoder;
  54421. sets = bundleSets;
  54422. }
  54423. if ( vp ) {
  54424. pass.setViewport(
  54425. Math.floor( vp.x * pixelRatio ),
  54426. Math.floor( vp.y * pixelRatio ),
  54427. Math.floor( vp.width * pixelRatio ),
  54428. Math.floor( vp.height * pixelRatio ),
  54429. context.viewportValue.minDepth,
  54430. context.viewportValue.maxDepth
  54431. );
  54432. }
  54433. // Set camera index binding for this layer
  54434. if ( cameraIndex && cameraData.indexesGPU ) {
  54435. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  54436. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  54437. }
  54438. draw( pass, sets );
  54439. }
  54440. }
  54441. } else {
  54442. // Regular single camera rendering
  54443. if ( renderContextData.currentPass ) {
  54444. // Handle occlusion queries
  54445. if ( renderContextData.occlusionQuerySet !== undefined ) {
  54446. const lastObject = renderContextData.lastOcclusionObject;
  54447. if ( lastObject !== object ) {
  54448. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  54449. renderContextData.currentPass.endOcclusionQuery();
  54450. renderContextData.occlusionQueryIndex ++;
  54451. }
  54452. if ( object.occlusionTest === true ) {
  54453. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  54454. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  54455. }
  54456. renderContextData.lastOcclusionObject = object;
  54457. }
  54458. }
  54459. draw( renderContextData.currentPass, renderContextData.currentSets );
  54460. }
  54461. }
  54462. }
  54463. // cache key
  54464. /**
  54465. * Returns `true` if the render pipeline requires an update.
  54466. *
  54467. * @param {RenderObject} renderObject - The render object.
  54468. * @return {boolean} Whether the render pipeline requires an update or not.
  54469. */
  54470. needsRenderUpdate( renderObject ) {
  54471. const data = this.get( renderObject );
  54472. const { object, material } = renderObject;
  54473. const utils = this.utils;
  54474. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  54475. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  54476. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54477. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54478. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  54479. let needsUpdate = false;
  54480. if ( data.material !== material || data.materialVersion !== material.version ||
  54481. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  54482. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  54483. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  54484. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  54485. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  54486. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  54487. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  54488. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  54489. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  54490. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  54491. data.primitiveTopology !== primitiveTopology ||
  54492. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  54493. ) {
  54494. data.material = material; data.materialVersion = material.version;
  54495. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  54496. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  54497. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  54498. data.colorWrite = material.colorWrite;
  54499. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  54500. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  54501. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  54502. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  54503. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  54504. data.sampleCount = sampleCount;
  54505. data.colorSpace = colorSpace;
  54506. data.colorFormat = colorFormat;
  54507. data.depthStencilFormat = depthStencilFormat;
  54508. data.primitiveTopology = primitiveTopology;
  54509. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  54510. needsUpdate = true;
  54511. }
  54512. return needsUpdate;
  54513. }
  54514. /**
  54515. * Returns a cache key that is used to identify render pipelines.
  54516. *
  54517. * @param {RenderObject} renderObject - The render object.
  54518. * @return {string} The cache key.
  54519. */
  54520. getRenderCacheKey( renderObject ) {
  54521. const { object, material } = renderObject;
  54522. const utils = this.utils;
  54523. const renderContext = renderObject.context;
  54524. // meshes with negative scale have a different frontFace render pipeline
  54525. // descriptor value so the following must be honored in the cache key
  54526. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  54527. return [
  54528. material.transparent, material.blending, material.premultipliedAlpha,
  54529. material.blendSrc, material.blendDst, material.blendEquation,
  54530. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  54531. material.colorWrite,
  54532. material.depthWrite, material.depthTest, material.depthFunc,
  54533. material.stencilWrite, material.stencilFunc,
  54534. material.stencilFail, material.stencilZFail, material.stencilZPass,
  54535. material.stencilFuncMask, material.stencilWriteMask,
  54536. material.side,
  54537. frontFaceCW,
  54538. utils.getSampleCountRenderContext( renderContext ),
  54539. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  54540. utils.getPrimitiveTopology( object, material ),
  54541. renderObject.getGeometryCacheKey(),
  54542. renderObject.clippingContextCacheKey
  54543. ].join();
  54544. }
  54545. // textures
  54546. /**
  54547. * Updates a GPU sampler for the given texture.
  54548. *
  54549. * @param {Texture} texture - The texture to update the sampler for.
  54550. * @return {string} The current sampler key.
  54551. */
  54552. updateSampler( texture ) {
  54553. return this.textureUtils.updateSampler( texture );
  54554. }
  54555. /**
  54556. * Creates a default texture for the given texture that can be used
  54557. * as a placeholder until the actual texture is ready for usage.
  54558. *
  54559. * @param {Texture} texture - The texture to create a default texture for.
  54560. * @return {boolean} Whether the sampler has been updated or not.
  54561. */
  54562. createDefaultTexture( texture ) {
  54563. return this.textureUtils.createDefaultTexture( texture );
  54564. }
  54565. /**
  54566. * Defines a texture on the GPU for the given texture object.
  54567. *
  54568. * @param {Texture} texture - The texture.
  54569. * @param {Object} [options={}] - Optional configuration parameter.
  54570. */
  54571. createTexture( texture, options ) {
  54572. this.textureUtils.createTexture( texture, options );
  54573. }
  54574. /**
  54575. * Uploads the updated texture data to the GPU.
  54576. *
  54577. * @param {Texture} texture - The texture.
  54578. * @param {Object} [options={}] - Optional configuration parameter.
  54579. */
  54580. updateTexture( texture, options ) {
  54581. this.textureUtils.updateTexture( texture, options );
  54582. }
  54583. /**
  54584. * Generates mipmaps for the given texture.
  54585. *
  54586. * @param {Texture} texture - The texture.
  54587. */
  54588. generateMipmaps( texture ) {
  54589. this.textureUtils.generateMipmaps( texture );
  54590. }
  54591. /**
  54592. * Destroys the GPU data for the given texture object.
  54593. *
  54594. * @param {Texture} texture - The texture.
  54595. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54596. */
  54597. destroyTexture( texture, isDefaultTexture = false ) {
  54598. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  54599. }
  54600. /**
  54601. * Returns texture data as a typed array.
  54602. *
  54603. * @async
  54604. * @param {Texture} texture - The texture to copy.
  54605. * @param {number} x - The x coordinate of the copy origin.
  54606. * @param {number} y - The y coordinate of the copy origin.
  54607. * @param {number} width - The width of the copy.
  54608. * @param {number} height - The height of the copy.
  54609. * @param {number} faceIndex - The face index.
  54610. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54611. */
  54612. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  54613. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  54614. }
  54615. /**
  54616. * Inits a time stamp query for the given render context.
  54617. *
  54618. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  54619. * @param {number} uid - Unique id for the context (e.g. render context id).
  54620. * @param {Object} descriptor - The query descriptor.
  54621. */
  54622. initTimestampQuery( type, uid, descriptor ) {
  54623. if ( ! this.trackTimestamp ) return;
  54624. if ( ! this.timestampQueryPool[ type ] ) {
  54625. // TODO: Variable maxQueries?
  54626. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  54627. }
  54628. const timestampQueryPool = this.timestampQueryPool[ type ];
  54629. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  54630. descriptor.timestampWrites = {
  54631. querySet: timestampQueryPool.querySet,
  54632. beginningOfPassWriteIndex: baseOffset,
  54633. endOfPassWriteIndex: baseOffset + 1,
  54634. };
  54635. }
  54636. // node builder
  54637. /**
  54638. * Returns a node builder for the given render object.
  54639. *
  54640. * @param {RenderObject} object - The render object.
  54641. * @param {Renderer} renderer - The renderer.
  54642. * @return {WGSLNodeBuilder} The node builder.
  54643. */
  54644. createNodeBuilder( object, renderer ) {
  54645. return new WGSLNodeBuilder( object, renderer );
  54646. }
  54647. // program
  54648. /**
  54649. * Creates a shader program from the given programmable stage.
  54650. *
  54651. * @param {ProgrammableStage} program - The programmable stage.
  54652. */
  54653. createProgram( program ) {
  54654. const programGPU = this.get( program );
  54655. programGPU.module = {
  54656. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  54657. entryPoint: 'main'
  54658. };
  54659. }
  54660. /**
  54661. * Destroys the shader program of the given programmable stage.
  54662. *
  54663. * @param {ProgrammableStage} program - The programmable stage.
  54664. */
  54665. destroyProgram( program ) {
  54666. this.delete( program );
  54667. }
  54668. // pipelines
  54669. /**
  54670. * Creates a render pipeline for the given render object.
  54671. *
  54672. * @param {RenderObject} renderObject - The render object.
  54673. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54674. */
  54675. createRenderPipeline( renderObject, promises ) {
  54676. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  54677. }
  54678. /**
  54679. * Creates a compute pipeline for the given compute node.
  54680. *
  54681. * @param {ComputePipeline} computePipeline - The compute pipeline.
  54682. * @param {Array<BindGroup>} bindings - The bindings.
  54683. */
  54684. createComputePipeline( computePipeline, bindings ) {
  54685. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  54686. }
  54687. /**
  54688. * Prepares the state for encoding render bundles.
  54689. *
  54690. * @param {RenderContext} renderContext - The render context.
  54691. */
  54692. beginBundle( renderContext ) {
  54693. const renderContextData = this.get( renderContext );
  54694. renderContextData._currentPass = renderContextData.currentPass;
  54695. renderContextData._currentSets = renderContextData.currentSets;
  54696. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54697. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  54698. }
  54699. /**
  54700. * After processing render bundles this method finalizes related work.
  54701. *
  54702. * @param {RenderContext} renderContext - The render context.
  54703. * @param {RenderBundle} bundle - The render bundle.
  54704. */
  54705. finishBundle( renderContext, bundle ) {
  54706. const renderContextData = this.get( renderContext );
  54707. const bundleEncoder = renderContextData.currentPass;
  54708. const bundleGPU = bundleEncoder.finish();
  54709. this.get( bundle ).bundleGPU = bundleGPU;
  54710. // restore render pass state
  54711. renderContextData.currentSets = renderContextData._currentSets;
  54712. renderContextData.currentPass = renderContextData._currentPass;
  54713. }
  54714. /**
  54715. * Adds a render bundle to the render context data.
  54716. *
  54717. * @param {RenderContext} renderContext - The render context.
  54718. * @param {RenderBundle} bundle - The render bundle to add.
  54719. */
  54720. addBundle( renderContext, bundle ) {
  54721. const renderContextData = this.get( renderContext );
  54722. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  54723. }
  54724. // bindings
  54725. /**
  54726. * Creates bindings from the given bind group definition.
  54727. *
  54728. * @param {BindGroup} bindGroup - The bind group.
  54729. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54730. * @param {number} cacheIndex - The cache index.
  54731. * @param {number} version - The version.
  54732. */
  54733. createBindings( bindGroup, bindings, cacheIndex, version ) {
  54734. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54735. }
  54736. /**
  54737. * Updates the given bind group definition.
  54738. *
  54739. * @param {BindGroup} bindGroup - The bind group.
  54740. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54741. * @param {number} cacheIndex - The cache index.
  54742. * @param {number} version - The version.
  54743. */
  54744. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  54745. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54746. }
  54747. /**
  54748. * Updates a buffer binding.
  54749. *
  54750. * @param {Buffer} binding - The buffer binding to update.
  54751. */
  54752. updateBinding( binding ) {
  54753. this.bindingUtils.updateBinding( binding );
  54754. }
  54755. // attributes
  54756. /**
  54757. * Creates the buffer of an indexed shader attribute.
  54758. *
  54759. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  54760. */
  54761. createIndexAttribute( attribute ) {
  54762. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  54763. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  54764. usage |= GPUBufferUsage.STORAGE;
  54765. }
  54766. this.attributeUtils.createAttribute( attribute, usage );
  54767. }
  54768. /**
  54769. * Creates the GPU buffer of a shader attribute.
  54770. *
  54771. * @param {BufferAttribute} attribute - The buffer attribute.
  54772. */
  54773. createAttribute( attribute ) {
  54774. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54775. }
  54776. /**
  54777. * Creates the GPU buffer of a storage attribute.
  54778. *
  54779. * @param {BufferAttribute} attribute - The buffer attribute.
  54780. */
  54781. createStorageAttribute( attribute ) {
  54782. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54783. }
  54784. /**
  54785. * Creates the GPU buffer of an indirect storage attribute.
  54786. *
  54787. * @param {BufferAttribute} attribute - The buffer attribute.
  54788. */
  54789. createIndirectStorageAttribute( attribute ) {
  54790. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54791. }
  54792. /**
  54793. * Updates the GPU buffer of a shader attribute.
  54794. *
  54795. * @param {BufferAttribute} attribute - The buffer attribute to update.
  54796. */
  54797. updateAttribute( attribute ) {
  54798. this.attributeUtils.updateAttribute( attribute );
  54799. }
  54800. /**
  54801. * Destroys the GPU buffer of a shader attribute.
  54802. *
  54803. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  54804. */
  54805. destroyAttribute( attribute ) {
  54806. this.attributeUtils.destroyAttribute( attribute );
  54807. }
  54808. // canvas
  54809. /**
  54810. * Triggers an update of the default render pass descriptor.
  54811. */
  54812. updateSize() {
  54813. this.delete( this.renderer.getCanvasTarget() );
  54814. }
  54815. // utils public
  54816. /**
  54817. * Returns the maximum anisotropy texture filtering value.
  54818. *
  54819. * @return {number} The maximum anisotropy texture filtering value.
  54820. */
  54821. getMaxAnisotropy() {
  54822. return 16;
  54823. }
  54824. /**
  54825. * Checks if the given feature is supported by the backend.
  54826. *
  54827. * @param {string} name - The feature's name.
  54828. * @return {boolean} Whether the feature is supported or not.
  54829. */
  54830. hasFeature( name ) {
  54831. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  54832. return this.device.features.has( name );
  54833. }
  54834. /**
  54835. * Copies data of the given source texture to the given destination texture.
  54836. *
  54837. * @param {Texture} srcTexture - The source texture.
  54838. * @param {Texture} dstTexture - The destination texture.
  54839. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  54840. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  54841. * @param {number} [srcLevel=0] - The mipmap level to copy.
  54842. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  54843. */
  54844. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54845. let dstX = 0;
  54846. let dstY = 0;
  54847. let dstZ = 0;
  54848. let srcX = 0;
  54849. let srcY = 0;
  54850. let srcZ = 0;
  54851. let srcWidth = srcTexture.image.width;
  54852. let srcHeight = srcTexture.image.height;
  54853. let srcDepth = 1;
  54854. if ( srcRegion !== null ) {
  54855. if ( srcRegion.isBox3 === true ) {
  54856. srcX = srcRegion.min.x;
  54857. srcY = srcRegion.min.y;
  54858. srcZ = srcRegion.min.z;
  54859. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54860. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54861. srcDepth = srcRegion.max.z - srcRegion.min.z;
  54862. } else {
  54863. // Assume it's a Box2
  54864. srcX = srcRegion.min.x;
  54865. srcY = srcRegion.min.y;
  54866. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54867. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54868. srcDepth = 1;
  54869. }
  54870. }
  54871. if ( dstPosition !== null ) {
  54872. dstX = dstPosition.x;
  54873. dstY = dstPosition.y;
  54874. dstZ = dstPosition.z || 0;
  54875. }
  54876. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  54877. const sourceGPU = this.get( srcTexture ).texture;
  54878. const destinationGPU = this.get( dstTexture ).texture;
  54879. encoder.copyTextureToTexture(
  54880. {
  54881. texture: sourceGPU,
  54882. mipLevel: srcLevel,
  54883. origin: { x: srcX, y: srcY, z: srcZ }
  54884. },
  54885. {
  54886. texture: destinationGPU,
  54887. mipLevel: dstLevel,
  54888. origin: { x: dstX, y: dstY, z: dstZ }
  54889. },
  54890. [
  54891. srcWidth,
  54892. srcHeight,
  54893. srcDepth
  54894. ]
  54895. );
  54896. this.device.queue.submit( [ encoder.finish() ] );
  54897. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54898. this.textureUtils.generateMipmaps( dstTexture );
  54899. }
  54900. }
  54901. /**
  54902. * Copies the current bound framebuffer to the given texture.
  54903. *
  54904. * @param {Texture} texture - The destination texture.
  54905. * @param {RenderContext} renderContext - The render context.
  54906. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  54907. */
  54908. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  54909. const renderContextData = this.get( renderContext );
  54910. let sourceGPU = null;
  54911. if ( renderContext.renderTarget ) {
  54912. if ( texture.isDepthTexture ) {
  54913. sourceGPU = this.get( renderContext.depthTexture ).texture;
  54914. } else {
  54915. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  54916. }
  54917. } else {
  54918. if ( texture.isDepthTexture ) {
  54919. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  54920. } else {
  54921. sourceGPU = this.context.getCurrentTexture();
  54922. }
  54923. }
  54924. const destinationGPU = this.get( texture ).texture;
  54925. if ( sourceGPU.format !== destinationGPU.format ) {
  54926. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  54927. return;
  54928. }
  54929. let encoder;
  54930. if ( renderContextData.currentPass ) {
  54931. renderContextData.currentPass.end();
  54932. encoder = renderContextData.encoder;
  54933. } else {
  54934. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  54935. }
  54936. encoder.copyTextureToTexture(
  54937. {
  54938. texture: sourceGPU,
  54939. origin: [ rectangle.x, rectangle.y, 0 ],
  54940. },
  54941. {
  54942. texture: destinationGPU
  54943. },
  54944. [
  54945. rectangle.z,
  54946. rectangle.w
  54947. ]
  54948. );
  54949. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  54950. // might be out-of-sync, see #31768
  54951. if ( texture.generateMipmaps ) {
  54952. this.textureUtils.generateMipmaps( texture, encoder );
  54953. }
  54954. if ( renderContextData.currentPass ) {
  54955. const { descriptor } = renderContextData;
  54956. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  54957. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  54958. }
  54959. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54960. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54961. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  54962. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54963. if ( renderContext.viewport ) {
  54964. this.updateViewport( renderContext );
  54965. }
  54966. if ( renderContext.scissor ) {
  54967. this.updateScissor( renderContext );
  54968. }
  54969. } else {
  54970. this.device.queue.submit( [ encoder.finish() ] );
  54971. }
  54972. }
  54973. dispose() {
  54974. this.textureUtils.dispose();
  54975. }
  54976. }
  54977. /**
  54978. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54979. *
  54980. * @augments SpotLight
  54981. */
  54982. class IESSpotLight extends SpotLight {
  54983. /**
  54984. * Constructs a new IES spot light.
  54985. *
  54986. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54987. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54988. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54989. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54990. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54991. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54992. */
  54993. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54994. super( color, intensity, distance, angle, penumbra, decay );
  54995. /**
  54996. * TODO
  54997. *
  54998. * @type {?Texture}
  54999. * @default null
  55000. */
  55001. this.iesMap = null;
  55002. }
  55003. copy( source, recursive ) {
  55004. super.copy( source, recursive );
  55005. this.iesMap = source.iesMap;
  55006. return this;
  55007. }
  55008. }
  55009. /**
  55010. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  55011. *
  55012. * @augments SpotLight
  55013. */
  55014. class ProjectorLight extends SpotLight {
  55015. /**
  55016. * Constructs a new projector light.
  55017. *
  55018. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  55019. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  55020. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  55021. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  55022. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  55023. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  55024. */
  55025. constructor( color, intensity, distance, angle, penumbra, decay ) {
  55026. super( color, intensity, distance, angle, penumbra, decay );
  55027. /**
  55028. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  55029. *
  55030. * @type {?number}
  55031. * @default null
  55032. */
  55033. this.aspect = null;
  55034. }
  55035. copy( source, recursive ) {
  55036. super.copy( source, recursive );
  55037. this.aspect = source.aspect;
  55038. return this;
  55039. }
  55040. }
  55041. /**
  55042. * This version of a node library represents a basic version
  55043. * just focusing on lights and tone mapping techniques.
  55044. *
  55045. * @private
  55046. * @augments NodeLibrary
  55047. */
  55048. class BasicNodeLibrary extends NodeLibrary {
  55049. /**
  55050. * Constructs a new basic node library.
  55051. */
  55052. constructor() {
  55053. super();
  55054. this.addLight( PointLightNode, PointLight );
  55055. this.addLight( DirectionalLightNode, DirectionalLight );
  55056. this.addLight( RectAreaLightNode, RectAreaLight );
  55057. this.addLight( SpotLightNode, SpotLight );
  55058. this.addLight( AmbientLightNode, AmbientLight );
  55059. this.addLight( HemisphereLightNode, HemisphereLight );
  55060. this.addLight( LightProbeNode, LightProbe );
  55061. this.addLight( IESSpotLightNode, IESSpotLight );
  55062. this.addLight( ProjectorLightNode, ProjectorLight );
  55063. this.addToneMapping( linearToneMapping, LinearToneMapping );
  55064. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  55065. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  55066. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  55067. this.addToneMapping( agxToneMapping, AgXToneMapping );
  55068. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  55069. }
  55070. }
  55071. /**
  55072. * This alternative version of {@link WebGPURenderer} only supports node materials.
  55073. * So classes like `MeshBasicMaterial` are not compatible.
  55074. *
  55075. * @private
  55076. * @augments Renderer
  55077. */
  55078. class WebGPURenderer extends Renderer {
  55079. /**
  55080. * Constructs a new WebGPU renderer.
  55081. *
  55082. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  55083. */
  55084. constructor( parameters = {} ) {
  55085. let BackendClass;
  55086. if ( parameters.forceWebGL ) {
  55087. BackendClass = WebGLBackend;
  55088. } else {
  55089. BackendClass = WebGPUBackend;
  55090. parameters.getFallback = () => {
  55091. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  55092. return new WebGLBackend( parameters );
  55093. };
  55094. }
  55095. const backend = new BackendClass( parameters );
  55096. super( backend, parameters );
  55097. /**
  55098. * The generic default value is overwritten with the
  55099. * standard node library for type mapping. Material
  55100. * mapping is not supported with this version.
  55101. *
  55102. * @type {BasicNodeLibrary}
  55103. */
  55104. this.library = new BasicNodeLibrary();
  55105. /**
  55106. * This flag can be used for type testing.
  55107. *
  55108. * @type {boolean}
  55109. * @readonly
  55110. * @default true
  55111. */
  55112. this.isWebGPURenderer = true;
  55113. }
  55114. }
  55115. /**
  55116. * A specialized group which enables applications access to the
  55117. * Render Bundle API of WebGPU. The group with all its descendant nodes
  55118. * are considered as one render bundle and processed as such by
  55119. * the renderer.
  55120. *
  55121. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  55122. * With a WebGL backend, the group can technically be rendered but without
  55123. * any performance improvements.
  55124. *
  55125. * @augments Group
  55126. */
  55127. class BundleGroup extends Group {
  55128. /**
  55129. * Constructs a new bundle group.
  55130. */
  55131. constructor() {
  55132. super();
  55133. /**
  55134. * This flag can be used for type testing.
  55135. *
  55136. * @type {boolean}
  55137. * @readonly
  55138. * @default true
  55139. */
  55140. this.isBundleGroup = true;
  55141. /**
  55142. * This property is only relevant for detecting types
  55143. * during serialization/deserialization. It should always
  55144. * match the class name.
  55145. *
  55146. * @type {string}
  55147. * @readonly
  55148. * @default 'BundleGroup'
  55149. */
  55150. this.type = 'BundleGroup';
  55151. /**
  55152. * Whether the bundle is static or not. When set to `true`, the structure
  55153. * is assumed to be static and does not change. E.g. no new objects are
  55154. * added to the group
  55155. *
  55156. * If a change is required, an update can still be forced by setting the
  55157. * `needsUpdate` flag to `true`.
  55158. *
  55159. * @type {boolean}
  55160. * @default true
  55161. */
  55162. this.static = true;
  55163. /**
  55164. * The bundle group's version.
  55165. *
  55166. * @type {number}
  55167. * @readonly
  55168. * @default 0
  55169. */
  55170. this.version = 0;
  55171. }
  55172. /**
  55173. * Set this property to `true` when the bundle group has changed.
  55174. *
  55175. * @type {boolean}
  55176. * @default false
  55177. * @param {boolean} value
  55178. */
  55179. set needsUpdate( value ) {
  55180. if ( value === true ) this.version ++;
  55181. }
  55182. }
  55183. /**
  55184. * This module is responsible to manage the post processing setups in apps.
  55185. * You usually create a single instance of this class and use it to define
  55186. * the output of your post processing effect chain.
  55187. * ```js
  55188. * const postProcessing = new PostProcessing( renderer );
  55189. *
  55190. * const scenePass = pass( scene, camera );
  55191. *
  55192. * postProcessing.outputNode = scenePass;
  55193. * ```
  55194. *
  55195. * Note: This module can only be used with `WebGPURenderer`.
  55196. */
  55197. class PostProcessing {
  55198. /**
  55199. * Constructs a new post processing management module.
  55200. *
  55201. * @param {Renderer} renderer - A reference to the renderer.
  55202. * @param {Node<vec4>} outputNode - An optional output node.
  55203. */
  55204. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  55205. /**
  55206. * A reference to the renderer.
  55207. *
  55208. * @type {Renderer}
  55209. */
  55210. this.renderer = renderer;
  55211. /**
  55212. * A node which defines the final output of the post
  55213. * processing. This is usually the last node in a chain
  55214. * of effect nodes.
  55215. *
  55216. * @type {Node<vec4>}
  55217. */
  55218. this.outputNode = outputNode;
  55219. /**
  55220. * Whether the default output tone mapping and color
  55221. * space transformation should be enabled or not.
  55222. *
  55223. * It is enabled by default by it must be disabled when
  55224. * effects must be executed after tone mapping and color
  55225. * space conversion. A typical example is FXAA which
  55226. * requires sRGB input.
  55227. *
  55228. * When set to `false`, the app must control the output
  55229. * transformation with `RenderOutputNode`.
  55230. *
  55231. * ```js
  55232. * const outputPass = renderOutput( scenePass );
  55233. * ```
  55234. *
  55235. * @type {boolean}
  55236. */
  55237. this.outputColorTransform = true;
  55238. /**
  55239. * Must be set to `true` when the output node changes.
  55240. *
  55241. * @type {Node<vec4>}
  55242. */
  55243. this.needsUpdate = true;
  55244. const material = new NodeMaterial();
  55245. material.name = 'PostProcessing';
  55246. /**
  55247. * The full screen quad that is used to render
  55248. * the effects.
  55249. *
  55250. * @private
  55251. * @type {QuadMesh}
  55252. */
  55253. this._quadMesh = new QuadMesh( material );
  55254. this._quadMesh.name = 'Post-Processing';
  55255. /**
  55256. * The context of the post processing stack.
  55257. *
  55258. * @private
  55259. * @type {?Object}
  55260. * @default null
  55261. */
  55262. this._context = null;
  55263. }
  55264. /**
  55265. * When `PostProcessing` is used to apply post processing effects,
  55266. * the application must use this version of `render()` inside
  55267. * its animation loop (not the one from the renderer).
  55268. */
  55269. render() {
  55270. const renderer = this.renderer;
  55271. this._update();
  55272. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55273. const toneMapping = renderer.toneMapping;
  55274. const outputColorSpace = renderer.outputColorSpace;
  55275. renderer.toneMapping = NoToneMapping;
  55276. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55277. //
  55278. const currentXR = renderer.xr.enabled;
  55279. renderer.xr.enabled = false;
  55280. this._quadMesh.render( renderer );
  55281. renderer.xr.enabled = currentXR;
  55282. //
  55283. renderer.toneMapping = toneMapping;
  55284. renderer.outputColorSpace = outputColorSpace;
  55285. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55286. }
  55287. /**
  55288. * Returns the current context of the post processing stack.
  55289. *
  55290. * @readonly
  55291. * @type {?Object}
  55292. */
  55293. get context() {
  55294. return this._context;
  55295. }
  55296. /**
  55297. * Frees internal resources.
  55298. */
  55299. dispose() {
  55300. this._quadMesh.material.dispose();
  55301. }
  55302. /**
  55303. * Updates the state of the module.
  55304. *
  55305. * @private
  55306. */
  55307. _update() {
  55308. if ( this.needsUpdate === true ) {
  55309. const renderer = this.renderer;
  55310. const toneMapping = renderer.toneMapping;
  55311. const outputColorSpace = renderer.outputColorSpace;
  55312. const context = {
  55313. postProcessing: this,
  55314. onBeforePostProcessing: null,
  55315. onAfterPostProcessing: null
  55316. };
  55317. let outputNode = this.outputNode;
  55318. if ( this.outputColorTransform === true ) {
  55319. outputNode = outputNode.context( context );
  55320. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  55321. } else {
  55322. context.toneMapping = toneMapping;
  55323. context.outputColorSpace = outputColorSpace;
  55324. outputNode = outputNode.context( context );
  55325. }
  55326. this._context = context;
  55327. this._quadMesh.material.fragmentNode = outputNode;
  55328. this._quadMesh.material.needsUpdate = true;
  55329. this.needsUpdate = false;
  55330. }
  55331. }
  55332. /**
  55333. * When `PostProcessing` is used to apply post processing effects,
  55334. * the application must use this version of `renderAsync()` inside
  55335. * its animation loop (not the one from the renderer).
  55336. *
  55337. * @async
  55338. * @deprecated
  55339. * @return {Promise} A Promise that resolves when the render has been finished.
  55340. */
  55341. async renderAsync() {
  55342. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  55343. await this.renderer.init();
  55344. this.render();
  55345. }
  55346. }
  55347. /**
  55348. * This special type of texture is intended for compute shaders.
  55349. * It can be used to compute the data of a texture with a compute shader.
  55350. *
  55351. * Note: This type of texture can only be used with `WebGPURenderer`
  55352. * and a WebGPU backend.
  55353. *
  55354. * @augments Texture
  55355. */
  55356. class StorageTexture extends Texture {
  55357. /**
  55358. * Constructs a new storage texture.
  55359. *
  55360. * @param {number} [width=1] - The storage texture's width.
  55361. * @param {number} [height=1] - The storage texture's height.
  55362. */
  55363. constructor( width = 1, height = 1 ) {
  55364. super();
  55365. /**
  55366. * The image object which just represents the texture's dimension.
  55367. *
  55368. * @type {{width: number, height: number}}
  55369. */
  55370. this.image = { width, height };
  55371. /**
  55372. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55373. *
  55374. * @type {number}
  55375. */
  55376. this.magFilter = LinearFilter;
  55377. /**
  55378. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55379. *
  55380. * @type {number}
  55381. */
  55382. this.minFilter = LinearFilter;
  55383. /**
  55384. * This flag can be used for type testing.
  55385. *
  55386. * @type {boolean}
  55387. * @readonly
  55388. * @default true
  55389. */
  55390. this.isStorageTexture = true;
  55391. /**
  55392. * When `true`, mipmaps will be auto-generated after compute writes.
  55393. * When `false`, mipmaps must be written manually via compute shaders.
  55394. *
  55395. * @type {boolean}
  55396. * @default true
  55397. */
  55398. this.mipmapsAutoUpdate = true;
  55399. }
  55400. /**
  55401. * Sets the size of the storage texture.
  55402. *
  55403. * @param {number} width - The new width of the storage texture.
  55404. * @param {number} height - The new height of the storage texture.
  55405. */
  55406. setSize( width, height ) {
  55407. if ( this.image.width !== width || this.image.height !== height ) {
  55408. this.image.width = width;
  55409. this.image.height = height;
  55410. this.dispose();
  55411. }
  55412. }
  55413. }
  55414. /**
  55415. * This special type of buffer attribute is intended for compute shaders.
  55416. * It can be used to encode draw parameters for indirect draw calls.
  55417. *
  55418. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  55419. * and a WebGPU backend.
  55420. *
  55421. * @augments StorageBufferAttribute
  55422. */
  55423. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  55424. /**
  55425. * Constructs a new storage buffer attribute.
  55426. *
  55427. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  55428. * The subsequent parameter is then obsolete.
  55429. * @param {number} itemSize - The item size.
  55430. */
  55431. constructor( count, itemSize ) {
  55432. super( count, itemSize, Uint32Array );
  55433. /**
  55434. * This flag can be used for type testing.
  55435. *
  55436. * @type {boolean}
  55437. * @readonly
  55438. * @default true
  55439. */
  55440. this.isIndirectStorageBufferAttribute = true;
  55441. }
  55442. }
  55443. /**
  55444. * A loader for loading node objects in the three.js JSON Object/Scene format.
  55445. *
  55446. * @augments Loader
  55447. */
  55448. class NodeLoader extends Loader {
  55449. /**
  55450. * Constructs a new node loader.
  55451. *
  55452. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55453. */
  55454. constructor( manager ) {
  55455. super( manager );
  55456. /**
  55457. * Represents a dictionary of textures.
  55458. *
  55459. * @type {Object<string,Texture>}
  55460. */
  55461. this.textures = {};
  55462. /**
  55463. * Represents a dictionary of node types.
  55464. *
  55465. * @type {Object<string,Node.constructor>}
  55466. */
  55467. this.nodes = {};
  55468. }
  55469. /**
  55470. * Loads the node definitions from the given URL.
  55471. *
  55472. * @param {string} url - The path/URL of the file to be loaded.
  55473. * @param {Function} onLoad - Will be called when load completes.
  55474. * @param {Function} onProgress - Will be called while load progresses.
  55475. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  55476. */
  55477. load( url, onLoad, onProgress, onError ) {
  55478. const loader = new FileLoader( this.manager );
  55479. loader.setPath( this.path );
  55480. loader.setRequestHeader( this.requestHeader );
  55481. loader.setWithCredentials( this.withCredentials );
  55482. loader.load( url, ( text ) => {
  55483. try {
  55484. onLoad( this.parse( JSON.parse( text ) ) );
  55485. } catch ( e ) {
  55486. if ( onError ) {
  55487. onError( e );
  55488. } else {
  55489. error( e );
  55490. }
  55491. this.manager.itemError( url );
  55492. }
  55493. }, onProgress, onError );
  55494. }
  55495. /**
  55496. * Parse the node dependencies for the loaded node.
  55497. *
  55498. * @param {Array<Object>} [json] - The JSON definition
  55499. * @return {Object<string,Node>} A dictionary with node dependencies.
  55500. */
  55501. parseNodes( json ) {
  55502. const nodes = {};
  55503. if ( json !== undefined ) {
  55504. for ( const nodeJSON of json ) {
  55505. const { uuid, type } = nodeJSON;
  55506. nodes[ uuid ] = this.createNodeFromType( type );
  55507. nodes[ uuid ].uuid = uuid;
  55508. }
  55509. const meta = { nodes, textures: this.textures };
  55510. for ( const nodeJSON of json ) {
  55511. nodeJSON.meta = meta;
  55512. const node = nodes[ nodeJSON.uuid ];
  55513. node.deserialize( nodeJSON );
  55514. delete nodeJSON.meta;
  55515. }
  55516. }
  55517. return nodes;
  55518. }
  55519. /**
  55520. * Parses the node from the given JSON.
  55521. *
  55522. * @param {Object} json - The JSON definition
  55523. * @param {string} json.type - The node type.
  55524. * @param {string} json.uuid - The node UUID.
  55525. * @param {Array<Object>} [json.nodes] - The node dependencies.
  55526. * @param {Object} [json.meta] - The meta data.
  55527. * @return {Node} The parsed node.
  55528. */
  55529. parse( json ) {
  55530. const node = this.createNodeFromType( json.type );
  55531. node.uuid = json.uuid;
  55532. const nodes = this.parseNodes( json.nodes );
  55533. const meta = { nodes, textures: this.textures };
  55534. json.meta = meta;
  55535. node.deserialize( json );
  55536. delete json.meta;
  55537. return node;
  55538. }
  55539. /**
  55540. * Defines the dictionary of textures.
  55541. *
  55542. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  55543. * @return {NodeLoader} A reference to this loader.
  55544. */
  55545. setTextures( value ) {
  55546. this.textures = value;
  55547. return this;
  55548. }
  55549. /**
  55550. * Defines the dictionary of node types.
  55551. *
  55552. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55553. * @return {NodeLoader} A reference to this loader.
  55554. */
  55555. setNodes( value ) {
  55556. this.nodes = value;
  55557. return this;
  55558. }
  55559. /**
  55560. * Creates a node object from the given type.
  55561. *
  55562. * @param {string} type - The node type.
  55563. * @return {Node} The created node instance.
  55564. */
  55565. createNodeFromType( type ) {
  55566. if ( this.nodes[ type ] === undefined ) {
  55567. error( 'NodeLoader: Node type not found:', type );
  55568. return float();
  55569. }
  55570. return nodeObject( new this.nodes[ type ]() );
  55571. }
  55572. }
  55573. /**
  55574. * A special type of material loader for loading node materials.
  55575. *
  55576. * @augments MaterialLoader
  55577. */
  55578. class NodeMaterialLoader extends MaterialLoader {
  55579. /**
  55580. * Constructs a new node material loader.
  55581. *
  55582. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55583. */
  55584. constructor( manager ) {
  55585. super( manager );
  55586. /**
  55587. * Represents a dictionary of node types.
  55588. *
  55589. * @type {Object<string,Node.constructor>}
  55590. */
  55591. this.nodes = {};
  55592. /**
  55593. * Represents a dictionary of node material types.
  55594. *
  55595. * @type {Object<string,NodeMaterial.constructor>}
  55596. */
  55597. this.nodeMaterials = {};
  55598. }
  55599. /**
  55600. * Parses the node material from the given JSON.
  55601. *
  55602. * @param {Object} json - The JSON definition
  55603. * @return {NodeMaterial}. The parsed material.
  55604. */
  55605. parse( json ) {
  55606. const material = super.parse( json );
  55607. const nodes = this.nodes;
  55608. const inputNodes = json.inputNodes;
  55609. for ( const property in inputNodes ) {
  55610. const uuid = inputNodes[ property ];
  55611. material[ property ] = nodes[ uuid ];
  55612. }
  55613. return material;
  55614. }
  55615. /**
  55616. * Defines the dictionary of node types.
  55617. *
  55618. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55619. * @return {NodeLoader} A reference to this loader.
  55620. */
  55621. setNodes( value ) {
  55622. this.nodes = value;
  55623. return this;
  55624. }
  55625. /**
  55626. * Defines the dictionary of node material types.
  55627. *
  55628. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55629. * @return {NodeLoader} A reference to this loader.
  55630. */
  55631. setNodeMaterials( value ) {
  55632. this.nodeMaterials = value;
  55633. return this;
  55634. }
  55635. /**
  55636. * Creates a node material from the given type.
  55637. *
  55638. * @param {string} type - The node material type.
  55639. * @return {Node} The created node material instance.
  55640. */
  55641. createMaterialFromType( type ) {
  55642. const materialClass = this.nodeMaterials[ type ];
  55643. if ( materialClass !== undefined ) {
  55644. return new materialClass();
  55645. }
  55646. return super.createMaterialFromType( type );
  55647. }
  55648. }
  55649. /**
  55650. * A special type of object loader for loading 3D objects using
  55651. * node materials.
  55652. *
  55653. * @augments ObjectLoader
  55654. */
  55655. class NodeObjectLoader extends ObjectLoader {
  55656. /**
  55657. * Constructs a new node object loader.
  55658. *
  55659. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55660. */
  55661. constructor( manager ) {
  55662. super( manager );
  55663. /**
  55664. * Represents a dictionary of node types.
  55665. *
  55666. * @type {Object<string,Node.constructor>}
  55667. */
  55668. this.nodes = {};
  55669. /**
  55670. * Represents a dictionary of node material types.
  55671. *
  55672. * @type {Object<string,NodeMaterial.constructor>}
  55673. */
  55674. this.nodeMaterials = {};
  55675. /**
  55676. * A reference to hold the `nodes` JSON property.
  55677. *
  55678. * @private
  55679. * @type {?Object[]}
  55680. */
  55681. this._nodesJSON = null;
  55682. }
  55683. /**
  55684. * Defines the dictionary of node types.
  55685. *
  55686. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55687. * @return {NodeObjectLoader} A reference to this loader.
  55688. */
  55689. setNodes( value ) {
  55690. this.nodes = value;
  55691. return this;
  55692. }
  55693. /**
  55694. * Defines the dictionary of node material types.
  55695. *
  55696. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55697. * @return {NodeObjectLoader} A reference to this loader.
  55698. */
  55699. setNodeMaterials( value ) {
  55700. this.nodeMaterials = value;
  55701. return this;
  55702. }
  55703. /**
  55704. * Parses the node objects from the given JSON.
  55705. *
  55706. * @param {Object} json - The JSON definition
  55707. * @param {Function} onLoad - The onLoad callback function.
  55708. * @return {Object3D}. The parsed 3D object.
  55709. */
  55710. parse( json, onLoad ) {
  55711. this._nodesJSON = json.nodes;
  55712. const data = super.parse( json, onLoad );
  55713. this._nodesJSON = null; // dispose
  55714. return data;
  55715. }
  55716. /**
  55717. * Parses the node objects from the given JSON and textures.
  55718. *
  55719. * @param {Object[]} json - The JSON definition
  55720. * @param {Object<string,Texture>} textures - The texture library.
  55721. * @return {Object<string,Node>}. The parsed nodes.
  55722. */
  55723. parseNodes( json, textures ) {
  55724. if ( json !== undefined ) {
  55725. const loader = new NodeLoader();
  55726. loader.setNodes( this.nodes );
  55727. loader.setTextures( textures );
  55728. return loader.parseNodes( json );
  55729. }
  55730. return {};
  55731. }
  55732. /**
  55733. * Parses the node objects from the given JSON and textures.
  55734. *
  55735. * @param {Object} json - The JSON definition
  55736. * @param {Object<string,Texture>} textures - The texture library.
  55737. * @return {Object<string,NodeMaterial>}. The parsed materials.
  55738. */
  55739. parseMaterials( json, textures ) {
  55740. const materials = {};
  55741. if ( json !== undefined ) {
  55742. const nodes = this.parseNodes( this._nodesJSON, textures );
  55743. const loader = new NodeMaterialLoader();
  55744. loader.setTextures( textures );
  55745. loader.setNodes( nodes );
  55746. loader.setNodeMaterials( this.nodeMaterials );
  55747. for ( let i = 0, l = json.length; i < l; i ++ ) {
  55748. const data = json[ i ];
  55749. materials[ data.uuid ] = loader.parse( data );
  55750. }
  55751. }
  55752. return materials;
  55753. }
  55754. }
  55755. /**
  55756. * In earlier three.js versions, clipping was defined globally
  55757. * on the renderer or on material level. This special version of
  55758. * `THREE.Group` allows to encode the clipping state into the scene
  55759. * graph. Meaning if you create an instance of this group, all
  55760. * descendant 3D objects will be affected by the respective clipping
  55761. * planes.
  55762. *
  55763. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  55764. *
  55765. * @augments Group
  55766. */
  55767. class ClippingGroup extends Group {
  55768. /**
  55769. * Constructs a new clipping group.
  55770. */
  55771. constructor() {
  55772. super();
  55773. /**
  55774. * This flag can be used for type testing.
  55775. *
  55776. * @type {boolean}
  55777. * @readonly
  55778. * @default true
  55779. */
  55780. this.isClippingGroup = true;
  55781. /**
  55782. * An array with clipping planes.
  55783. *
  55784. * @type {Array<Plane>}
  55785. */
  55786. this.clippingPlanes = [];
  55787. /**
  55788. * Whether clipping should be enabled or not.
  55789. *
  55790. * @type {boolean}
  55791. * @default true
  55792. */
  55793. this.enabled = true;
  55794. /**
  55795. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  55796. *
  55797. * @type {boolean}
  55798. * @default false
  55799. */
  55800. this.clipIntersection = false;
  55801. /**
  55802. * Whether shadows should be clipped or not.
  55803. *
  55804. * @type {boolean}
  55805. * @default false
  55806. */
  55807. this.clipShadows = false;
  55808. }
  55809. }
  55810. 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, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号