three.webgpu.js 1.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918
  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. const isGenerateOnce = this.generate.length === 1;
  1362. if ( isGenerateOnce ) {
  1363. const type = this.getNodeType( builder );
  1364. const nodeData = builder.getDataFromNode( this );
  1365. result = nodeData.snippet;
  1366. if ( result === undefined ) {
  1367. if ( nodeData.generated === undefined ) {
  1368. nodeData.generated = true;
  1369. result = this.generate( builder ) || '';
  1370. nodeData.snippet = result;
  1371. } else {
  1372. warn( 'Node: Recursion detected.', this );
  1373. result = '/* Recursion detected. */';
  1374. }
  1375. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1376. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1377. }
  1378. result = builder.format( result, type, output );
  1379. } else {
  1380. result = this.generate( builder, output ) || '';
  1381. }
  1382. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1383. // if no snippet is generated, return a default value
  1384. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1385. result = builder.generateConst( output );
  1386. }
  1387. }
  1388. builder.removeChain( this );
  1389. builder.addSequentialNode( this );
  1390. return result;
  1391. }
  1392. /**
  1393. * Returns the child nodes as a JSON object.
  1394. *
  1395. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1396. */
  1397. getSerializeChildren() {
  1398. return getNodeChildren( this );
  1399. }
  1400. /**
  1401. * Serializes the node to JSON.
  1402. *
  1403. * @param {Object} json - The output JSON object.
  1404. */
  1405. serialize( json ) {
  1406. const nodeChildren = this.getSerializeChildren();
  1407. const inputNodes = {};
  1408. for ( const { property, index, childNode } of nodeChildren ) {
  1409. if ( index !== undefined ) {
  1410. if ( inputNodes[ property ] === undefined ) {
  1411. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1412. }
  1413. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1414. } else {
  1415. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1416. }
  1417. }
  1418. if ( Object.keys( inputNodes ).length > 0 ) {
  1419. json.inputNodes = inputNodes;
  1420. }
  1421. }
  1422. /**
  1423. * Deserializes the node from the given JSON.
  1424. *
  1425. * @param {Object} json - The JSON object.
  1426. */
  1427. deserialize( json ) {
  1428. if ( json.inputNodes !== undefined ) {
  1429. const nodes = json.meta.nodes;
  1430. for ( const property in json.inputNodes ) {
  1431. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1432. const inputArray = [];
  1433. for ( const uuid of json.inputNodes[ property ] ) {
  1434. inputArray.push( nodes[ uuid ] );
  1435. }
  1436. this[ property ] = inputArray;
  1437. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1438. const inputObject = {};
  1439. for ( const subProperty in json.inputNodes[ property ] ) {
  1440. const uuid = json.inputNodes[ property ][ subProperty ];
  1441. inputObject[ subProperty ] = nodes[ uuid ];
  1442. }
  1443. this[ property ] = inputObject;
  1444. } else {
  1445. const uuid = json.inputNodes[ property ];
  1446. this[ property ] = nodes[ uuid ];
  1447. }
  1448. }
  1449. }
  1450. }
  1451. /**
  1452. * Serializes the node into the three.js JSON Object/Scene format.
  1453. *
  1454. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1455. * @return {Object} The serialized node.
  1456. */
  1457. toJSON( meta ) {
  1458. const { uuid, type } = this;
  1459. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1460. if ( isRoot ) {
  1461. meta = {
  1462. textures: {},
  1463. images: {},
  1464. nodes: {}
  1465. };
  1466. }
  1467. // serialize
  1468. let data = meta.nodes[ uuid ];
  1469. if ( data === undefined ) {
  1470. data = {
  1471. uuid,
  1472. type,
  1473. meta,
  1474. metadata: {
  1475. version: 4.7,
  1476. type: 'Node',
  1477. generator: 'Node.toJSON'
  1478. }
  1479. };
  1480. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1481. this.serialize( data );
  1482. delete data.meta;
  1483. }
  1484. // TODO: Copied from Object3D.toJSON
  1485. function extractFromCache( cache ) {
  1486. const values = [];
  1487. for ( const key in cache ) {
  1488. const data = cache[ key ];
  1489. delete data.metadata;
  1490. values.push( data );
  1491. }
  1492. return values;
  1493. }
  1494. if ( isRoot ) {
  1495. const textures = extractFromCache( meta.textures );
  1496. const images = extractFromCache( meta.images );
  1497. const nodes = extractFromCache( meta.nodes );
  1498. if ( textures.length > 0 ) data.textures = textures;
  1499. if ( images.length > 0 ) data.images = images;
  1500. if ( nodes.length > 0 ) data.nodes = nodes;
  1501. }
  1502. return data;
  1503. }
  1504. }
  1505. /**
  1506. * Base class for representing element access on an array-like
  1507. * node data structures.
  1508. *
  1509. * @augments Node
  1510. */
  1511. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1512. static get type() {
  1513. return 'ArrayElementNode';
  1514. }
  1515. /**
  1516. * Constructs an array element node.
  1517. *
  1518. * @param {Node} node - The array-like node.
  1519. * @param {Node} indexNode - The index node that defines the element access.
  1520. */
  1521. constructor( node, indexNode ) {
  1522. super();
  1523. /**
  1524. * The array-like node.
  1525. *
  1526. * @type {Node}
  1527. */
  1528. this.node = node;
  1529. /**
  1530. * The index node that defines the element access.
  1531. *
  1532. * @type {Node}
  1533. */
  1534. this.indexNode = indexNode;
  1535. /**
  1536. * This flag can be used for type testing.
  1537. *
  1538. * @type {boolean}
  1539. * @readonly
  1540. * @default true
  1541. */
  1542. this.isArrayElementNode = true;
  1543. }
  1544. /**
  1545. * This method is overwritten since the node type is inferred from the array-like node.
  1546. *
  1547. * @param {NodeBuilder} builder - The current node builder.
  1548. * @return {string} The node type.
  1549. */
  1550. getNodeType( builder ) {
  1551. return this.node.getElementType( builder );
  1552. }
  1553. generate( builder ) {
  1554. const indexType = this.indexNode.getNodeType( builder );
  1555. const nodeSnippet = this.node.build( builder );
  1556. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1557. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1558. }
  1559. }
  1560. /**
  1561. * This module is part of the TSL core and usually not used in app level code.
  1562. * It represents a convert operation during the shader generation process
  1563. * meaning it converts the data type of a node to a target data type.
  1564. *
  1565. * @augments Node
  1566. */
  1567. class ConvertNode extends Node {
  1568. static get type() {
  1569. return 'ConvertNode';
  1570. }
  1571. /**
  1572. * Constructs a new convert node.
  1573. *
  1574. * @param {Node} node - The node which type should be converted.
  1575. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1576. */
  1577. constructor( node, convertTo ) {
  1578. super();
  1579. /**
  1580. * The node which type should be converted.
  1581. *
  1582. * @type {Node}
  1583. */
  1584. this.node = node;
  1585. /**
  1586. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1587. *
  1588. * @type {string}
  1589. */
  1590. this.convertTo = convertTo;
  1591. }
  1592. /**
  1593. * This method is overwritten since the implementation tries to infer the best
  1594. * matching type from the {@link ConvertNode#convertTo} property.
  1595. *
  1596. * @param {NodeBuilder} builder - The current node builder.
  1597. * @return {string} The node type.
  1598. */
  1599. getNodeType( builder ) {
  1600. const requestType = this.node.getNodeType( builder );
  1601. let convertTo = null;
  1602. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1603. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1604. convertTo = overloadingType;
  1605. }
  1606. }
  1607. return convertTo;
  1608. }
  1609. serialize( data ) {
  1610. super.serialize( data );
  1611. data.convertTo = this.convertTo;
  1612. }
  1613. deserialize( data ) {
  1614. super.deserialize( data );
  1615. this.convertTo = data.convertTo;
  1616. }
  1617. generate( builder, output ) {
  1618. const node = this.node;
  1619. const type = this.getNodeType( builder );
  1620. const snippet = node.build( builder, type );
  1621. return builder.format( snippet, type, output );
  1622. }
  1623. }
  1624. /**
  1625. * This module uses cache management to create temporary variables
  1626. * if the node is used more than once to prevent duplicate calculations.
  1627. *
  1628. * The class acts as a base class for many other nodes types.
  1629. *
  1630. * @augments Node
  1631. */
  1632. class TempNode extends Node {
  1633. static get type() {
  1634. return 'TempNode';
  1635. }
  1636. /**
  1637. * Constructs a temp node.
  1638. *
  1639. * @param {?string} nodeType - The node type.
  1640. */
  1641. constructor( nodeType = null ) {
  1642. super( nodeType );
  1643. /**
  1644. * This flag can be used for type testing.
  1645. *
  1646. * @type {boolean}
  1647. * @readonly
  1648. * @default true
  1649. */
  1650. this.isTempNode = true;
  1651. }
  1652. /**
  1653. * Whether this node is used more than once in context of other nodes.
  1654. *
  1655. * @param {NodeBuilder} builder - The node builder.
  1656. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1657. */
  1658. hasDependencies( builder ) {
  1659. return builder.getDataFromNode( this ).usageCount > 1;
  1660. }
  1661. build( builder, output ) {
  1662. const buildStage = builder.getBuildStage();
  1663. if ( buildStage === 'generate' ) {
  1664. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1665. const nodeData = builder.getDataFromNode( this );
  1666. if ( nodeData.propertyName !== undefined ) {
  1667. return builder.format( nodeData.propertyName, type, output );
  1668. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1669. const snippet = super.build( builder, type );
  1670. const nodeVar = builder.getVarFromNode( this, null, type );
  1671. const propertyName = builder.getPropertyName( nodeVar );
  1672. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1673. nodeData.snippet = snippet;
  1674. nodeData.propertyName = propertyName;
  1675. return builder.format( nodeData.propertyName, type, output );
  1676. }
  1677. }
  1678. return super.build( builder, output );
  1679. }
  1680. }
  1681. /**
  1682. * This module is part of the TSL core and usually not used in app level code.
  1683. * It represents a join operation during the shader generation process.
  1684. * For example in can compose/join two single floats into a `vec2` type.
  1685. *
  1686. * @augments TempNode
  1687. */
  1688. class JoinNode extends TempNode {
  1689. static get type() {
  1690. return 'JoinNode';
  1691. }
  1692. /**
  1693. * Constructs a new join node.
  1694. *
  1695. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1696. * @param {?string} [nodeType=null] - The node type.
  1697. */
  1698. constructor( nodes = [], nodeType = null ) {
  1699. super( nodeType );
  1700. /**
  1701. * An array of nodes that should be joined.
  1702. *
  1703. * @type {Array<Node>}
  1704. */
  1705. this.nodes = nodes;
  1706. }
  1707. /**
  1708. * This method is overwritten since the node type must be inferred from the
  1709. * joined data length if not explicitly defined.
  1710. *
  1711. * @param {NodeBuilder} builder - The current node builder.
  1712. * @return {string} The node type.
  1713. */
  1714. getNodeType( builder ) {
  1715. if ( this.nodeType !== null ) {
  1716. return builder.getVectorType( this.nodeType );
  1717. }
  1718. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1719. }
  1720. generate( builder, output ) {
  1721. const type = this.getNodeType( builder );
  1722. const maxLength = builder.getTypeLength( type );
  1723. const nodes = this.nodes;
  1724. const primitiveType = builder.getComponentType( type );
  1725. const snippetValues = [];
  1726. let length = 0;
  1727. for ( const input of nodes ) {
  1728. if ( length >= maxLength ) {
  1729. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1730. break;
  1731. }
  1732. let inputType = input.getNodeType( builder );
  1733. let inputTypeLength = builder.getTypeLength( inputType );
  1734. let inputSnippet;
  1735. if ( length + inputTypeLength > maxLength ) {
  1736. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1737. inputTypeLength = maxLength - length;
  1738. inputType = builder.getTypeFromLength( inputTypeLength );
  1739. }
  1740. length += inputTypeLength;
  1741. inputSnippet = input.build( builder, inputType );
  1742. const inputPrimitiveType = builder.getComponentType( inputType );
  1743. if ( inputPrimitiveType !== primitiveType ) {
  1744. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1745. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1746. }
  1747. snippetValues.push( inputSnippet );
  1748. }
  1749. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1750. return builder.format( snippet, type, output );
  1751. }
  1752. }
  1753. const _stringVectorComponents = vectorComponents.join( '' );
  1754. /**
  1755. * This module is part of the TSL core and usually not used in app level code.
  1756. * `SplitNode` represents a property access operation which means it is
  1757. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1758. * For example:
  1759. * ```js
  1760. * const redValue = color.r;
  1761. * ```
  1762. *
  1763. * @augments Node
  1764. */
  1765. class SplitNode extends Node {
  1766. static get type() {
  1767. return 'SplitNode';
  1768. }
  1769. /**
  1770. * Constructs a new split node.
  1771. *
  1772. * @param {Node} node - The node that should be accessed.
  1773. * @param {string} [components='x'] - The components that should be accessed.
  1774. */
  1775. constructor( node, components = 'x' ) {
  1776. super();
  1777. /**
  1778. * The node that should be accessed.
  1779. *
  1780. * @type {Node}
  1781. */
  1782. this.node = node;
  1783. /**
  1784. * The components that should be accessed.
  1785. *
  1786. * @type {string}
  1787. */
  1788. this.components = components;
  1789. /**
  1790. * This flag can be used for type testing.
  1791. *
  1792. * @type {boolean}
  1793. * @readonly
  1794. * @default true
  1795. */
  1796. this.isSplitNode = true;
  1797. }
  1798. /**
  1799. * Returns the vector length which is computed based on the requested components.
  1800. *
  1801. * @return {number} The vector length.
  1802. */
  1803. getVectorLength() {
  1804. let vectorLength = this.components.length;
  1805. for ( const c of this.components ) {
  1806. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1807. }
  1808. return vectorLength;
  1809. }
  1810. /**
  1811. * Returns the component type of the node's type.
  1812. *
  1813. * @param {NodeBuilder} builder - The current node builder.
  1814. * @return {string} The component type.
  1815. */
  1816. getComponentType( builder ) {
  1817. return builder.getComponentType( this.node.getNodeType( builder ) );
  1818. }
  1819. /**
  1820. * This method is overwritten since the node type is inferred from requested components.
  1821. *
  1822. * @param {NodeBuilder} builder - The current node builder.
  1823. * @return {string} The node type.
  1824. */
  1825. getNodeType( builder ) {
  1826. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1827. }
  1828. /**
  1829. * Returns the scope of the node.
  1830. *
  1831. * @return {Node} The scope of the node.
  1832. */
  1833. getScope() {
  1834. return this.node.getScope();
  1835. }
  1836. generate( builder, output ) {
  1837. const node = this.node;
  1838. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1839. let snippet = null;
  1840. if ( nodeTypeLength > 1 ) {
  1841. let type = null;
  1842. const componentsLength = this.getVectorLength();
  1843. if ( componentsLength >= nodeTypeLength ) {
  1844. // needed expand the input node
  1845. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1846. }
  1847. const nodeSnippet = node.build( builder, type );
  1848. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1849. // unnecessary swizzle
  1850. snippet = builder.format( nodeSnippet, type, output );
  1851. } else {
  1852. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1853. }
  1854. } else {
  1855. // ignore .components if .node returns float/integer
  1856. snippet = node.build( builder, output );
  1857. }
  1858. return snippet;
  1859. }
  1860. serialize( data ) {
  1861. super.serialize( data );
  1862. data.components = this.components;
  1863. }
  1864. deserialize( data ) {
  1865. super.deserialize( data );
  1866. this.components = data.components;
  1867. }
  1868. }
  1869. /**
  1870. * This module is part of the TSL core and usually not used in app level code.
  1871. * `SetNode` represents a set operation which means it is used to implement any
  1872. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1873. * For example:
  1874. * ```js
  1875. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1876. * ```
  1877. *
  1878. * @augments TempNode
  1879. */
  1880. class SetNode extends TempNode {
  1881. static get type() {
  1882. return 'SetNode';
  1883. }
  1884. /**
  1885. * Constructs a new set node.
  1886. *
  1887. * @param {Node} sourceNode - The node that should be updated.
  1888. * @param {string} components - The components that should be updated.
  1889. * @param {Node} targetNode - The value node.
  1890. */
  1891. constructor( sourceNode, components, targetNode ) {
  1892. super();
  1893. /**
  1894. * The node that should be updated.
  1895. *
  1896. * @type {Node}
  1897. */
  1898. this.sourceNode = sourceNode;
  1899. /**
  1900. * The components that should be updated.
  1901. *
  1902. * @type {string}
  1903. */
  1904. this.components = components;
  1905. /**
  1906. * The value node.
  1907. *
  1908. * @type {Node}
  1909. */
  1910. this.targetNode = targetNode;
  1911. }
  1912. /**
  1913. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1914. *
  1915. * @param {NodeBuilder} builder - The current node builder.
  1916. * @return {string} The node type.
  1917. */
  1918. getNodeType( builder ) {
  1919. return this.sourceNode.getNodeType( builder );
  1920. }
  1921. generate( builder ) {
  1922. const { sourceNode, components, targetNode } = this;
  1923. const sourceType = this.getNodeType( builder );
  1924. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1925. const targetType = builder.getTypeFromLength( components.length, componentType );
  1926. const targetSnippet = targetNode.build( builder, targetType );
  1927. const sourceSnippet = sourceNode.build( builder, sourceType );
  1928. const length = builder.getTypeLength( sourceType );
  1929. const snippetValues = [];
  1930. for ( let i = 0; i < length; i ++ ) {
  1931. const component = vectorComponents[ i ];
  1932. if ( component === components[ 0 ] ) {
  1933. snippetValues.push( targetSnippet );
  1934. i += components.length - 1;
  1935. } else {
  1936. snippetValues.push( sourceSnippet + '.' + component );
  1937. }
  1938. }
  1939. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1940. }
  1941. }
  1942. /**
  1943. * This module is part of the TSL core and usually not used in app level code.
  1944. * It represents a flip operation during the shader generation process
  1945. * meaning it flips normalized values with the following formula:
  1946. * ```
  1947. * x = 1 - x;
  1948. * ```
  1949. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1950. * `flipSTPQ()` method invocations on node objects. For example:
  1951. * ```js
  1952. * uvNode = uvNode.flipY();
  1953. * ```
  1954. *
  1955. * @augments TempNode
  1956. */
  1957. class FlipNode extends TempNode {
  1958. static get type() {
  1959. return 'FlipNode';
  1960. }
  1961. /**
  1962. * Constructs a new flip node.
  1963. *
  1964. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1965. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1966. */
  1967. constructor( sourceNode, components ) {
  1968. super();
  1969. /**
  1970. * The node which component(s) should be flipped.
  1971. *
  1972. * @type {Node}
  1973. */
  1974. this.sourceNode = sourceNode;
  1975. /**
  1976. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1977. *
  1978. * @type {string}
  1979. */
  1980. this.components = components;
  1981. }
  1982. /**
  1983. * This method is overwritten since the node type is inferred from the source node.
  1984. *
  1985. * @param {NodeBuilder} builder - The current node builder.
  1986. * @return {string} The node type.
  1987. */
  1988. getNodeType( builder ) {
  1989. return this.sourceNode.getNodeType( builder );
  1990. }
  1991. generate( builder ) {
  1992. const { components, sourceNode } = this;
  1993. const sourceType = this.getNodeType( builder );
  1994. const sourceSnippet = sourceNode.build( builder );
  1995. const sourceCache = builder.getVarFromNode( this );
  1996. const sourceProperty = builder.getPropertyName( sourceCache );
  1997. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1998. const length = builder.getTypeLength( sourceType );
  1999. const snippetValues = [];
  2000. let componentIndex = 0;
  2001. for ( let i = 0; i < length; i ++ ) {
  2002. const component = vectorComponents[ i ];
  2003. if ( component === components[ componentIndex ] ) {
  2004. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2005. componentIndex ++;
  2006. } else {
  2007. snippetValues.push( sourceProperty + '.' + component );
  2008. }
  2009. }
  2010. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2011. }
  2012. }
  2013. /**
  2014. * Base class for representing data input nodes.
  2015. *
  2016. * @augments Node
  2017. */
  2018. class InputNode extends Node {
  2019. static get type() {
  2020. return 'InputNode';
  2021. }
  2022. /**
  2023. * Constructs a new input node.
  2024. *
  2025. * @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).
  2026. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2027. */
  2028. constructor( value, nodeType = null ) {
  2029. super( nodeType );
  2030. /**
  2031. * This flag can be used for type testing.
  2032. *
  2033. * @type {boolean}
  2034. * @readonly
  2035. * @default true
  2036. */
  2037. this.isInputNode = true;
  2038. /**
  2039. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2040. *
  2041. * @type {any}
  2042. */
  2043. this.value = value;
  2044. /**
  2045. * The precision of the value in the shader.
  2046. *
  2047. * @type {?('low'|'medium'|'high')}
  2048. * @default null
  2049. */
  2050. this.precision = null;
  2051. }
  2052. getNodeType( /*builder*/ ) {
  2053. if ( this.nodeType === null ) {
  2054. return getValueType( this.value );
  2055. }
  2056. return this.nodeType;
  2057. }
  2058. /**
  2059. * Returns the input type of the node which is by default the node type. Derived modules
  2060. * might overwrite this method and use a fixed type or compute one analytically.
  2061. *
  2062. * A typical example for different input and node types are textures. The input type of a
  2063. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2064. *
  2065. * @param {NodeBuilder} builder - The current node builder.
  2066. * @return {string} The input type.
  2067. */
  2068. getInputType( builder ) {
  2069. return this.getNodeType( builder );
  2070. }
  2071. /**
  2072. * Sets the precision to the given value. The method can be
  2073. * overwritten in derived classes if the final precision must be computed
  2074. * analytically.
  2075. *
  2076. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2077. * @return {InputNode} A reference to this node.
  2078. */
  2079. setPrecision( precision ) {
  2080. this.precision = precision;
  2081. return this;
  2082. }
  2083. serialize( data ) {
  2084. super.serialize( data );
  2085. data.value = this.value;
  2086. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2087. data.valueType = getValueType( this.value );
  2088. data.nodeType = this.nodeType;
  2089. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2090. data.precision = this.precision;
  2091. }
  2092. deserialize( data ) {
  2093. super.deserialize( data );
  2094. this.nodeType = data.nodeType;
  2095. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2096. this.precision = data.precision || null;
  2097. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2098. }
  2099. generate( /*builder, output*/ ) {
  2100. warn( 'Abstract function.' );
  2101. }
  2102. }
  2103. const _regNum = /float|u?int/;
  2104. /**
  2105. * Class for representing a constant value in the shader.
  2106. *
  2107. * @augments InputNode
  2108. */
  2109. class ConstNode extends InputNode {
  2110. static get type() {
  2111. return 'ConstNode';
  2112. }
  2113. /**
  2114. * Constructs a new input node.
  2115. *
  2116. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2117. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2118. */
  2119. constructor( value, nodeType = null ) {
  2120. super( value, nodeType );
  2121. /**
  2122. * This flag can be used for type testing.
  2123. *
  2124. * @type {boolean}
  2125. * @readonly
  2126. * @default true
  2127. */
  2128. this.isConstNode = true;
  2129. }
  2130. /**
  2131. * Generates the shader string of the value with the current node builder.
  2132. *
  2133. * @param {NodeBuilder} builder - The current node builder.
  2134. * @return {string} The generated value as a shader string.
  2135. */
  2136. generateConst( builder ) {
  2137. return builder.generateConst( this.getNodeType( builder ), this.value );
  2138. }
  2139. generate( builder, output ) {
  2140. const type = this.getNodeType( builder );
  2141. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2142. return builder.generateConst( output, this.value );
  2143. }
  2144. return builder.format( this.generateConst( builder ), type, output );
  2145. }
  2146. }
  2147. /**
  2148. * Base class for representing member access on an object-like
  2149. * node data structures.
  2150. *
  2151. * @augments Node
  2152. */
  2153. class MemberNode extends Node {
  2154. static get type() {
  2155. return 'MemberNode';
  2156. }
  2157. /**
  2158. * Constructs a member node.
  2159. *
  2160. * @param {Node} structNode - The struct node.
  2161. * @param {string} property - The property name.
  2162. */
  2163. constructor( structNode, property ) {
  2164. super();
  2165. /**
  2166. * The struct node.
  2167. *
  2168. * @type {Node}
  2169. */
  2170. this.structNode = structNode;
  2171. /**
  2172. * The property name.
  2173. *
  2174. * @type {Node}
  2175. */
  2176. this.property = property;
  2177. /**
  2178. * This flag can be used for type testing.
  2179. *
  2180. * @type {boolean}
  2181. * @readonly
  2182. * @default true
  2183. */
  2184. this.isMemberNode = true;
  2185. }
  2186. hasMember( builder ) {
  2187. if ( this.structNode.isMemberNode ) {
  2188. if ( this.structNode.hasMember( builder ) === false ) {
  2189. return false;
  2190. }
  2191. }
  2192. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2193. }
  2194. getNodeType( builder ) {
  2195. if ( this.hasMember( builder ) === false ) {
  2196. // default type if member does not exist
  2197. return 'float';
  2198. }
  2199. return this.structNode.getMemberType( builder, this.property );
  2200. }
  2201. getMemberType( builder, name ) {
  2202. if ( this.hasMember( builder ) === false ) {
  2203. // default type if member does not exist
  2204. return 'float';
  2205. }
  2206. const type = this.getNodeType( builder );
  2207. const struct = builder.getStructTypeNode( type );
  2208. return struct.getMemberType( builder, name );
  2209. }
  2210. generate( builder ) {
  2211. if ( this.hasMember( builder ) === false ) {
  2212. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2213. const type = this.getNodeType( builder );
  2214. return builder.generateConst( type );
  2215. }
  2216. const propertyName = this.structNode.build( builder );
  2217. return propertyName + '.' + this.property;
  2218. }
  2219. }
  2220. let currentStack = null;
  2221. const NodeElements = new Map();
  2222. // Extend Node Class for TSL using prototype
  2223. function addMethodChaining( name, nodeElement ) {
  2224. if ( NodeElements.has( name ) ) {
  2225. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2226. return;
  2227. }
  2228. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2229. NodeElements.set( name, nodeElement );
  2230. if ( name !== 'assign' ) {
  2231. // Changing Node prototype to add method chaining
  2232. Node.prototype[ name ] = function ( ...params ) {
  2233. //if ( name === 'toVarIntent' ) return this;
  2234. return this.isStackNode ? this.add( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2235. };
  2236. // Adding assign method chaining
  2237. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2238. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2239. };
  2240. }
  2241. }
  2242. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2243. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2244. Node.prototype.assign = function ( ...params ) {
  2245. if ( this.isStackNode !== true ) {
  2246. if ( currentStack !== null ) {
  2247. currentStack.assign( this, ...params );
  2248. } else {
  2249. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2250. }
  2251. return this;
  2252. } else {
  2253. const nodeElement = NodeElements.get( 'assign' );
  2254. return this.add( nodeElement( ...params ) );
  2255. }
  2256. };
  2257. Node.prototype.toVarIntent = function () {
  2258. return this;
  2259. };
  2260. Node.prototype.get = function ( value ) {
  2261. return new MemberNode( this, value );
  2262. };
  2263. // Cache prototype for TSL
  2264. const proto = {};
  2265. // Set swizzle properties for xyzw, rgba, and stpq.
  2266. function setProtoSwizzle( property, altA, altB ) {
  2267. // swizzle properties
  2268. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2269. get() {
  2270. this._cache = this._cache || {};
  2271. //
  2272. let split = this._cache[ property ];
  2273. if ( split === undefined ) {
  2274. split = new SplitNode( this, property );
  2275. this._cache[ property ] = split;
  2276. }
  2277. return split;
  2278. },
  2279. set( value ) {
  2280. this[ property ].assign( nodeObject( value ) );
  2281. }
  2282. };
  2283. // set properties ( swizzle ) and sort to xyzw sequence
  2284. const propUpper = property.toUpperCase();
  2285. const altAUpper = altA.toUpperCase();
  2286. const altBUpper = altB.toUpperCase();
  2287. // Set methods for swizzle properties
  2288. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2289. const swizzle = parseSwizzleAndSort( property );
  2290. return new SetNode( this, swizzle, nodeObject( value ) );
  2291. };
  2292. // Set methods for flip properties
  2293. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2294. const swizzle = parseSwizzleAndSort( property );
  2295. return new FlipNode( this, swizzle );
  2296. };
  2297. }
  2298. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2299. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2300. const swizzleC = [ 's', 't', 'p', 'q' ];
  2301. for ( let a = 0; a < 4; a ++ ) {
  2302. let prop = swizzleA[ a ];
  2303. let altA = swizzleB[ a ];
  2304. let altB = swizzleC[ a ];
  2305. setProtoSwizzle( prop, altA, altB );
  2306. for ( let b = 0; b < 4; b ++ ) {
  2307. prop = swizzleA[ a ] + swizzleA[ b ];
  2308. altA = swizzleB[ a ] + swizzleB[ b ];
  2309. altB = swizzleC[ a ] + swizzleC[ b ];
  2310. setProtoSwizzle( prop, altA, altB );
  2311. for ( let c = 0; c < 4; c ++ ) {
  2312. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2313. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2314. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2315. setProtoSwizzle( prop, altA, altB );
  2316. for ( let d = 0; d < 4; d ++ ) {
  2317. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2318. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2319. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2320. setProtoSwizzle( prop, altA, altB );
  2321. }
  2322. }
  2323. }
  2324. }
  2325. // Set/get static properties for array elements (0-31).
  2326. for ( let i = 0; i < 32; i ++ ) {
  2327. proto[ i ] = {
  2328. get() {
  2329. this._cache = this._cache || {};
  2330. //
  2331. let element = this._cache[ i ];
  2332. if ( element === undefined ) {
  2333. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2334. this._cache[ i ] = element;
  2335. }
  2336. return element;
  2337. },
  2338. set( value ) {
  2339. this[ i ].assign( nodeObject( value ) );
  2340. }
  2341. };
  2342. }
  2343. /*
  2344. // Set properties for width, height, and depth.
  2345. function setProtoProperty( property, target ) {
  2346. proto[ property ] = {
  2347. get() {
  2348. this._cache = this._cache || {};
  2349. //
  2350. let split = this._cache[ target ];
  2351. if ( split === undefined ) {
  2352. split = new SplitNode( this, target );
  2353. this._cache[ target ] = split;
  2354. }
  2355. return split;
  2356. },
  2357. set( value ) {
  2358. this[ target ].assign( nodeObject( value ) );
  2359. }
  2360. };
  2361. }
  2362. setProtoProperty( 'width', 'x' );
  2363. setProtoProperty( 'height', 'y' );
  2364. setProtoProperty( 'depth', 'z' );
  2365. */
  2366. Object.defineProperties( Node.prototype, proto );
  2367. // --- FINISH ---
  2368. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2369. const ShaderNodeObject = function ( obj, altType = null ) {
  2370. const type = getValueType( obj );
  2371. if ( type === 'node' ) {
  2372. return obj;
  2373. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2374. return nodeObject( getConstNode( obj, altType ) );
  2375. } else if ( type === 'shader' ) {
  2376. return obj.isFn ? obj : Fn( obj );
  2377. }
  2378. return obj;
  2379. };
  2380. const ShaderNodeObjects = function ( objects, altType = null ) {
  2381. for ( const name in objects ) {
  2382. objects[ name ] = nodeObject( objects[ name ], altType );
  2383. }
  2384. return objects;
  2385. };
  2386. const ShaderNodeArray = function ( array, altType = null ) {
  2387. const len = array.length;
  2388. for ( let i = 0; i < len; i ++ ) {
  2389. array[ i ] = nodeObject( array[ i ], altType );
  2390. }
  2391. return array;
  2392. };
  2393. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2394. function assignNode( node ) {
  2395. if ( settings !== null ) {
  2396. node = nodeObject( Object.assign( node, settings ) );
  2397. if ( settings.intent === true ) {
  2398. node = node.toVarIntent();
  2399. }
  2400. } else {
  2401. node = nodeObject( node );
  2402. }
  2403. return node;
  2404. }
  2405. let fn, name = scope, minParams, maxParams;
  2406. function verifyParamsLimit( params ) {
  2407. let tslName;
  2408. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2409. else tslName = NodeClass.type;
  2410. if ( minParams !== undefined && params.length < minParams ) {
  2411. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2412. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2413. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2414. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2415. return params.slice( 0, maxParams );
  2416. }
  2417. return params;
  2418. }
  2419. if ( scope === null ) {
  2420. fn = ( ...params ) => {
  2421. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2422. };
  2423. } else if ( factor !== null ) {
  2424. factor = nodeObject( factor );
  2425. fn = ( ...params ) => {
  2426. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2427. };
  2428. } else {
  2429. fn = ( ...params ) => {
  2430. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2431. };
  2432. }
  2433. fn.setParameterLength = ( ...params ) => {
  2434. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2435. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2436. return fn;
  2437. };
  2438. fn.setName = ( value ) => {
  2439. name = value;
  2440. return fn;
  2441. };
  2442. return fn;
  2443. };
  2444. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2445. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2446. };
  2447. class ShaderCallNodeInternal extends Node {
  2448. constructor( shaderNode, rawInputs ) {
  2449. super();
  2450. this.shaderNode = shaderNode;
  2451. this.rawInputs = rawInputs;
  2452. this.isShaderCallNodeInternal = true;
  2453. }
  2454. getNodeType( builder ) {
  2455. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2456. }
  2457. getMemberType( builder, name ) {
  2458. return this.getOutputNode( builder ).getMemberType( builder, name );
  2459. }
  2460. call( builder ) {
  2461. const { shaderNode, rawInputs } = this;
  2462. const properties = builder.getNodeProperties( shaderNode );
  2463. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2464. const subBuildProperty = subBuild || 'default';
  2465. if ( properties[ subBuildProperty ] ) {
  2466. return properties[ subBuildProperty ];
  2467. }
  2468. //
  2469. const previousSubBuildFn = builder.subBuildFn;
  2470. const previousFnCall = builder.fnCall;
  2471. builder.subBuildFn = subBuild;
  2472. builder.fnCall = this;
  2473. let result = null;
  2474. if ( shaderNode.layout ) {
  2475. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2476. if ( functionNodesCacheMap === undefined ) {
  2477. functionNodesCacheMap = new WeakMap();
  2478. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2479. }
  2480. let functionNode = functionNodesCacheMap.get( shaderNode );
  2481. if ( functionNode === undefined ) {
  2482. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2483. functionNodesCacheMap.set( shaderNode, functionNode );
  2484. }
  2485. builder.addInclude( functionNode );
  2486. //
  2487. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2488. result = nodeObject( functionNode.call( inputs ) );
  2489. } else {
  2490. const secureNodeBuilder = new Proxy( builder, {
  2491. get: ( target, property, receiver ) => {
  2492. let value;
  2493. if ( Symbol.iterator === property ) {
  2494. value = function* () {
  2495. yield undefined;
  2496. };
  2497. } else {
  2498. value = Reflect.get( target, property, receiver );
  2499. }
  2500. return value;
  2501. }
  2502. } );
  2503. //
  2504. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2505. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2506. const jsFunc = shaderNode.jsFunc;
  2507. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2508. result = nodeObject( outputNode );
  2509. }
  2510. builder.subBuildFn = previousSubBuildFn;
  2511. builder.fnCall = previousFnCall;
  2512. if ( shaderNode.once ) {
  2513. properties[ subBuildProperty ] = result;
  2514. }
  2515. return result;
  2516. }
  2517. setupOutput( builder ) {
  2518. builder.addStack();
  2519. builder.stack.outputNode = this.call( builder );
  2520. return builder.removeStack();
  2521. }
  2522. getOutputNode( builder ) {
  2523. const properties = builder.getNodeProperties( this );
  2524. const subBuildOutput = builder.getSubBuildOutput( this );
  2525. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2526. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2527. return properties[ subBuildOutput ];
  2528. }
  2529. build( builder, output = null ) {
  2530. let result = null;
  2531. const buildStage = builder.getBuildStage();
  2532. const properties = builder.getNodeProperties( this );
  2533. const subBuildOutput = builder.getSubBuildOutput( this );
  2534. const outputNode = this.getOutputNode( builder );
  2535. const previousFnCall = builder.fnCall;
  2536. builder.fnCall = this;
  2537. if ( buildStage === 'setup' ) {
  2538. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2539. if ( properties[ subBuildInitialized ] !== true ) {
  2540. properties[ subBuildInitialized ] = true;
  2541. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2542. properties[ subBuildOutput ].build( builder );
  2543. // If the shaderNode has subBuilds, add them to the chaining nodes
  2544. // so they can be built later in the build process.
  2545. if ( this.shaderNode.subBuilds ) {
  2546. for ( const node of builder.chaining ) {
  2547. const nodeData = builder.getDataFromNode( node, 'any' );
  2548. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2549. for ( const subBuild of this.shaderNode.subBuilds ) {
  2550. nodeData.subBuilds.add( subBuild );
  2551. }
  2552. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2553. }
  2554. }
  2555. }
  2556. result = properties[ subBuildOutput ];
  2557. } else if ( buildStage === 'analyze' ) {
  2558. outputNode.build( builder, output );
  2559. } else if ( buildStage === 'generate' ) {
  2560. result = outputNode.build( builder, output ) || '';
  2561. }
  2562. builder.fnCall = previousFnCall;
  2563. return result;
  2564. }
  2565. }
  2566. function getLayoutParameters( params ) {
  2567. let output;
  2568. nodeObjects( params );
  2569. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2570. if ( isArrayAsParameter ) {
  2571. output = [ ...params ];
  2572. } else {
  2573. output = params[ 0 ];
  2574. }
  2575. return output;
  2576. }
  2577. function getProxyParameters( params ) {
  2578. let index = 0;
  2579. nodeObjects( params );
  2580. return new Proxy( params, {
  2581. get: ( target, property, receiver ) => {
  2582. let value;
  2583. if ( property === 'length' ) {
  2584. value = params.length;
  2585. return value;
  2586. }
  2587. if ( Symbol.iterator === property ) {
  2588. value = function* () {
  2589. for ( const inputNode of params ) {
  2590. yield nodeObject( inputNode );
  2591. }
  2592. };
  2593. } else {
  2594. if ( params.length > 0 ) {
  2595. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2596. const objectTarget = params[ 0 ];
  2597. if ( objectTarget[ property ] === undefined ) {
  2598. value = objectTarget[ index ++ ];
  2599. } else {
  2600. value = Reflect.get( objectTarget, property, receiver );
  2601. }
  2602. } else if ( params[ 0 ] instanceof Node ) {
  2603. if ( params[ property ] === undefined ) {
  2604. value = params[ index ++ ];
  2605. } else {
  2606. value = Reflect.get( params, property, receiver );
  2607. }
  2608. }
  2609. } else {
  2610. value = Reflect.get( target, property, receiver );
  2611. }
  2612. value = nodeObject( value );
  2613. }
  2614. return value;
  2615. }
  2616. } );
  2617. }
  2618. class ShaderNodeInternal extends Node {
  2619. constructor( jsFunc, nodeType ) {
  2620. super( nodeType );
  2621. this.jsFunc = jsFunc;
  2622. this.layout = null;
  2623. this.global = true;
  2624. this.once = false;
  2625. }
  2626. setLayout( layout ) {
  2627. this.layout = layout;
  2628. return this;
  2629. }
  2630. getLayout() {
  2631. return this.layout;
  2632. }
  2633. call( rawInputs = null ) {
  2634. return new ShaderCallNodeInternal( this, rawInputs );
  2635. }
  2636. setup() {
  2637. return this.call();
  2638. }
  2639. }
  2640. const bools = [ false, true ];
  2641. const uints = [ 0, 1, 2, 3 ];
  2642. const ints = [ -1, -2 ];
  2643. 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 ];
  2644. const boolsCacheMap = new Map();
  2645. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2646. const uintsCacheMap = new Map();
  2647. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2648. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2649. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2650. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2651. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2652. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2653. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2654. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2655. const getConstNode = ( value, type ) => {
  2656. if ( constNodesCacheMap.has( value ) ) {
  2657. return constNodesCacheMap.get( value );
  2658. } else if ( value.isNode === true ) {
  2659. return value;
  2660. } else {
  2661. return new ConstNode( value, type );
  2662. }
  2663. };
  2664. const ConvertType = function ( type, cacheMap = null ) {
  2665. return ( ...params ) => {
  2666. for ( const param of params ) {
  2667. if ( param === undefined ) {
  2668. error( `TSL: Invalid parameter for the type "${ type }".` );
  2669. return nodeObject( new ConstNode( 0, type ) );
  2670. }
  2671. }
  2672. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2673. const paramType = typeof param;
  2674. return paramType !== 'object' && paramType !== 'function';
  2675. } ) ) ) {
  2676. params = [ getValueFromType( type, ...params ) ];
  2677. }
  2678. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2679. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2680. }
  2681. if ( params.length === 1 ) {
  2682. const node = getConstNode( params[ 0 ], type );
  2683. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2684. return nodeObjectIntent( new ConvertNode( node, type ) );
  2685. }
  2686. const nodes = params.map( param => getConstNode( param ) );
  2687. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2688. };
  2689. };
  2690. // exports
  2691. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2692. // utils
  2693. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2694. // shader node base
  2695. function ShaderNode( jsFunc, nodeType ) {
  2696. return new ShaderNodeInternal( jsFunc, nodeType );
  2697. }
  2698. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2699. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2700. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2701. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2702. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2703. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2704. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2705. let fnId = 0;
  2706. class FnNode extends Node {
  2707. constructor( jsFunc, layout = null ) {
  2708. super();
  2709. let nodeType = null;
  2710. if ( layout !== null ) {
  2711. if ( typeof layout === 'object' ) {
  2712. nodeType = layout.return;
  2713. } else {
  2714. if ( typeof layout === 'string' ) {
  2715. nodeType = layout;
  2716. } else {
  2717. error( 'TSL: Invalid layout type.' );
  2718. }
  2719. layout = null;
  2720. }
  2721. }
  2722. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2723. if ( layout !== null ) {
  2724. this.setLayout( layout );
  2725. }
  2726. this.isFn = true;
  2727. }
  2728. setLayout( layout ) {
  2729. const nodeType = this.shaderNode.nodeType;
  2730. if ( typeof layout.inputs !== 'object' ) {
  2731. const fullLayout = {
  2732. name: 'fn' + fnId ++,
  2733. type: nodeType,
  2734. inputs: []
  2735. };
  2736. for ( const name in layout ) {
  2737. if ( name === 'return' ) continue;
  2738. fullLayout.inputs.push( {
  2739. name: name,
  2740. type: layout[ name ]
  2741. } );
  2742. }
  2743. layout = fullLayout;
  2744. }
  2745. this.shaderNode.setLayout( layout );
  2746. return this;
  2747. }
  2748. getNodeType( builder ) {
  2749. return this.shaderNode.getNodeType( builder ) || 'float';
  2750. }
  2751. call( ...params ) {
  2752. const fnCall = this.shaderNode.call( params );
  2753. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2754. return fnCall.toVarIntent();
  2755. }
  2756. once( subBuilds = null ) {
  2757. this.shaderNode.once = true;
  2758. this.shaderNode.subBuilds = subBuilds;
  2759. return this;
  2760. }
  2761. generate( builder ) {
  2762. const type = this.getNodeType( builder );
  2763. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2764. return builder.generateConst( type );
  2765. }
  2766. }
  2767. function Fn( jsFunc, layout = null ) {
  2768. const instance = new FnNode( jsFunc, layout );
  2769. return new Proxy( () => {}, {
  2770. apply( target, thisArg, params ) {
  2771. return instance.call( ...params );
  2772. },
  2773. get( target, prop, receiver ) {
  2774. return Reflect.get( instance, prop, receiver );
  2775. },
  2776. set( target, prop, value, receiver ) {
  2777. return Reflect.set( instance, prop, value, receiver );
  2778. }
  2779. } );
  2780. }
  2781. //
  2782. const setCurrentStack = ( stack ) => {
  2783. currentStack = stack;
  2784. };
  2785. const getCurrentStack = () => currentStack;
  2786. /**
  2787. * Represent a conditional node using if/else statements.
  2788. *
  2789. * ```js
  2790. * If( condition, function )
  2791. * .ElseIf( condition, function )
  2792. * .Else( function )
  2793. * ```
  2794. * @tsl
  2795. * @function
  2796. * @param {...any} params - The parameters for the conditional node.
  2797. * @returns {StackNode} The conditional node.
  2798. */
  2799. const If = ( ...params ) => currentStack.If( ...params );
  2800. /**
  2801. * Represent a conditional node using switch/case statements.
  2802. *
  2803. * ```js
  2804. * Switch( value )
  2805. * .Case( 1, function )
  2806. * .Case( 2, 3, 4, function )
  2807. * .Default( function )
  2808. * ```
  2809. * @tsl
  2810. * @function
  2811. * @param {...any} params - The parameters for the conditional node.
  2812. * @returns {StackNode} The conditional node.
  2813. */
  2814. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2815. /**
  2816. * Add the given node to the current stack.
  2817. *
  2818. * @param {Node} node - The node to add.
  2819. * @returns {Node} The node that was added to the stack.
  2820. */
  2821. function Stack( node ) {
  2822. if ( currentStack ) currentStack.add( node );
  2823. return node;
  2824. }
  2825. addMethodChaining( 'toStack', Stack );
  2826. // types
  2827. const color = new ConvertType( 'color' );
  2828. const float = new ConvertType( 'float', cacheMaps.float );
  2829. const int = new ConvertType( 'int', cacheMaps.ints );
  2830. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2831. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2832. const vec2 = new ConvertType( 'vec2' );
  2833. const ivec2 = new ConvertType( 'ivec2' );
  2834. const uvec2 = new ConvertType( 'uvec2' );
  2835. const bvec2 = new ConvertType( 'bvec2' );
  2836. const vec3 = new ConvertType( 'vec3' );
  2837. const ivec3 = new ConvertType( 'ivec3' );
  2838. const uvec3 = new ConvertType( 'uvec3' );
  2839. const bvec3 = new ConvertType( 'bvec3' );
  2840. const vec4 = new ConvertType( 'vec4' );
  2841. const ivec4 = new ConvertType( 'ivec4' );
  2842. const uvec4 = new ConvertType( 'uvec4' );
  2843. const bvec4 = new ConvertType( 'bvec4' );
  2844. const mat2 = new ConvertType( 'mat2' );
  2845. const mat3 = new ConvertType( 'mat3' );
  2846. const mat4 = new ConvertType( 'mat4' );
  2847. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2848. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2849. addMethodChaining( 'toColor', color );
  2850. addMethodChaining( 'toFloat', float );
  2851. addMethodChaining( 'toInt', int );
  2852. addMethodChaining( 'toUint', uint );
  2853. addMethodChaining( 'toBool', bool );
  2854. addMethodChaining( 'toVec2', vec2 );
  2855. addMethodChaining( 'toIVec2', ivec2 );
  2856. addMethodChaining( 'toUVec2', uvec2 );
  2857. addMethodChaining( 'toBVec2', bvec2 );
  2858. addMethodChaining( 'toVec3', vec3 );
  2859. addMethodChaining( 'toIVec3', ivec3 );
  2860. addMethodChaining( 'toUVec3', uvec3 );
  2861. addMethodChaining( 'toBVec3', bvec3 );
  2862. addMethodChaining( 'toVec4', vec4 );
  2863. addMethodChaining( 'toIVec4', ivec4 );
  2864. addMethodChaining( 'toUVec4', uvec4 );
  2865. addMethodChaining( 'toBVec4', bvec4 );
  2866. addMethodChaining( 'toMat2', mat2 );
  2867. addMethodChaining( 'toMat3', mat3 );
  2868. addMethodChaining( 'toMat4', mat4 );
  2869. // basic nodes
  2870. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2871. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2872. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2873. addMethodChaining( 'element', element );
  2874. addMethodChaining( 'convert', convert );
  2875. // deprecated
  2876. /**
  2877. * @tsl
  2878. * @function
  2879. * @deprecated since r176. Use {@link Stack} instead.
  2880. *
  2881. * @param {Node} node - The node to add.
  2882. * @returns {Function}
  2883. */
  2884. const append = ( node ) => { // @deprecated, r176
  2885. warn( 'TSL: append() has been renamed to Stack().' );
  2886. return Stack( node );
  2887. };
  2888. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2889. warn( 'TSL: .append() has been renamed to .toStack().' );
  2890. return Stack( node );
  2891. } );
  2892. /**
  2893. * This class represents a shader property. It can be used
  2894. * to explicitly define a property and assign a value to it.
  2895. *
  2896. * ```js
  2897. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2898. *```
  2899. * `PropertyNode` is used by the engine to predefined common material properties
  2900. * for TSL code.
  2901. *
  2902. * @augments Node
  2903. */
  2904. class PropertyNode extends Node {
  2905. static get type() {
  2906. return 'PropertyNode';
  2907. }
  2908. /**
  2909. * Constructs a new property node.
  2910. *
  2911. * @param {string} nodeType - The type of the node.
  2912. * @param {?string} [name=null] - The name of the property in the shader.
  2913. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2914. */
  2915. constructor( nodeType, name = null, varying = false ) {
  2916. super( nodeType );
  2917. /**
  2918. * The name of the property in the shader. If no name is defined,
  2919. * the node system auto-generates one.
  2920. *
  2921. * @type {?string}
  2922. * @default null
  2923. */
  2924. this.name = name;
  2925. /**
  2926. * Whether this property is a varying or not.
  2927. *
  2928. * @type {boolean}
  2929. * @default false
  2930. */
  2931. this.varying = varying;
  2932. /**
  2933. * This flag can be used for type testing.
  2934. *
  2935. * @type {boolean}
  2936. * @readonly
  2937. * @default true
  2938. */
  2939. this.isPropertyNode = true;
  2940. /**
  2941. * This flag is used for global cache.
  2942. *
  2943. * @type {boolean}
  2944. * @default true
  2945. */
  2946. this.global = true;
  2947. }
  2948. getHash( builder ) {
  2949. return this.name || super.getHash( builder );
  2950. }
  2951. generate( builder ) {
  2952. let nodeVar;
  2953. if ( this.varying === true ) {
  2954. nodeVar = builder.getVaryingFromNode( this, this.name );
  2955. nodeVar.needsInterpolation = true;
  2956. } else {
  2957. nodeVar = builder.getVarFromNode( this, this.name );
  2958. }
  2959. return builder.getPropertyName( nodeVar );
  2960. }
  2961. }
  2962. /**
  2963. * TSL function for creating a property node.
  2964. *
  2965. * @tsl
  2966. * @function
  2967. * @param {string} type - The type of the node.
  2968. * @param {?string} [name=null] - The name of the property in the shader.
  2969. * @returns {PropertyNode}
  2970. */
  2971. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2972. /**
  2973. * TSL function for creating a varying property node.
  2974. *
  2975. * @tsl
  2976. * @function
  2977. * @param {string} type - The type of the node.
  2978. * @param {?string} [name=null] - The name of the varying in the shader.
  2979. * @returns {PropertyNode}
  2980. */
  2981. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2982. /**
  2983. * TSL object that represents the shader variable `DiffuseColor`.
  2984. *
  2985. * @tsl
  2986. * @type {PropertyNode<vec4>}
  2987. */
  2988. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2989. /**
  2990. * TSL object that represents the shader variable `EmissiveColor`.
  2991. *
  2992. * @tsl
  2993. * @type {PropertyNode<vec3>}
  2994. */
  2995. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2996. /**
  2997. * TSL object that represents the shader variable `Roughness`.
  2998. *
  2999. * @tsl
  3000. * @type {PropertyNode<float>}
  3001. */
  3002. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3003. /**
  3004. * TSL object that represents the shader variable `Metalness`.
  3005. *
  3006. * @tsl
  3007. * @type {PropertyNode<float>}
  3008. */
  3009. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3010. /**
  3011. * TSL object that represents the shader variable `Clearcoat`.
  3012. *
  3013. * @tsl
  3014. * @type {PropertyNode<float>}
  3015. */
  3016. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3017. /**
  3018. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3019. *
  3020. * @tsl
  3021. * @type {PropertyNode<float>}
  3022. */
  3023. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3024. /**
  3025. * TSL object that represents the shader variable `Sheen`.
  3026. *
  3027. * @tsl
  3028. * @type {PropertyNode<vec3>}
  3029. */
  3030. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3031. /**
  3032. * TSL object that represents the shader variable `SheenRoughness`.
  3033. *
  3034. * @tsl
  3035. * @type {PropertyNode<float>}
  3036. */
  3037. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3038. /**
  3039. * TSL object that represents the shader variable `Iridescence`.
  3040. *
  3041. * @tsl
  3042. * @type {PropertyNode<float>}
  3043. */
  3044. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3045. /**
  3046. * TSL object that represents the shader variable `IridescenceIOR`.
  3047. *
  3048. * @tsl
  3049. * @type {PropertyNode<float>}
  3050. */
  3051. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3052. /**
  3053. * TSL object that represents the shader variable `IridescenceThickness`.
  3054. *
  3055. * @tsl
  3056. * @type {PropertyNode<float>}
  3057. */
  3058. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3059. /**
  3060. * TSL object that represents the shader variable `AlphaT`.
  3061. *
  3062. * @tsl
  3063. * @type {PropertyNode<float>}
  3064. */
  3065. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3066. /**
  3067. * TSL object that represents the shader variable `Anisotropy`.
  3068. *
  3069. * @tsl
  3070. * @type {PropertyNode<float>}
  3071. */
  3072. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3073. /**
  3074. * TSL object that represents the shader variable `AnisotropyT`.
  3075. *
  3076. * @tsl
  3077. * @type {PropertyNode<vec3>}
  3078. */
  3079. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3080. /**
  3081. * TSL object that represents the shader variable `AnisotropyB`.
  3082. *
  3083. * @tsl
  3084. * @type {PropertyNode<vec3>}
  3085. */
  3086. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3087. /**
  3088. * TSL object that represents the shader variable `SpecularColor`.
  3089. *
  3090. * @tsl
  3091. * @type {PropertyNode<color>}
  3092. */
  3093. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3094. /**
  3095. * TSL object that represents the shader variable `SpecularF90`.
  3096. *
  3097. * @tsl
  3098. * @type {PropertyNode<float>}
  3099. */
  3100. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3101. /**
  3102. * TSL object that represents the shader variable `Shininess`.
  3103. *
  3104. * @tsl
  3105. * @type {PropertyNode<float>}
  3106. */
  3107. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3108. /**
  3109. * TSL object that represents the shader variable `Output`.
  3110. *
  3111. * @tsl
  3112. * @type {PropertyNode<vec4>}
  3113. */
  3114. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3115. /**
  3116. * TSL object that represents the shader variable `dashSize`.
  3117. *
  3118. * @tsl
  3119. * @type {PropertyNode<float>}
  3120. */
  3121. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3122. /**
  3123. * TSL object that represents the shader variable `gapSize`.
  3124. *
  3125. * @tsl
  3126. * @type {PropertyNode<float>}
  3127. */
  3128. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3129. /**
  3130. * TSL object that represents the shader variable `pointWidth`.
  3131. *
  3132. * @tsl
  3133. * @type {PropertyNode<float>}
  3134. */
  3135. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3136. /**
  3137. * TSL object that represents the shader variable `IOR`.
  3138. *
  3139. * @tsl
  3140. * @type {PropertyNode<float>}
  3141. */
  3142. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3143. /**
  3144. * TSL object that represents the shader variable `Transmission`.
  3145. *
  3146. * @tsl
  3147. * @type {PropertyNode<float>}
  3148. */
  3149. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3150. /**
  3151. * TSL object that represents the shader variable `Thickness`.
  3152. *
  3153. * @tsl
  3154. * @type {PropertyNode<float>}
  3155. */
  3156. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3157. /**
  3158. * TSL object that represents the shader variable `AttenuationDistance`.
  3159. *
  3160. * @tsl
  3161. * @type {PropertyNode<float>}
  3162. */
  3163. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3164. /**
  3165. * TSL object that represents the shader variable `AttenuationColor`.
  3166. *
  3167. * @tsl
  3168. * @type {PropertyNode<color>}
  3169. */
  3170. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3171. /**
  3172. * TSL object that represents the shader variable `Dispersion`.
  3173. *
  3174. * @tsl
  3175. * @type {PropertyNode<float>}
  3176. */
  3177. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3178. /**
  3179. * This node can be used to group single instances of {@link UniformNode}
  3180. * and manage them as a uniform buffer.
  3181. *
  3182. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3183. * will be used when defining the {@link UniformNode#groupNode} property.
  3184. *
  3185. * - `objectGroup`: Uniform buffer per object.
  3186. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3187. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3188. *
  3189. * @augments Node
  3190. */
  3191. class UniformGroupNode extends Node {
  3192. static get type() {
  3193. return 'UniformGroupNode';
  3194. }
  3195. /**
  3196. * Constructs a new uniform group node.
  3197. *
  3198. * @param {string} name - The name of the uniform group node.
  3199. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3200. * @param {number} [order=1] - Influences the internal sorting.
  3201. */
  3202. constructor( name, shared = false, order = 1 ) {
  3203. super( 'string' );
  3204. /**
  3205. * The name of the uniform group node.
  3206. *
  3207. * @type {string}
  3208. */
  3209. this.name = name;
  3210. /**
  3211. * Whether this uniform group node is shared or not.
  3212. *
  3213. * @type {boolean}
  3214. * @default false
  3215. */
  3216. this.shared = shared;
  3217. /**
  3218. * Influences the internal sorting.
  3219. * TODO: Add details when this property should be changed.
  3220. *
  3221. * @type {number}
  3222. * @default 1
  3223. */
  3224. this.order = order;
  3225. /**
  3226. * This flag can be used for type testing.
  3227. *
  3228. * @type {boolean}
  3229. * @readonly
  3230. * @default true
  3231. */
  3232. this.isUniformGroup = true;
  3233. }
  3234. serialize( data ) {
  3235. super.serialize( data );
  3236. data.name = this.name;
  3237. data.version = this.version;
  3238. data.shared = this.shared;
  3239. }
  3240. deserialize( data ) {
  3241. super.deserialize( data );
  3242. this.name = data.name;
  3243. this.version = data.version;
  3244. this.shared = data.shared;
  3245. }
  3246. }
  3247. /**
  3248. * TSL function for creating a uniform group node with the given name.
  3249. *
  3250. * @tsl
  3251. * @function
  3252. * @param {string} name - The name of the uniform group node.
  3253. * @returns {UniformGroupNode}
  3254. */
  3255. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3256. /**
  3257. * TSL function for creating a shared uniform group node with the given name and order.
  3258. *
  3259. * @tsl
  3260. * @function
  3261. * @param {string} name - The name of the uniform group node.
  3262. * @param {number} [order=0] - Influences the internal sorting.
  3263. * @returns {UniformGroupNode}
  3264. */
  3265. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3266. /**
  3267. * TSL object that represents a shared uniform group node which is updated once per frame.
  3268. *
  3269. * @tsl
  3270. * @type {UniformGroupNode}
  3271. */
  3272. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3273. /**
  3274. * TSL object that represents a shared uniform group node which is updated once per render.
  3275. *
  3276. * @tsl
  3277. * @type {UniformGroupNode}
  3278. */
  3279. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3280. /**
  3281. * TSL object that represents a uniform group node which is updated once per object.
  3282. *
  3283. * @tsl
  3284. * @type {UniformGroupNode}
  3285. */
  3286. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3287. /**
  3288. * Class for representing a uniform.
  3289. *
  3290. * @augments InputNode
  3291. */
  3292. class UniformNode extends InputNode {
  3293. static get type() {
  3294. return 'UniformNode';
  3295. }
  3296. /**
  3297. * Constructs a new uniform node.
  3298. *
  3299. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3300. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3301. */
  3302. constructor( value, nodeType = null ) {
  3303. super( value, nodeType );
  3304. /**
  3305. * This flag can be used for type testing.
  3306. *
  3307. * @type {boolean}
  3308. * @readonly
  3309. * @default true
  3310. */
  3311. this.isUniformNode = true;
  3312. /**
  3313. * The name or label of the uniform.
  3314. *
  3315. * @type {string}
  3316. * @default ''
  3317. */
  3318. this.name = '';
  3319. /**
  3320. * The uniform group of this uniform. By default, uniforms are
  3321. * managed per object but they might belong to a shared group
  3322. * which is updated per frame or render call.
  3323. *
  3324. * @type {UniformGroupNode}
  3325. */
  3326. this.groupNode = objectGroup;
  3327. }
  3328. /**
  3329. * Sets the {@link UniformNode#name} property.
  3330. *
  3331. * @param {string} name - The name of the uniform.
  3332. * @return {UniformNode} A reference to this node.
  3333. */
  3334. setName( name ) {
  3335. this.name = name;
  3336. return this;
  3337. }
  3338. /**
  3339. * Sets the {@link UniformNode#name} property.
  3340. *
  3341. * @deprecated
  3342. * @param {string} name - The name of the uniform.
  3343. * @return {UniformNode} A reference to this node.
  3344. */
  3345. label( name ) {
  3346. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3347. return this.setName( name );
  3348. }
  3349. /**
  3350. * Sets the {@link UniformNode#groupNode} property.
  3351. *
  3352. * @param {UniformGroupNode} group - The uniform group.
  3353. * @return {UniformNode} A reference to this node.
  3354. */
  3355. setGroup( group ) {
  3356. this.groupNode = group;
  3357. return this;
  3358. }
  3359. /**
  3360. * Returns the {@link UniformNode#groupNode}.
  3361. *
  3362. * @return {UniformGroupNode} The uniform group.
  3363. */
  3364. getGroup() {
  3365. return this.groupNode;
  3366. }
  3367. /**
  3368. * By default, this method returns the result of {@link Node#getHash} but derived
  3369. * classes might overwrite this method with a different implementation.
  3370. *
  3371. * @param {NodeBuilder} builder - The current node builder.
  3372. * @return {string} The uniform hash.
  3373. */
  3374. getUniformHash( builder ) {
  3375. return this.getHash( builder );
  3376. }
  3377. onUpdate( callback, updateType ) {
  3378. callback = callback.bind( this );
  3379. return super.onUpdate( ( frame ) => {
  3380. const value = callback( frame, this );
  3381. if ( value !== undefined ) {
  3382. this.value = value;
  3383. }
  3384. }, updateType );
  3385. }
  3386. getInputType( builder ) {
  3387. let type = super.getInputType( builder );
  3388. if ( type === 'bool' ) {
  3389. type = 'uint';
  3390. }
  3391. return type;
  3392. }
  3393. generate( builder, output ) {
  3394. const type = this.getNodeType( builder );
  3395. const hash = this.getUniformHash( builder );
  3396. let sharedNode = builder.getNodeFromHash( hash );
  3397. if ( sharedNode === undefined ) {
  3398. builder.setHashNode( this, hash );
  3399. sharedNode = this;
  3400. }
  3401. const sharedNodeType = sharedNode.getInputType( builder );
  3402. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3403. const uniformName = builder.getPropertyName( nodeUniform );
  3404. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3405. //
  3406. let snippet = uniformName;
  3407. if ( type === 'bool' ) {
  3408. // cache to variable
  3409. const nodeData = builder.getDataFromNode( this );
  3410. let propertyName = nodeData.propertyName;
  3411. if ( propertyName === undefined ) {
  3412. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3413. propertyName = builder.getPropertyName( nodeVar );
  3414. nodeData.propertyName = propertyName;
  3415. snippet = builder.format( uniformName, sharedNodeType, type );
  3416. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3417. }
  3418. snippet = propertyName;
  3419. }
  3420. return builder.format( snippet, type, output );
  3421. }
  3422. }
  3423. /**
  3424. * TSL function for creating a uniform node.
  3425. *
  3426. * @tsl
  3427. * @function
  3428. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3429. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3430. * @returns {UniformNode}
  3431. */
  3432. const uniform = ( value, type ) => {
  3433. const nodeType = getConstNodeType( type || value );
  3434. if ( nodeType === value ) {
  3435. // if the value is a type but no having a value
  3436. value = getValueFromType( nodeType );
  3437. }
  3438. // @TODO: get ConstNode from .traverse() in the future
  3439. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3440. return nodeObject( new UniformNode( value, nodeType ) );
  3441. };
  3442. /**
  3443. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3444. * ```js
  3445. * const colors = array( [
  3446. * vec3( 1, 0, 0 ),
  3447. * vec3( 0, 1, 0 ),
  3448. * vec3( 0, 0, 1 )
  3449. * ] );
  3450. *
  3451. * const redColor = tintColors.element( 0 );
  3452. * ```
  3453. *
  3454. * @augments TempNode
  3455. */
  3456. class ArrayNode extends TempNode {
  3457. static get type() {
  3458. return 'ArrayNode';
  3459. }
  3460. /**
  3461. * Constructs a new array node.
  3462. *
  3463. * @param {?string} nodeType - The data type of the elements.
  3464. * @param {number} count - Size of the array.
  3465. * @param {?Array<Node>} [values=null] - Array default values.
  3466. */
  3467. constructor( nodeType, count, values = null ) {
  3468. super( nodeType );
  3469. /**
  3470. * Array size.
  3471. *
  3472. * @type {number}
  3473. */
  3474. this.count = count;
  3475. /**
  3476. * Array default values.
  3477. *
  3478. * @type {?Array<Node>}
  3479. */
  3480. this.values = values;
  3481. /**
  3482. * This flag can be used for type testing.
  3483. *
  3484. * @type {boolean}
  3485. * @readonly
  3486. * @default true
  3487. */
  3488. this.isArrayNode = true;
  3489. }
  3490. /**
  3491. * Returns the number of elements in the node array.
  3492. *
  3493. * @param {NodeBuilder} builder - The current node builder.
  3494. * @return {number} The number of elements in the node array.
  3495. */
  3496. getArrayCount( /*builder*/ ) {
  3497. return this.count;
  3498. }
  3499. /**
  3500. * Returns the node's type.
  3501. *
  3502. * @param {NodeBuilder} builder - The current node builder.
  3503. * @return {string} The type of the node.
  3504. */
  3505. getNodeType( builder ) {
  3506. if ( this.nodeType === null ) {
  3507. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3508. }
  3509. return this.nodeType;
  3510. }
  3511. /**
  3512. * Returns the node's type.
  3513. *
  3514. * @param {NodeBuilder} builder - The current node builder.
  3515. * @return {string} The type of the node.
  3516. */
  3517. getElementType( builder ) {
  3518. return this.getNodeType( builder );
  3519. }
  3520. /**
  3521. * This method builds the output node and returns the resulting array as a shader string.
  3522. *
  3523. * @param {NodeBuilder} builder - The current node builder.
  3524. * @return {string} The generated shader string.
  3525. */
  3526. generate( builder ) {
  3527. const type = this.getNodeType( builder );
  3528. return builder.generateArray( type, this.count, this.values );
  3529. }
  3530. }
  3531. /**
  3532. * TSL function for creating an array node.
  3533. *
  3534. * @tsl
  3535. * @function
  3536. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3537. * or an array containing the default values (e.g., [ vec3() ]).
  3538. * @param {?number} [count] - Size of the array.
  3539. * @returns {ArrayNode}
  3540. */
  3541. const array = ( ...params ) => {
  3542. let node;
  3543. if ( params.length === 1 ) {
  3544. const values = params[ 0 ];
  3545. node = new ArrayNode( null, values.length, values );
  3546. } else {
  3547. const nodeType = params[ 0 ];
  3548. const count = params[ 1 ];
  3549. node = new ArrayNode( nodeType, count );
  3550. }
  3551. return nodeObject( node );
  3552. };
  3553. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3554. /**
  3555. * These node represents an assign operation. Meaning a node is assigned
  3556. * to another node.
  3557. *
  3558. * @augments TempNode
  3559. */
  3560. class AssignNode extends TempNode {
  3561. static get type() {
  3562. return 'AssignNode';
  3563. }
  3564. /**
  3565. * Constructs a new assign node.
  3566. *
  3567. * @param {Node} targetNode - The target node.
  3568. * @param {Node} sourceNode - The source type.
  3569. */
  3570. constructor( targetNode, sourceNode ) {
  3571. super();
  3572. /**
  3573. * The target node.
  3574. *
  3575. * @type {Node}
  3576. */
  3577. this.targetNode = targetNode;
  3578. /**
  3579. * The source node.
  3580. *
  3581. * @type {Node}
  3582. */
  3583. this.sourceNode = sourceNode;
  3584. /**
  3585. * This flag can be used for type testing.
  3586. *
  3587. * @type {boolean}
  3588. * @readonly
  3589. * @default true
  3590. */
  3591. this.isAssignNode = true;
  3592. }
  3593. /**
  3594. * Whether this node is used more than once in context of other nodes. This method
  3595. * is overwritten since it always returns `false` (assigns are unique).
  3596. *
  3597. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3598. */
  3599. hasDependencies() {
  3600. return false;
  3601. }
  3602. getNodeType( builder, output ) {
  3603. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3604. }
  3605. /**
  3606. * Whether a split is required when assigning source to target. This can happen when the component length of
  3607. * target and source data type does not match.
  3608. *
  3609. * @param {NodeBuilder} builder - The current node builder.
  3610. * @return {boolean} Whether a split is required when assigning source to target.
  3611. */
  3612. needsSplitAssign( builder ) {
  3613. const { targetNode } = this;
  3614. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3615. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3616. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3617. return assignDifferentVector;
  3618. }
  3619. return false;
  3620. }
  3621. setup( builder ) {
  3622. const { targetNode, sourceNode } = this;
  3623. const scope = targetNode.getScope();
  3624. const targetProperties = builder.getNodeProperties( scope );
  3625. targetProperties.assign = true;
  3626. const properties = builder.getNodeProperties( this );
  3627. properties.sourceNode = sourceNode;
  3628. properties.targetNode = targetNode.context( { assign: true } );
  3629. }
  3630. generate( builder, output ) {
  3631. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3632. const needsSplitAssign = this.needsSplitAssign( builder );
  3633. const target = targetNode.build( builder );
  3634. const targetType = targetNode.getNodeType( builder );
  3635. const source = sourceNode.build( builder, targetType );
  3636. const sourceType = sourceNode.getNodeType( builder );
  3637. const nodeData = builder.getDataFromNode( this );
  3638. //
  3639. let snippet;
  3640. if ( nodeData.initialized === true ) {
  3641. if ( output !== 'void' ) {
  3642. snippet = target;
  3643. }
  3644. } else if ( needsSplitAssign ) {
  3645. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3646. const sourceProperty = builder.getPropertyName( sourceVar );
  3647. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3648. const splitNode = targetNode.node;
  3649. const splitTargetNode = splitNode.node.context( { assign: true } );
  3650. const targetRoot = splitTargetNode.build( builder );
  3651. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3652. const component = splitNode.components[ i ];
  3653. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3654. }
  3655. if ( output !== 'void' ) {
  3656. snippet = target;
  3657. }
  3658. } else {
  3659. snippet = `${ target } = ${ source }`;
  3660. if ( output === 'void' || sourceType === 'void' ) {
  3661. builder.addLineFlowCode( snippet, this );
  3662. if ( output !== 'void' ) {
  3663. snippet = target;
  3664. }
  3665. }
  3666. }
  3667. nodeData.initialized = true;
  3668. return builder.format( snippet, targetType, output );
  3669. }
  3670. }
  3671. /**
  3672. * TSL function for creating an assign node.
  3673. *
  3674. * @tsl
  3675. * @function
  3676. * @param {Node} targetNode - The target node.
  3677. * @param {Node} sourceNode - The source type.
  3678. * @returns {AssignNode}
  3679. */
  3680. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3681. addMethodChaining( 'assign', assign );
  3682. /**
  3683. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3684. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3685. * this logic.
  3686. *
  3687. * @augments TempNode
  3688. */
  3689. class FunctionCallNode extends TempNode {
  3690. static get type() {
  3691. return 'FunctionCallNode';
  3692. }
  3693. /**
  3694. * Constructs a new function call node.
  3695. *
  3696. * @param {?FunctionNode} functionNode - The function node.
  3697. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3698. */
  3699. constructor( functionNode = null, parameters = {} ) {
  3700. super();
  3701. /**
  3702. * The function node.
  3703. *
  3704. * @type {?FunctionNode}
  3705. * @default null
  3706. */
  3707. this.functionNode = functionNode;
  3708. /**
  3709. * The parameters of the function call.
  3710. *
  3711. * @type {Object<string, Node>}
  3712. * @default {}
  3713. */
  3714. this.parameters = parameters;
  3715. }
  3716. /**
  3717. * Sets the parameters of the function call node.
  3718. *
  3719. * @param {Object<string, Node>} parameters - The parameters to set.
  3720. * @return {FunctionCallNode} A reference to this node.
  3721. */
  3722. setParameters( parameters ) {
  3723. this.parameters = parameters;
  3724. return this;
  3725. }
  3726. /**
  3727. * Returns the parameters of the function call node.
  3728. *
  3729. * @return {Object<string, Node>} The parameters of this node.
  3730. */
  3731. getParameters() {
  3732. return this.parameters;
  3733. }
  3734. /**
  3735. * Returns the type of this function call node.
  3736. *
  3737. * @param {NodeBuilder} builder - The current node builder.
  3738. * @returns {string} The type of this node.
  3739. */
  3740. getNodeType( builder ) {
  3741. return this.functionNode.getNodeType( builder );
  3742. }
  3743. /**
  3744. * Returns the function node of this function call node.
  3745. *
  3746. * @param {NodeBuilder} builder - The current node builder.
  3747. * @param {string} [name] - The name of the member.
  3748. * @returns {string} The type of the member.
  3749. */
  3750. getMemberType( builder, name ) {
  3751. return this.functionNode.getMemberType( builder, name );
  3752. }
  3753. generate( builder ) {
  3754. const params = [];
  3755. const functionNode = this.functionNode;
  3756. const inputs = functionNode.getInputs( builder );
  3757. const parameters = this.parameters;
  3758. const generateInput = ( node, inputNode ) => {
  3759. const type = inputNode.type;
  3760. const pointer = type === 'pointer';
  3761. let output;
  3762. if ( pointer ) output = '&' + node.build( builder );
  3763. else output = node.build( builder, type );
  3764. return output;
  3765. };
  3766. if ( Array.isArray( parameters ) ) {
  3767. if ( parameters.length > inputs.length ) {
  3768. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3769. parameters.length = inputs.length;
  3770. } else if ( parameters.length < inputs.length ) {
  3771. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3772. while ( parameters.length < inputs.length ) {
  3773. parameters.push( float( 0 ) );
  3774. }
  3775. }
  3776. for ( let i = 0; i < parameters.length; i ++ ) {
  3777. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3778. }
  3779. } else {
  3780. for ( const inputNode of inputs ) {
  3781. const node = parameters[ inputNode.name ];
  3782. if ( node !== undefined ) {
  3783. params.push( generateInput( node, inputNode ) );
  3784. } else {
  3785. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3786. params.push( generateInput( float( 0 ), inputNode ) );
  3787. }
  3788. }
  3789. }
  3790. const functionName = functionNode.build( builder, 'property' );
  3791. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3792. }
  3793. }
  3794. const call = ( func, ...params ) => {
  3795. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3796. return new FunctionCallNode( nodeObject( func ), params );
  3797. };
  3798. addMethodChaining( 'call', call );
  3799. const _vectorOperators = {
  3800. '==': 'equal',
  3801. '!=': 'notEqual',
  3802. '<': 'lessThan',
  3803. '>': 'greaterThan',
  3804. '<=': 'lessThanEqual',
  3805. '>=': 'greaterThanEqual',
  3806. '%': 'mod'
  3807. };
  3808. /**
  3809. * This node represents basic mathematical and logical operations like addition,
  3810. * subtraction or comparisons (e.g. `equal()`).
  3811. *
  3812. * @augments TempNode
  3813. */
  3814. class OperatorNode extends TempNode {
  3815. static get type() {
  3816. return 'OperatorNode';
  3817. }
  3818. /**
  3819. * Constructs a new operator node.
  3820. *
  3821. * @param {string} op - The operator.
  3822. * @param {Node} aNode - The first input.
  3823. * @param {Node} bNode - The second input.
  3824. * @param {...Node} params - Additional input parameters.
  3825. */
  3826. constructor( op, aNode, bNode, ...params ) {
  3827. super();
  3828. if ( params.length > 0 ) {
  3829. let finalOp = new OperatorNode( op, aNode, bNode );
  3830. for ( let i = 0; i < params.length - 1; i ++ ) {
  3831. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3832. }
  3833. aNode = finalOp;
  3834. bNode = params[ params.length - 1 ];
  3835. }
  3836. /**
  3837. * The operator.
  3838. *
  3839. * @type {string}
  3840. */
  3841. this.op = op;
  3842. /**
  3843. * The first input.
  3844. *
  3845. * @type {Node}
  3846. */
  3847. this.aNode = aNode;
  3848. /**
  3849. * The second input.
  3850. *
  3851. * @type {Node}
  3852. */
  3853. this.bNode = bNode;
  3854. /**
  3855. * This flag can be used for type testing.
  3856. *
  3857. * @type {boolean}
  3858. * @readonly
  3859. * @default true
  3860. */
  3861. this.isOperatorNode = true;
  3862. }
  3863. /**
  3864. * Returns the operator method name.
  3865. *
  3866. * @param {NodeBuilder} builder - The current node builder.
  3867. * @param {string} output - The output type.
  3868. * @returns {string} The operator method name.
  3869. */
  3870. getOperatorMethod( builder, output ) {
  3871. return builder.getMethod( _vectorOperators[ this.op ], output );
  3872. }
  3873. /**
  3874. * This method is overwritten since the node type is inferred from the operator
  3875. * and the input node types.
  3876. *
  3877. * @param {NodeBuilder} builder - The current node builder.
  3878. * @param {?string} [output=null] - The output type.
  3879. * @return {string} The node type.
  3880. */
  3881. getNodeType( builder, output = null ) {
  3882. const op = this.op;
  3883. const aNode = this.aNode;
  3884. const bNode = this.bNode;
  3885. const typeA = aNode.getNodeType( builder );
  3886. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3887. if ( typeA === 'void' || typeB === 'void' ) {
  3888. return output || 'void';
  3889. } else if ( op === '%' ) {
  3890. return typeA;
  3891. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3892. return builder.getIntegerType( typeA );
  3893. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3894. return 'bool';
  3895. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3896. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3897. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3898. } else {
  3899. // Handle matrix operations
  3900. if ( builder.isMatrix( typeA ) ) {
  3901. if ( typeB === 'float' ) {
  3902. return typeA; // matrix * scalar = matrix
  3903. } else if ( builder.isVector( typeB ) ) {
  3904. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3905. } else if ( builder.isMatrix( typeB ) ) {
  3906. return typeA; // matrix * matrix
  3907. }
  3908. } else if ( builder.isMatrix( typeB ) ) {
  3909. if ( typeA === 'float' ) {
  3910. return typeB; // scalar * matrix = matrix
  3911. } else if ( builder.isVector( typeA ) ) {
  3912. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3913. }
  3914. }
  3915. // Handle non-matrix cases
  3916. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3917. // anytype x anytype: use the greater length vector
  3918. return typeB;
  3919. }
  3920. return typeA;
  3921. }
  3922. }
  3923. generate( builder, output ) {
  3924. const op = this.op;
  3925. const { aNode, bNode } = this;
  3926. const type = this.getNodeType( builder, output );
  3927. let typeA = null;
  3928. let typeB = null;
  3929. if ( type !== 'void' ) {
  3930. typeA = aNode.getNodeType( builder );
  3931. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3932. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3933. if ( builder.isVector( typeA ) ) {
  3934. typeB = typeA;
  3935. } else if ( builder.isVector( typeB ) ) {
  3936. typeA = typeB;
  3937. } else if ( typeA !== typeB ) {
  3938. typeA = typeB = 'float';
  3939. }
  3940. } else if ( op === '>>' || op === '<<' ) {
  3941. typeA = type;
  3942. typeB = builder.changeComponentType( typeB, 'uint' );
  3943. } else if ( op === '%' ) {
  3944. typeA = type;
  3945. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3946. } else if ( builder.isMatrix( typeA ) ) {
  3947. if ( typeB === 'float' ) {
  3948. // Keep matrix type for typeA, but ensure typeB stays float
  3949. typeB = 'float';
  3950. } else if ( builder.isVector( typeB ) ) {
  3951. // matrix x vector
  3952. typeB = builder.getVectorFromMatrix( typeA );
  3953. } else if ( builder.isMatrix( typeB ) ) ; else {
  3954. typeA = typeB = type;
  3955. }
  3956. } else if ( builder.isMatrix( typeB ) ) {
  3957. if ( typeA === 'float' ) {
  3958. // Keep matrix type for typeB, but ensure typeA stays float
  3959. typeA = 'float';
  3960. } else if ( builder.isVector( typeA ) ) {
  3961. // vector x matrix
  3962. typeA = builder.getVectorFromMatrix( typeB );
  3963. } else {
  3964. typeA = typeB = type;
  3965. }
  3966. } else {
  3967. // anytype x anytype
  3968. typeA = typeB = type;
  3969. }
  3970. } else {
  3971. typeA = typeB = type;
  3972. }
  3973. const a = aNode.build( builder, typeA );
  3974. const b = bNode ? bNode.build( builder, typeB ) : null;
  3975. const fnOpSnippet = builder.getFunctionOperator( op );
  3976. if ( output !== 'void' ) {
  3977. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3978. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3979. if ( isGLSL ) {
  3980. if ( builder.isVector( typeA ) ) {
  3981. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3982. } else {
  3983. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3984. }
  3985. } else {
  3986. // WGSL
  3987. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3988. }
  3989. } else if ( op === '%' ) {
  3990. if ( builder.isInteger( typeB ) ) {
  3991. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3992. } else {
  3993. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3994. }
  3995. } else if ( op === '!' || op === '~' ) {
  3996. return builder.format( `(${op}${a})`, typeA, output );
  3997. } else if ( fnOpSnippet ) {
  3998. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3999. } else {
  4000. // Handle matrix operations
  4001. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4002. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4003. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4004. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4005. } else {
  4006. let snippet = `( ${ a } ${ op } ${ b } )`;
  4007. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4008. snippet = `all${ snippet }`;
  4009. }
  4010. return builder.format( snippet, type, output );
  4011. }
  4012. }
  4013. } else if ( typeA !== 'void' ) {
  4014. if ( fnOpSnippet ) {
  4015. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4016. } else {
  4017. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4018. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4019. } else {
  4020. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4021. }
  4022. }
  4023. }
  4024. }
  4025. serialize( data ) {
  4026. super.serialize( data );
  4027. data.op = this.op;
  4028. }
  4029. deserialize( data ) {
  4030. super.deserialize( data );
  4031. this.op = data.op;
  4032. }
  4033. }
  4034. /**
  4035. * Returns the addition of two or more value.
  4036. *
  4037. * @tsl
  4038. * @function
  4039. * @param {Node} a - The first input.
  4040. * @param {Node} b - The second input.
  4041. * @param {...Node} params - Additional input parameters.
  4042. * @returns {OperatorNode}
  4043. */
  4044. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4045. /**
  4046. * Returns the subtraction of two or more value.
  4047. *
  4048. * @tsl
  4049. * @function
  4050. * @param {Node} a - The first input.
  4051. * @param {Node} b - The second input.
  4052. * @param {...Node} params - Additional input parameters.
  4053. * @returns {OperatorNode}
  4054. */
  4055. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4056. /**
  4057. * Returns the multiplication of two or more value.
  4058. *
  4059. * @tsl
  4060. * @function
  4061. * @param {Node} a - The first input.
  4062. * @param {Node} b - The second input.
  4063. * @param {...Node} params - Additional input parameters.
  4064. * @returns {OperatorNode}
  4065. */
  4066. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4067. /**
  4068. * Returns the division of two or more value.
  4069. *
  4070. * @tsl
  4071. * @function
  4072. * @param {Node} a - The first input.
  4073. * @param {Node} b - The second input.
  4074. * @param {...Node} params - Additional input parameters.
  4075. * @returns {OperatorNode}
  4076. */
  4077. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4078. /**
  4079. * Computes the remainder of dividing the first node by the second one.
  4080. *
  4081. * @tsl
  4082. * @function
  4083. * @param {Node} a - The first input.
  4084. * @param {Node} b - The second input.
  4085. * @returns {OperatorNode}
  4086. */
  4087. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4088. /**
  4089. * Checks if two nodes are equal.
  4090. *
  4091. * @tsl
  4092. * @function
  4093. * @param {Node} a - The first input.
  4094. * @param {Node} b - The second input.
  4095. * @returns {OperatorNode}
  4096. */
  4097. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4098. /**
  4099. * Checks if two nodes are not equal.
  4100. *
  4101. * @tsl
  4102. * @function
  4103. * @param {Node} a - The first input.
  4104. * @param {Node} b - The second input.
  4105. * @returns {OperatorNode}
  4106. */
  4107. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4108. /**
  4109. * Checks if the first node is less than the second.
  4110. *
  4111. * @tsl
  4112. * @function
  4113. * @param {Node} a - The first input.
  4114. * @param {Node} b - The second input.
  4115. * @returns {OperatorNode}
  4116. */
  4117. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4118. /**
  4119. * Checks if the first node is greater than the second.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node} a - The first input.
  4124. * @param {Node} b - The second input.
  4125. * @returns {OperatorNode}
  4126. */
  4127. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4128. /**
  4129. * Checks if the first node is less than or equal to the second.
  4130. *
  4131. * @tsl
  4132. * @function
  4133. * @param {Node} a - The first input.
  4134. * @param {Node} b - The second input.
  4135. * @returns {OperatorNode}
  4136. */
  4137. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4138. /**
  4139. * Checks if the first node is greater than or equal to the second.
  4140. *
  4141. * @tsl
  4142. * @function
  4143. * @param {Node} a - The first input.
  4144. * @param {Node} b - The second input.
  4145. * @returns {OperatorNode}
  4146. */
  4147. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4148. /**
  4149. * Performs a logical AND operation on multiple nodes.
  4150. *
  4151. * @tsl
  4152. * @function
  4153. * @param {...Node} nodes - The input nodes to be combined using AND.
  4154. * @returns {OperatorNode}
  4155. */
  4156. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4157. /**
  4158. * Performs a logical OR operation on multiple nodes.
  4159. *
  4160. * @tsl
  4161. * @function
  4162. * @param {...Node} nodes - The input nodes to be combined using OR.
  4163. * @returns {OperatorNode}
  4164. */
  4165. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4166. /**
  4167. * Performs logical NOT on a node.
  4168. *
  4169. * @tsl
  4170. * @function
  4171. * @param {Node} value - The value.
  4172. * @returns {OperatorNode}
  4173. */
  4174. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4175. /**
  4176. * Performs logical XOR on two nodes.
  4177. *
  4178. * @tsl
  4179. * @function
  4180. * @param {Node} a - The first input.
  4181. * @param {Node} b - The second input.
  4182. * @returns {OperatorNode}
  4183. */
  4184. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4185. /**
  4186. * Performs bitwise AND on two nodes.
  4187. *
  4188. * @tsl
  4189. * @function
  4190. * @param {Node} a - The first input.
  4191. * @param {Node} b - The second input.
  4192. * @returns {OperatorNode}
  4193. */
  4194. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4195. /**
  4196. * Performs bitwise NOT on a node.
  4197. *
  4198. * @tsl
  4199. * @function
  4200. * @param {Node} a - The first input.
  4201. * @param {Node} b - The second input.
  4202. * @returns {OperatorNode}
  4203. */
  4204. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4205. /**
  4206. * Performs bitwise OR on two nodes.
  4207. *
  4208. * @tsl
  4209. * @function
  4210. * @param {Node} a - The first input.
  4211. * @param {Node} b - The second input.
  4212. * @returns {OperatorNode}
  4213. */
  4214. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4215. /**
  4216. * Performs bitwise XOR on two nodes.
  4217. *
  4218. * @tsl
  4219. * @function
  4220. * @param {Node} a - The first input.
  4221. * @param {Node} b - The second input.
  4222. * @returns {OperatorNode}
  4223. */
  4224. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4225. /**
  4226. * Shifts a node to the left.
  4227. *
  4228. * @tsl
  4229. * @function
  4230. * @param {Node} a - The node to shift.
  4231. * @param {Node} b - The value to shift.
  4232. * @returns {OperatorNode}
  4233. */
  4234. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4235. /**
  4236. * Shifts a node to the right.
  4237. *
  4238. * @tsl
  4239. * @function
  4240. * @param {Node} a - The node to shift.
  4241. * @param {Node} b - The value to shift.
  4242. * @returns {OperatorNode}
  4243. */
  4244. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4245. /**
  4246. * Increments a node by 1.
  4247. *
  4248. * @tsl
  4249. * @function
  4250. * @param {Node} a - The node to increment.
  4251. * @returns {OperatorNode}
  4252. */
  4253. const incrementBefore = Fn( ( [ a ] ) => {
  4254. a.addAssign( 1 );
  4255. return a;
  4256. } );
  4257. /**
  4258. * Decrements a node by 1.
  4259. *
  4260. * @tsl
  4261. * @function
  4262. * @param {Node} a - The node to decrement.
  4263. * @returns {OperatorNode}
  4264. */
  4265. const decrementBefore = Fn( ( [ a ] ) => {
  4266. a.subAssign( 1 );
  4267. return a;
  4268. } );
  4269. /**
  4270. * Increments a node by 1 and returns the previous value.
  4271. *
  4272. * @tsl
  4273. * @function
  4274. * @param {Node} a - The node to increment.
  4275. * @returns {OperatorNode}
  4276. */
  4277. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4278. const temp = int( a ).toConst();
  4279. a.addAssign( 1 );
  4280. return temp;
  4281. } );
  4282. /**
  4283. * Decrements a node by 1 and returns the previous value.
  4284. *
  4285. * @tsl
  4286. * @function
  4287. * @param {Node} a - The node to decrement.
  4288. * @returns {OperatorNode}
  4289. */
  4290. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4291. const temp = int( a ).toConst();
  4292. a.subAssign( 1 );
  4293. return temp;
  4294. } );
  4295. addMethodChaining( 'add', add );
  4296. addMethodChaining( 'sub', sub );
  4297. addMethodChaining( 'mul', mul );
  4298. addMethodChaining( 'div', div );
  4299. addMethodChaining( 'mod', mod );
  4300. addMethodChaining( 'equal', equal );
  4301. addMethodChaining( 'notEqual', notEqual );
  4302. addMethodChaining( 'lessThan', lessThan );
  4303. addMethodChaining( 'greaterThan', greaterThan );
  4304. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4305. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4306. addMethodChaining( 'and', and );
  4307. addMethodChaining( 'or', or );
  4308. addMethodChaining( 'not', not );
  4309. addMethodChaining( 'xor', xor );
  4310. addMethodChaining( 'bitAnd', bitAnd );
  4311. addMethodChaining( 'bitNot', bitNot );
  4312. addMethodChaining( 'bitOr', bitOr );
  4313. addMethodChaining( 'bitXor', bitXor );
  4314. addMethodChaining( 'shiftLeft', shiftLeft );
  4315. addMethodChaining( 'shiftRight', shiftRight );
  4316. addMethodChaining( 'incrementBefore', incrementBefore );
  4317. addMethodChaining( 'decrementBefore', decrementBefore );
  4318. addMethodChaining( 'increment', increment );
  4319. addMethodChaining( 'decrement', decrement );
  4320. /**
  4321. * @tsl
  4322. * @function
  4323. * @deprecated since r175. Use {@link mod} instead.
  4324. *
  4325. * @param {Node} a - The first input.
  4326. * @param {Node} b - The second input.
  4327. * @returns {OperatorNode}
  4328. */
  4329. const modInt = ( a, b ) => { // @deprecated, r175
  4330. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4331. return mod( int( a ), int( b ) );
  4332. };
  4333. addMethodChaining( 'modInt', modInt );
  4334. /**
  4335. * This node represents a variety of mathematical methods available in shaders.
  4336. * They are divided into three categories:
  4337. *
  4338. * - Methods with one input like `sin`, `cos` or `normalize`.
  4339. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4340. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4341. *
  4342. * @augments TempNode
  4343. */
  4344. class MathNode extends TempNode {
  4345. static get type() {
  4346. return 'MathNode';
  4347. }
  4348. /**
  4349. * Constructs a new math node.
  4350. *
  4351. * @param {string} method - The method name.
  4352. * @param {Node} aNode - The first input.
  4353. * @param {?Node} [bNode=null] - The second input.
  4354. * @param {?Node} [cNode=null] - The third input.
  4355. */
  4356. constructor( method, aNode, bNode = null, cNode = null ) {
  4357. super();
  4358. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4359. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4360. let finalOp = new MathNode( method, aNode, bNode );
  4361. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4362. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4363. }
  4364. aNode = finalOp;
  4365. bNode = arguments[ arguments.length - 1 ];
  4366. cNode = null;
  4367. }
  4368. /**
  4369. * The method name.
  4370. *
  4371. * @type {string}
  4372. */
  4373. this.method = method;
  4374. /**
  4375. * The first input.
  4376. *
  4377. * @type {Node}
  4378. */
  4379. this.aNode = aNode;
  4380. /**
  4381. * The second input.
  4382. *
  4383. * @type {?Node}
  4384. * @default null
  4385. */
  4386. this.bNode = bNode;
  4387. /**
  4388. * The third input.
  4389. *
  4390. * @type {?Node}
  4391. * @default null
  4392. */
  4393. this.cNode = cNode;
  4394. /**
  4395. * This flag can be used for type testing.
  4396. *
  4397. * @type {boolean}
  4398. * @readonly
  4399. * @default true
  4400. */
  4401. this.isMathNode = true;
  4402. }
  4403. /**
  4404. * The input type is inferred from the node types of the input nodes.
  4405. *
  4406. * @param {NodeBuilder} builder - The current node builder.
  4407. * @return {string} The input type.
  4408. */
  4409. getInputType( builder ) {
  4410. const aType = this.aNode.getNodeType( builder );
  4411. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4412. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4413. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4414. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4415. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4416. if ( aLen > bLen && aLen > cLen ) {
  4417. return aType;
  4418. } else if ( bLen > cLen ) {
  4419. return bType;
  4420. } else if ( cLen > aLen ) {
  4421. return cType;
  4422. }
  4423. return aType;
  4424. }
  4425. /**
  4426. * The selected method as well as the input type determine the node type of this node.
  4427. *
  4428. * @param {NodeBuilder} builder - The current node builder.
  4429. * @return {string} The node type.
  4430. */
  4431. getNodeType( builder ) {
  4432. const method = this.method;
  4433. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4434. return 'float';
  4435. } else if ( method === MathNode.CROSS ) {
  4436. return 'vec3';
  4437. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4438. return 'bool';
  4439. } else if ( method === MathNode.EQUALS ) {
  4440. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4441. } else {
  4442. return this.getInputType( builder );
  4443. }
  4444. }
  4445. setup( builder ) {
  4446. const { aNode, bNode, method } = this;
  4447. let outputNode = null;
  4448. if ( method === MathNode.ONE_MINUS ) {
  4449. outputNode = sub( 1.0, aNode );
  4450. } else if ( method === MathNode.RECIPROCAL ) {
  4451. outputNode = div( 1.0, aNode );
  4452. } else if ( method === MathNode.DIFFERENCE ) {
  4453. outputNode = abs( sub( aNode, bNode ) );
  4454. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4455. // dir can be either a direction vector or a normal vector
  4456. // upper-left 3x3 of matrix is assumed to be orthogonal
  4457. let tA = aNode;
  4458. let tB = bNode;
  4459. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4460. tB = vec4( vec3( tB ), 0.0 );
  4461. } else {
  4462. tA = vec4( vec3( tA ), 0.0 );
  4463. }
  4464. const mulNode = mul( tA, tB ).xyz;
  4465. outputNode = normalize( mulNode );
  4466. }
  4467. if ( outputNode !== null ) {
  4468. return outputNode;
  4469. } else {
  4470. return super.setup( builder );
  4471. }
  4472. }
  4473. generate( builder, output ) {
  4474. const properties = builder.getNodeProperties( this );
  4475. if ( properties.outputNode ) {
  4476. return super.generate( builder, output );
  4477. }
  4478. let method = this.method;
  4479. const type = this.getNodeType( builder );
  4480. const inputType = this.getInputType( builder );
  4481. const a = this.aNode;
  4482. const b = this.bNode;
  4483. const c = this.cNode;
  4484. const coordinateSystem = builder.renderer.coordinateSystem;
  4485. if ( method === MathNode.NEGATE ) {
  4486. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4487. } else {
  4488. const params = [];
  4489. if ( method === MathNode.CROSS ) {
  4490. params.push(
  4491. a.build( builder, type ),
  4492. b.build( builder, type )
  4493. );
  4494. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4495. params.push(
  4496. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4497. b.build( builder, inputType )
  4498. );
  4499. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4500. params.push(
  4501. a.build( builder, inputType ),
  4502. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4503. );
  4504. } else if ( method === MathNode.REFRACT ) {
  4505. params.push(
  4506. a.build( builder, inputType ),
  4507. b.build( builder, inputType ),
  4508. c.build( builder, 'float' )
  4509. );
  4510. } else if ( method === MathNode.MIX ) {
  4511. params.push(
  4512. a.build( builder, inputType ),
  4513. b.build( builder, inputType ),
  4514. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4515. );
  4516. } else {
  4517. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4518. method = 'atan2';
  4519. }
  4520. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4521. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4522. method = '/*' + method + '*/';
  4523. }
  4524. params.push( a.build( builder, inputType ) );
  4525. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4526. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4527. }
  4528. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4529. }
  4530. }
  4531. serialize( data ) {
  4532. super.serialize( data );
  4533. data.method = this.method;
  4534. }
  4535. deserialize( data ) {
  4536. super.deserialize( data );
  4537. this.method = data.method;
  4538. }
  4539. }
  4540. // 1 input
  4541. MathNode.ALL = 'all';
  4542. MathNode.ANY = 'any';
  4543. MathNode.RADIANS = 'radians';
  4544. MathNode.DEGREES = 'degrees';
  4545. MathNode.EXP = 'exp';
  4546. MathNode.EXP2 = 'exp2';
  4547. MathNode.LOG = 'log';
  4548. MathNode.LOG2 = 'log2';
  4549. MathNode.SQRT = 'sqrt';
  4550. MathNode.INVERSE_SQRT = 'inversesqrt';
  4551. MathNode.FLOOR = 'floor';
  4552. MathNode.CEIL = 'ceil';
  4553. MathNode.NORMALIZE = 'normalize';
  4554. MathNode.FRACT = 'fract';
  4555. MathNode.SIN = 'sin';
  4556. MathNode.COS = 'cos';
  4557. MathNode.TAN = 'tan';
  4558. MathNode.ASIN = 'asin';
  4559. MathNode.ACOS = 'acos';
  4560. MathNode.ATAN = 'atan';
  4561. MathNode.ABS = 'abs';
  4562. MathNode.SIGN = 'sign';
  4563. MathNode.LENGTH = 'length';
  4564. MathNode.NEGATE = 'negate';
  4565. MathNode.ONE_MINUS = 'oneMinus';
  4566. MathNode.DFDX = 'dFdx';
  4567. MathNode.DFDY = 'dFdy';
  4568. MathNode.ROUND = 'round';
  4569. MathNode.RECIPROCAL = 'reciprocal';
  4570. MathNode.TRUNC = 'trunc';
  4571. MathNode.FWIDTH = 'fwidth';
  4572. MathNode.TRANSPOSE = 'transpose';
  4573. MathNode.DETERMINANT = 'determinant';
  4574. MathNode.INVERSE = 'inverse';
  4575. // 2 inputs
  4576. MathNode.EQUALS = 'equals';
  4577. MathNode.MIN = 'min';
  4578. MathNode.MAX = 'max';
  4579. MathNode.STEP = 'step';
  4580. MathNode.REFLECT = 'reflect';
  4581. MathNode.DISTANCE = 'distance';
  4582. MathNode.DIFFERENCE = 'difference';
  4583. MathNode.DOT = 'dot';
  4584. MathNode.CROSS = 'cross';
  4585. MathNode.POW = 'pow';
  4586. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4587. // 3 inputs
  4588. MathNode.MIX = 'mix';
  4589. MathNode.CLAMP = 'clamp';
  4590. MathNode.REFRACT = 'refract';
  4591. MathNode.SMOOTHSTEP = 'smoothstep';
  4592. MathNode.FACEFORWARD = 'faceforward';
  4593. // 1 inputs
  4594. /**
  4595. * A small value used to handle floating-point precision errors.
  4596. *
  4597. * @tsl
  4598. * @type {Node<float>}
  4599. */
  4600. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4601. /**
  4602. * Represents infinity.
  4603. *
  4604. * @tsl
  4605. * @type {Node<float>}
  4606. */
  4607. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4608. /**
  4609. * Represents PI.
  4610. *
  4611. * @tsl
  4612. * @type {Node<float>}
  4613. */
  4614. const PI = /*@__PURE__*/ float( Math.PI );
  4615. /**
  4616. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4617. *
  4618. * @tsl
  4619. * @deprecated
  4620. * @type {Node<float>}
  4621. */
  4622. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4623. /**
  4624. * Represents PI * 2.
  4625. *
  4626. * @tsl
  4627. * @type {Node<float>}
  4628. */
  4629. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4630. /**
  4631. * Represents PI / 2.
  4632. *
  4633. * @tsl
  4634. * @type {Node<float>}
  4635. */
  4636. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4637. /**
  4638. * Returns `true` if all components of `x` are `true`.
  4639. *
  4640. * @tsl
  4641. * @function
  4642. * @param {Node | number} x - The parameter.
  4643. * @returns {Node<bool>}
  4644. */
  4645. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4646. /**
  4647. * Returns `true` if any components of `x` are `true`.
  4648. *
  4649. * @tsl
  4650. * @function
  4651. * @param {Node | number} x - The parameter.
  4652. * @returns {Node<bool>}
  4653. */
  4654. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4655. /**
  4656. * Converts a quantity in degrees to radians.
  4657. *
  4658. * @tsl
  4659. * @function
  4660. * @param {Node | number} x - The input in degrees.
  4661. * @returns {Node}
  4662. */
  4663. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4664. /**
  4665. * Convert a quantity in radians to degrees.
  4666. *
  4667. * @tsl
  4668. * @function
  4669. * @param {Node | number} x - The input in radians.
  4670. * @returns {Node}
  4671. */
  4672. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4673. /**
  4674. * Returns the natural exponentiation of the parameter.
  4675. *
  4676. * @tsl
  4677. * @function
  4678. * @param {Node | number} x - The parameter.
  4679. * @returns {Node}
  4680. */
  4681. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4682. /**
  4683. * Returns 2 raised to the power of the parameter.
  4684. *
  4685. * @tsl
  4686. * @function
  4687. * @param {Node | number} x - The parameter.
  4688. * @returns {Node}
  4689. */
  4690. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4691. /**
  4692. * Returns the natural logarithm of the parameter.
  4693. *
  4694. * @tsl
  4695. * @function
  4696. * @param {Node | number} x - The parameter.
  4697. * @returns {Node}
  4698. */
  4699. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4700. /**
  4701. * Returns the base 2 logarithm of the parameter.
  4702. *
  4703. * @tsl
  4704. * @function
  4705. * @param {Node | number} x - The parameter.
  4706. * @returns {Node}
  4707. */
  4708. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4709. /**
  4710. * Returns the square root of the parameter.
  4711. *
  4712. * @tsl
  4713. * @function
  4714. * @param {Node | number} x - The parameter.
  4715. * @returns {Node}
  4716. */
  4717. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4718. /**
  4719. * Returns the inverse of the square root of the parameter.
  4720. *
  4721. * @tsl
  4722. * @function
  4723. * @param {Node | number} x - The parameter.
  4724. * @returns {Node}
  4725. */
  4726. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4727. /**
  4728. * Finds the nearest integer less than or equal to the parameter.
  4729. *
  4730. * @tsl
  4731. * @function
  4732. * @param {Node | number} x - The parameter.
  4733. * @returns {Node}
  4734. */
  4735. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4736. /**
  4737. * Finds the nearest integer that is greater than or equal to the parameter.
  4738. *
  4739. * @tsl
  4740. * @function
  4741. * @param {Node | number} x - The parameter.
  4742. * @returns {Node}
  4743. */
  4744. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4745. /**
  4746. * Calculates the unit vector in the same direction as the original vector.
  4747. *
  4748. * @tsl
  4749. * @function
  4750. * @param {Node} x - The input vector.
  4751. * @returns {Node}
  4752. */
  4753. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4754. /**
  4755. * Computes the fractional part of the parameter.
  4756. *
  4757. * @tsl
  4758. * @function
  4759. * @param {Node | number} x - The parameter.
  4760. * @returns {Node}
  4761. */
  4762. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4763. /**
  4764. * Returns the sine of the parameter.
  4765. *
  4766. * @tsl
  4767. * @function
  4768. * @param {Node | number} x - The parameter.
  4769. * @returns {Node}
  4770. */
  4771. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4772. /**
  4773. * Returns the cosine of the parameter.
  4774. *
  4775. * @tsl
  4776. * @function
  4777. * @param {Node | number} x - The parameter.
  4778. * @returns {Node}
  4779. */
  4780. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4781. /**
  4782. * Returns the tangent of the parameter.
  4783. *
  4784. * @tsl
  4785. * @function
  4786. * @param {Node | number} x - The parameter.
  4787. * @returns {Node}
  4788. */
  4789. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4790. /**
  4791. * Returns the arcsine of the parameter.
  4792. *
  4793. * @tsl
  4794. * @function
  4795. * @param {Node | number} x - The parameter.
  4796. * @returns {Node}
  4797. */
  4798. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4799. /**
  4800. * Returns the arccosine of the parameter.
  4801. *
  4802. * @tsl
  4803. * @function
  4804. * @param {Node | number} x - The parameter.
  4805. * @returns {Node}
  4806. */
  4807. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4808. /**
  4809. * Returns the arc-tangent of the parameter.
  4810. * If two parameters are provided, the result is `atan2(y/x)`.
  4811. *
  4812. * @tsl
  4813. * @function
  4814. * @param {Node | number} y - The y parameter.
  4815. * @param {?(Node | number)} x - The x parameter.
  4816. * @returns {Node}
  4817. */
  4818. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4819. /**
  4820. * Returns the absolute value of the parameter.
  4821. *
  4822. * @tsl
  4823. * @function
  4824. * @param {Node | number} x - The parameter.
  4825. * @returns {Node}
  4826. */
  4827. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4828. /**
  4829. * Extracts the sign of the parameter.
  4830. *
  4831. * @tsl
  4832. * @function
  4833. * @param {Node | number} x - The parameter.
  4834. * @returns {Node}
  4835. */
  4836. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4837. /**
  4838. * Calculates the length of a vector.
  4839. *
  4840. * @tsl
  4841. * @function
  4842. * @param {Node} x - The parameter.
  4843. * @returns {Node<float>}
  4844. */
  4845. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4846. /**
  4847. * Negates the value of the parameter (-x).
  4848. *
  4849. * @tsl
  4850. * @function
  4851. * @param {Node | number} x - The parameter.
  4852. * @returns {Node}
  4853. */
  4854. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4855. /**
  4856. * Return `1` minus the parameter.
  4857. *
  4858. * @tsl
  4859. * @function
  4860. * @param {Node | number} x - The parameter.
  4861. * @returns {Node}
  4862. */
  4863. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4864. /**
  4865. * Returns the partial derivative of the parameter with respect to x.
  4866. *
  4867. * @tsl
  4868. * @function
  4869. * @param {Node | number} x - The parameter.
  4870. * @returns {Node}
  4871. */
  4872. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4873. /**
  4874. * Returns the partial derivative of the parameter with respect to y.
  4875. *
  4876. * @tsl
  4877. * @function
  4878. * @param {Node | number} x - The parameter.
  4879. * @returns {Node}
  4880. */
  4881. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4882. /**
  4883. * Rounds the parameter to the nearest integer.
  4884. *
  4885. * @tsl
  4886. * @function
  4887. * @param {Node | number} x - The parameter.
  4888. * @returns {Node}
  4889. */
  4890. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4891. /**
  4892. * Returns the reciprocal of the parameter `(1/x)`.
  4893. *
  4894. * @tsl
  4895. * @function
  4896. * @param {Node | number} x - The parameter.
  4897. * @returns {Node}
  4898. */
  4899. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4900. /**
  4901. * Truncates the parameter, removing the fractional part.
  4902. *
  4903. * @tsl
  4904. * @function
  4905. * @param {Node | number} x - The parameter.
  4906. * @returns {Node}
  4907. */
  4908. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4909. /**
  4910. * Returns the sum of the absolute derivatives in x and y.
  4911. *
  4912. * @tsl
  4913. * @function
  4914. * @param {Node | number} x - The parameter.
  4915. * @returns {Node}
  4916. */
  4917. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4918. /**
  4919. * Returns the transpose of a matrix.
  4920. *
  4921. * @tsl
  4922. * @function
  4923. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4924. * @returns {Node}
  4925. */
  4926. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4927. /**
  4928. * Returns the determinant of a matrix.
  4929. *
  4930. * @tsl
  4931. * @function
  4932. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4933. * @returns {Node<float>}
  4934. */
  4935. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4936. /**
  4937. * Returns the inverse of a matrix.
  4938. *
  4939. * @tsl
  4940. * @function
  4941. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4942. * @returns {Node<mat2|mat3|mat4>}
  4943. */
  4944. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4945. // 2 inputs
  4946. /**
  4947. * Returns `true` if `x` equals `y`.
  4948. *
  4949. * @tsl
  4950. * @function
  4951. * @param {Node | number} x - The first parameter.
  4952. * @param {Node | number} y - The second parameter.
  4953. * @deprecated since r175. Use {@link equal} instead.
  4954. * @returns {Node<bool>}
  4955. */
  4956. const equals = ( x, y ) => { // @deprecated, r172
  4957. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4958. return equal( x, y );
  4959. };
  4960. /**
  4961. * Returns the least of the given values.
  4962. *
  4963. * @tsl
  4964. * @function
  4965. * @param {...(Node | number)} values - The values to compare.
  4966. * @returns {Node}
  4967. */
  4968. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4969. /**
  4970. * Returns the greatest of the given values.
  4971. *
  4972. * @tsl
  4973. * @function
  4974. * @param {...(Node | number)} values - The values to compare.
  4975. * @returns {Node}
  4976. */
  4977. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4978. /**
  4979. * Generate a step function by comparing two values.
  4980. *
  4981. * @tsl
  4982. * @function
  4983. * @param {Node | number} x - The y parameter.
  4984. * @param {Node | number} y - The x parameter.
  4985. * @returns {Node}
  4986. */
  4987. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4988. /**
  4989. * Calculates the reflection direction for an incident vector.
  4990. *
  4991. * @tsl
  4992. * @function
  4993. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4994. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4995. * @returns {Node<vec2|vec3|vec4>}
  4996. */
  4997. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4998. /**
  4999. * Calculates the distance between two points.
  5000. *
  5001. * @tsl
  5002. * @function
  5003. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5004. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5005. * @returns {Node<float>}
  5006. */
  5007. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5008. /**
  5009. * Calculates the absolute difference between two values.
  5010. *
  5011. * @tsl
  5012. * @function
  5013. * @param {Node | number} x - The first parameter.
  5014. * @param {Node | number} y - The second parameter.
  5015. * @returns {Node}
  5016. */
  5017. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5018. /**
  5019. * Calculates the dot product of two vectors.
  5020. *
  5021. * @tsl
  5022. * @function
  5023. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5024. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5025. * @returns {Node<float>}
  5026. */
  5027. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5028. /**
  5029. * Calculates the cross product of two vectors.
  5030. *
  5031. * @tsl
  5032. * @function
  5033. * @param {Node<vec2|vec3>} x - The first vector.
  5034. * @param {Node<vec2|vec3>} y - The second vector.
  5035. * @returns {Node<float|vec3>}
  5036. */
  5037. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5038. /**
  5039. * Return the value of the first parameter raised to the power of the second one.
  5040. *
  5041. * @tsl
  5042. * @function
  5043. * @param {Node | number} x - The first parameter.
  5044. * @param {Node | number} y - The second parameter.
  5045. * @returns {Node}
  5046. */
  5047. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5048. /**
  5049. * Returns the square of the parameter.
  5050. *
  5051. * @tsl
  5052. * @function
  5053. * @param {Node | number} x - The first parameter.
  5054. * @returns {Node}
  5055. */
  5056. const pow2 = ( x ) => mul( x, x );
  5057. /**
  5058. * Returns the cube of the parameter.
  5059. *
  5060. * @tsl
  5061. * @function
  5062. * @param {Node | number} x - The first parameter.
  5063. * @returns {Node}
  5064. */
  5065. const pow3 = ( x ) => mul( x, x, x );
  5066. /**
  5067. * Returns the fourth power of the parameter.
  5068. *
  5069. * @tsl
  5070. * @function
  5071. * @param {Node | number} x - The first parameter.
  5072. * @returns {Node}
  5073. */
  5074. const pow4 = ( x ) => mul( x, x, x, x );
  5075. /**
  5076. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5077. *
  5078. * @tsl
  5079. * @function
  5080. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5081. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5082. * @returns {Node}
  5083. */
  5084. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5085. /**
  5086. * Returns the cube root of a number.
  5087. *
  5088. * @tsl
  5089. * @function
  5090. * @param {Node | number} a - The first parameter.
  5091. * @returns {Node}
  5092. */
  5093. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5094. /**
  5095. * Calculate the squared length of a vector.
  5096. *
  5097. * @tsl
  5098. * @function
  5099. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5100. * @returns {Node<float>}
  5101. */
  5102. const lengthSq = ( a ) => dot( a, a );
  5103. /**
  5104. * Linearly interpolates between two values.
  5105. *
  5106. * @tsl
  5107. * @function
  5108. * @param {Node | number} a - The first parameter.
  5109. * @param {Node | number} b - The second parameter.
  5110. * @param {Node | number} t - The interpolation value.
  5111. * @returns {Node}
  5112. */
  5113. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5114. /**
  5115. * Constrains a value to lie between two further values.
  5116. *
  5117. * @tsl
  5118. * @function
  5119. * @param {Node | number} value - The value to constrain.
  5120. * @param {Node | number} [low=0] - The lower bound.
  5121. * @param {Node | number} [high=1] - The upper bound.
  5122. * @returns {Node}
  5123. */
  5124. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5125. /**
  5126. * Constrains a value between `0` and `1`.
  5127. *
  5128. * @tsl
  5129. * @function
  5130. * @param {Node | number} value - The value to constrain.
  5131. * @returns {Node}
  5132. */
  5133. const saturate = ( value ) => clamp( value );
  5134. /**
  5135. * Calculates the refraction direction for an incident vector.
  5136. *
  5137. * @tsl
  5138. * @function
  5139. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5140. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5141. * @param {Node<float>} eta - The ratio of indices of refraction.
  5142. * @returns {Node<vec2|vec3|vec4>}
  5143. */
  5144. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5145. /**
  5146. * Performs a Hermite interpolation between two values.
  5147. *
  5148. * @tsl
  5149. * @function
  5150. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5151. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5152. * @param {Node | number} x - The source value for interpolation.
  5153. * @returns {Node}
  5154. */
  5155. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5156. /**
  5157. * Returns a vector pointing in the same direction as another.
  5158. *
  5159. * @tsl
  5160. * @function
  5161. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5162. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5163. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5164. * @returns {Node<vec2|vec3|vec4>}
  5165. */
  5166. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5167. /**
  5168. * Returns a random value for the given uv.
  5169. *
  5170. * @tsl
  5171. * @function
  5172. * @param {Node<vec2>} uv - The uv node.
  5173. * @returns {Node<float>}
  5174. */
  5175. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5176. const a = 12.9898, b = 78.233, c = 43758.5453;
  5177. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5178. return fract( sin( sn ).mul( c ) );
  5179. } );
  5180. /**
  5181. * Alias for `mix()` with a different parameter order.
  5182. *
  5183. * @tsl
  5184. * @function
  5185. * @param {Node | number} t - The interpolation value.
  5186. * @param {Node | number} e1 - The first parameter.
  5187. * @param {Node | number} e2 - The second parameter.
  5188. * @returns {Node}
  5189. */
  5190. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5191. /**
  5192. * Alias for `smoothstep()` with a different parameter order.
  5193. *
  5194. * @tsl
  5195. * @function
  5196. * @param {Node | number} x - The source value for interpolation.
  5197. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5198. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5199. * @returns {Node}
  5200. */
  5201. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5202. /**
  5203. * Alias for `step()` with a different parameter order.
  5204. *
  5205. * @tsl
  5206. * @function
  5207. * @param {Node | number} x - The source value for interpolation.
  5208. * @param {Node | number} edge - The edge value.
  5209. * @returns {Node}
  5210. */
  5211. const stepElement = ( x, edge ) => step( edge, x );
  5212. /**
  5213. * Returns the arc-tangent of the quotient of its parameters.
  5214. *
  5215. * @tsl
  5216. * @function
  5217. * @deprecated since r172. Use {@link atan} instead.
  5218. *
  5219. * @param {Node | number} y - The y parameter.
  5220. * @param {Node | number} x - The x parameter.
  5221. * @returns {Node}
  5222. */
  5223. const atan2 = ( y, x ) => { // @deprecated, r172
  5224. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5225. return atan( y, x );
  5226. };
  5227. // GLSL alias function
  5228. const faceforward = faceForward;
  5229. const inversesqrt = inverseSqrt;
  5230. // Method chaining
  5231. addMethodChaining( 'all', all );
  5232. addMethodChaining( 'any', any );
  5233. addMethodChaining( 'equals', equals );
  5234. addMethodChaining( 'radians', radians );
  5235. addMethodChaining( 'degrees', degrees );
  5236. addMethodChaining( 'exp', exp );
  5237. addMethodChaining( 'exp2', exp2 );
  5238. addMethodChaining( 'log', log );
  5239. addMethodChaining( 'log2', log2 );
  5240. addMethodChaining( 'sqrt', sqrt );
  5241. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5242. addMethodChaining( 'floor', floor );
  5243. addMethodChaining( 'ceil', ceil );
  5244. addMethodChaining( 'normalize', normalize );
  5245. addMethodChaining( 'fract', fract );
  5246. addMethodChaining( 'sin', sin );
  5247. addMethodChaining( 'cos', cos );
  5248. addMethodChaining( 'tan', tan );
  5249. addMethodChaining( 'asin', asin );
  5250. addMethodChaining( 'acos', acos );
  5251. addMethodChaining( 'atan', atan );
  5252. addMethodChaining( 'abs', abs );
  5253. addMethodChaining( 'sign', sign );
  5254. addMethodChaining( 'length', length );
  5255. addMethodChaining( 'lengthSq', lengthSq );
  5256. addMethodChaining( 'negate', negate );
  5257. addMethodChaining( 'oneMinus', oneMinus );
  5258. addMethodChaining( 'dFdx', dFdx );
  5259. addMethodChaining( 'dFdy', dFdy );
  5260. addMethodChaining( 'round', round );
  5261. addMethodChaining( 'reciprocal', reciprocal );
  5262. addMethodChaining( 'trunc', trunc );
  5263. addMethodChaining( 'fwidth', fwidth );
  5264. addMethodChaining( 'atan2', atan2 );
  5265. addMethodChaining( 'min', min$1 );
  5266. addMethodChaining( 'max', max$1 );
  5267. addMethodChaining( 'step', stepElement );
  5268. addMethodChaining( 'reflect', reflect );
  5269. addMethodChaining( 'distance', distance );
  5270. addMethodChaining( 'dot', dot );
  5271. addMethodChaining( 'cross', cross );
  5272. addMethodChaining( 'pow', pow );
  5273. addMethodChaining( 'pow2', pow2 );
  5274. addMethodChaining( 'pow3', pow3 );
  5275. addMethodChaining( 'pow4', pow4 );
  5276. addMethodChaining( 'transformDirection', transformDirection );
  5277. addMethodChaining( 'mix', mixElement );
  5278. addMethodChaining( 'clamp', clamp );
  5279. addMethodChaining( 'refract', refract );
  5280. addMethodChaining( 'smoothstep', smoothstepElement );
  5281. addMethodChaining( 'faceForward', faceForward );
  5282. addMethodChaining( 'difference', difference );
  5283. addMethodChaining( 'saturate', saturate );
  5284. addMethodChaining( 'cbrt', cbrt );
  5285. addMethodChaining( 'transpose', transpose );
  5286. addMethodChaining( 'determinant', determinant );
  5287. addMethodChaining( 'inverse', inverse );
  5288. addMethodChaining( 'rand', rand );
  5289. /**
  5290. * Represents a logical `if/else` statement. Can be used as an alternative
  5291. * to the `If()`/`Else()` syntax.
  5292. *
  5293. * The corresponding TSL `select()` looks like so:
  5294. * ```js
  5295. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5296. * ```
  5297. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5298. * determine the outcome of the entire statement.
  5299. *
  5300. * @augments Node
  5301. */
  5302. class ConditionalNode extends Node {
  5303. static get type() {
  5304. return 'ConditionalNode';
  5305. }
  5306. /**
  5307. * Constructs a new conditional node.
  5308. *
  5309. * @param {Node} condNode - The node that defines the condition.
  5310. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5311. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5312. */
  5313. constructor( condNode, ifNode, elseNode = null ) {
  5314. super();
  5315. /**
  5316. * The node that defines the condition.
  5317. *
  5318. * @type {Node}
  5319. */
  5320. this.condNode = condNode;
  5321. /**
  5322. * The node that is evaluate when the condition ends up `true`.
  5323. *
  5324. * @type {Node}
  5325. */
  5326. this.ifNode = ifNode;
  5327. /**
  5328. * The node that is evaluate when the condition ends up `false`.
  5329. *
  5330. * @type {?Node}
  5331. * @default null
  5332. */
  5333. this.elseNode = elseNode;
  5334. }
  5335. /**
  5336. * This method is overwritten since the node type is inferred from the if/else
  5337. * nodes.
  5338. *
  5339. * @param {NodeBuilder} builder - The current node builder.
  5340. * @return {string} The node type.
  5341. */
  5342. getNodeType( builder ) {
  5343. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5344. if ( ifNode === undefined ) {
  5345. // fallback setup
  5346. builder.flowBuildStage( this, 'setup' );
  5347. return this.getNodeType( builder );
  5348. }
  5349. const ifType = ifNode.getNodeType( builder );
  5350. if ( elseNode !== null ) {
  5351. const elseType = elseNode.getNodeType( builder );
  5352. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5353. return elseType;
  5354. }
  5355. }
  5356. return ifType;
  5357. }
  5358. setup( builder ) {
  5359. const condNode = this.condNode;
  5360. const ifNode = this.ifNode.isolate();
  5361. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5362. //
  5363. const currentNodeBlock = builder.context.nodeBlock;
  5364. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5365. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5366. //
  5367. const isUniformFlow = builder.context.uniformFlow;
  5368. const properties = builder.getNodeProperties( this );
  5369. properties.condNode = condNode;
  5370. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5371. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5372. }
  5373. generate( builder, output ) {
  5374. const type = this.getNodeType( builder );
  5375. const nodeData = builder.getDataFromNode( this );
  5376. if ( nodeData.nodeProperty !== undefined ) {
  5377. return nodeData.nodeProperty;
  5378. }
  5379. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5380. const functionNode = builder.currentFunctionNode;
  5381. const needsOutput = output !== 'void';
  5382. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5383. nodeData.nodeProperty = nodeProperty;
  5384. const nodeSnippet = condNode.build( builder, 'bool' );
  5385. const isUniformFlow = builder.context.uniformFlow;
  5386. if ( isUniformFlow && elseNode !== null ) {
  5387. const ifSnippet = ifNode.build( builder, type );
  5388. const elseSnippet = elseNode.build( builder, type );
  5389. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5390. // TODO: If node property already exists return something else
  5391. return builder.format( mathSnippet, type, output );
  5392. }
  5393. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5394. let ifSnippet = ifNode.build( builder, type );
  5395. if ( ifSnippet ) {
  5396. if ( needsOutput ) {
  5397. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5398. } else {
  5399. ifSnippet = 'return ' + ifSnippet + ';';
  5400. if ( functionNode === null ) {
  5401. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5402. ifSnippet = '// ' + ifSnippet;
  5403. }
  5404. }
  5405. }
  5406. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5407. if ( elseNode !== null ) {
  5408. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5409. let elseSnippet = elseNode.build( builder, type );
  5410. if ( elseSnippet ) {
  5411. if ( needsOutput ) {
  5412. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5413. } else {
  5414. elseSnippet = 'return ' + elseSnippet + ';';
  5415. if ( functionNode === null ) {
  5416. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5417. elseSnippet = '// ' + elseSnippet;
  5418. }
  5419. }
  5420. }
  5421. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5422. } else {
  5423. builder.addFlowCode( '\n\n' );
  5424. }
  5425. return builder.format( nodeProperty, type, output );
  5426. }
  5427. }
  5428. /**
  5429. * TSL function for creating a conditional node.
  5430. *
  5431. * @tsl
  5432. * @function
  5433. * @param {Node} condNode - The node that defines the condition.
  5434. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5435. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5436. * @returns {ConditionalNode}
  5437. */
  5438. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5439. addMethodChaining( 'select', select );
  5440. /**
  5441. * This node can be used as a context management component for another node.
  5442. * {@link NodeBuilder} performs its node building process in a specific context and
  5443. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5444. *
  5445. * ```js
  5446. *node.context( { getUV: () => customCoord } );
  5447. *```
  5448. * @augments Node
  5449. */
  5450. class ContextNode extends Node {
  5451. static get type() {
  5452. return 'ContextNode';
  5453. }
  5454. /**
  5455. * Constructs a new context node.
  5456. *
  5457. * @param {Node} node - The node whose context should be modified.
  5458. * @param {Object} [value={}] - The modified context data.
  5459. */
  5460. constructor( node, value = {} ) {
  5461. super();
  5462. /**
  5463. * This flag can be used for type testing.
  5464. *
  5465. * @type {boolean}
  5466. * @readonly
  5467. * @default true
  5468. */
  5469. this.isContextNode = true;
  5470. /**
  5471. * The node whose context should be modified.
  5472. *
  5473. * @type {Node}
  5474. */
  5475. this.node = node;
  5476. /**
  5477. * The modified context data.
  5478. *
  5479. * @type {Object}
  5480. * @default {}
  5481. */
  5482. this.value = value;
  5483. }
  5484. /**
  5485. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5486. *
  5487. * @return {Node} A reference to {@link ContextNode#node}.
  5488. */
  5489. getScope() {
  5490. return this.node.getScope();
  5491. }
  5492. /**
  5493. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5494. *
  5495. * @param {NodeBuilder} builder - The current node builder.
  5496. * @return {string} The node type.
  5497. */
  5498. getNodeType( builder ) {
  5499. return this.node.getNodeType( builder );
  5500. }
  5501. /**
  5502. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5503. *
  5504. * @param {NodeBuilder} builder - The current node builder.
  5505. * @param {string} name - The member name.
  5506. * @returns {string} The member type.
  5507. */
  5508. getMemberType( builder, name ) {
  5509. return this.node.getMemberType( builder, name );
  5510. }
  5511. analyze( builder ) {
  5512. const previousContext = builder.addContext( this.value );
  5513. this.node.build( builder );
  5514. builder.setContext( previousContext );
  5515. }
  5516. setup( builder ) {
  5517. const previousContext = builder.addContext( this.value );
  5518. this.node.build( builder );
  5519. builder.setContext( previousContext );
  5520. }
  5521. generate( builder, output ) {
  5522. const previousContext = builder.addContext( this.value );
  5523. const snippet = this.node.build( builder, output );
  5524. builder.setContext( previousContext );
  5525. return snippet;
  5526. }
  5527. }
  5528. /**
  5529. * TSL function for creating a context node.
  5530. *
  5531. * @tsl
  5532. * @function
  5533. * @param {Node} node - The node whose context should be modified.
  5534. * @param {Object} [value={}] - The modified context data.
  5535. * @returns {ContextNode}
  5536. */
  5537. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5538. /**
  5539. * TSL function for defining a uniformFlow context value for a given node.
  5540. *
  5541. * @tsl
  5542. * @function
  5543. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5544. * @returns {ContextNode}
  5545. */
  5546. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5547. /**
  5548. * TSL function for defining a name for the context value for a given node.
  5549. *
  5550. * @tsl
  5551. * @function
  5552. * @param {Node} node - The node whose context should be modified.
  5553. * @param {string} name - The name to set.
  5554. * @returns {ContextNode}
  5555. */
  5556. const setName = ( node, name ) => context( node, { nodeName: name } );
  5557. /**
  5558. * TSL function for defining a label context value for a given node.
  5559. *
  5560. * @tsl
  5561. * @function
  5562. * @deprecated
  5563. * @param {Node} node - The node whose context should be modified.
  5564. * @param {string} name - The name/label to set.
  5565. * @returns {ContextNode}
  5566. */
  5567. function label( node, name ) {
  5568. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5569. return setName( node, name );
  5570. }
  5571. addMethodChaining( 'context', context );
  5572. addMethodChaining( 'label', label );
  5573. addMethodChaining( 'uniformFlow', uniformFlow );
  5574. addMethodChaining( 'setName', setName );
  5575. /**
  5576. * Class for representing shader variables as nodes. Variables are created from
  5577. * existing nodes like the following:
  5578. *
  5579. * ```js
  5580. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5581. * ```
  5582. *
  5583. * @augments Node
  5584. */
  5585. class VarNode extends Node {
  5586. static get type() {
  5587. return 'VarNode';
  5588. }
  5589. /**
  5590. * Constructs a new variable node.
  5591. *
  5592. * @param {Node} node - The node for which a variable should be created.
  5593. * @param {?string} [name=null] - The name of the variable in the shader.
  5594. * @param {boolean} [readOnly=false] - The read-only flag.
  5595. */
  5596. constructor( node, name = null, readOnly = false ) {
  5597. super();
  5598. /**
  5599. * The node for which a variable should be created.
  5600. *
  5601. * @type {Node}
  5602. */
  5603. this.node = node;
  5604. /**
  5605. * The name of the variable in the shader. If no name is defined,
  5606. * the node system auto-generates one.
  5607. *
  5608. * @type {?string}
  5609. * @default null
  5610. */
  5611. this.name = name;
  5612. /**
  5613. * `VarNode` sets this property to `true` by default.
  5614. *
  5615. * @type {boolean}
  5616. * @default true
  5617. */
  5618. this.global = true;
  5619. /**
  5620. * This flag can be used for type testing.
  5621. *
  5622. * @type {boolean}
  5623. * @readonly
  5624. * @default true
  5625. */
  5626. this.isVarNode = true;
  5627. /**
  5628. *
  5629. * The read-only flag.
  5630. *
  5631. * @type {boolean}
  5632. * @default false
  5633. */
  5634. this.readOnly = readOnly;
  5635. /**
  5636. *
  5637. * Add this flag to the node system to indicate that this node require parents.
  5638. *
  5639. * @type {boolean}
  5640. * @default true
  5641. */
  5642. this.parents = true;
  5643. /**
  5644. * This flag is used to indicate that this node is used for intent.
  5645. *
  5646. * @type {boolean}
  5647. * @default false
  5648. */
  5649. this.intent = false;
  5650. }
  5651. /**
  5652. * Sets the intent flag for this node.
  5653. *
  5654. * This flag is used to indicate that this node is used for intent
  5655. * and should not be built directly. Instead, it is used to indicate that
  5656. * the node should be treated as a variable intent.
  5657. *
  5658. * It's useful for assigning variables without needing creating a new variable node.
  5659. *
  5660. * @param {boolean} value - The value to set for the intent flag.
  5661. * @returns {VarNode} This node.
  5662. */
  5663. setIntent( value ) {
  5664. this.intent = value;
  5665. return this;
  5666. }
  5667. /**
  5668. * Returns the intent flag of this node.
  5669. *
  5670. * @return {boolean} The intent flag.
  5671. */
  5672. getIntent() {
  5673. return this.intent;
  5674. }
  5675. getMemberType( builder, name ) {
  5676. return this.node.getMemberType( builder, name );
  5677. }
  5678. getElementType( builder ) {
  5679. return this.node.getElementType( builder );
  5680. }
  5681. getNodeType( builder ) {
  5682. return this.node.getNodeType( builder );
  5683. }
  5684. getArrayCount( builder ) {
  5685. return this.node.getArrayCount( builder );
  5686. }
  5687. isAssign( builder ) {
  5688. const properties = builder.getNodeProperties( this );
  5689. let assign = properties.assign;
  5690. if ( assign !== true ) {
  5691. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5692. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5693. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5694. if ( shaderNodeData.hasLoop ) {
  5695. assign = true;
  5696. }
  5697. }
  5698. }
  5699. }
  5700. return assign;
  5701. }
  5702. build( ...params ) {
  5703. if ( this.intent === true ) {
  5704. const builder = params[ 0 ];
  5705. if ( this.isAssign( builder ) !== true ) {
  5706. return this.node.build( ...params );
  5707. }
  5708. }
  5709. return super.build( ...params );
  5710. }
  5711. generate( builder ) {
  5712. const { node, name, readOnly } = this;
  5713. const { renderer } = builder;
  5714. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5715. let isDeterministic = false;
  5716. let shouldTreatAsReadOnly = false;
  5717. if ( readOnly ) {
  5718. isDeterministic = builder.isDeterministic( node );
  5719. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5720. }
  5721. const nodeType = this.getNodeType( builder );
  5722. if ( nodeType == 'void' ) {
  5723. if ( this.intent !== true ) {
  5724. error( 'TSL: ".toVar()" can not be used with void type.' );
  5725. }
  5726. const snippet = node.build( builder );
  5727. return snippet;
  5728. }
  5729. const vectorType = builder.getVectorType( nodeType );
  5730. const snippet = node.build( builder, vectorType );
  5731. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5732. const propertyName = builder.getPropertyName( nodeVar );
  5733. let declarationPrefix = propertyName;
  5734. if ( shouldTreatAsReadOnly ) {
  5735. if ( isWebGPUBackend ) {
  5736. declarationPrefix = isDeterministic
  5737. ? `const ${ propertyName }`
  5738. : `let ${ propertyName }`;
  5739. } else {
  5740. const count = node.getArrayCount( builder );
  5741. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5742. }
  5743. }
  5744. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5745. return propertyName;
  5746. }
  5747. }
  5748. /**
  5749. * TSL function for creating a var node.
  5750. *
  5751. * @tsl
  5752. * @function
  5753. * @param {Node} node - The node for which a variable should be created.
  5754. * @param {?string} name - The name of the variable in the shader.
  5755. * @returns {VarNode}
  5756. */
  5757. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5758. /**
  5759. * TSL function for creating a var node.
  5760. *
  5761. * @tsl
  5762. * @function
  5763. * @param {Node} node - The node for which a variable should be created.
  5764. * @param {?string} name - The name of the variable in the shader.
  5765. * @returns {VarNode}
  5766. */
  5767. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5768. /**
  5769. * TSL function for creating a const node.
  5770. *
  5771. * @tsl
  5772. * @function
  5773. * @param {Node} node - The node for which a constant should be created.
  5774. * @param {?string} name - The name of the constant in the shader.
  5775. * @returns {VarNode}
  5776. */
  5777. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5778. //
  5779. //
  5780. /**
  5781. * TSL function for creating a var intent node.
  5782. *
  5783. * @tsl
  5784. * @function
  5785. * @param {Node} node - The node for which a variable should be created.
  5786. * @param {?string} name - The name of the variable in the shader.
  5787. * @returns {VarNode}
  5788. */
  5789. const VarIntent = ( node ) => {
  5790. if ( getCurrentStack() === null ) {
  5791. return node;
  5792. }
  5793. return createVar( node ).setIntent( true ).toStack();
  5794. };
  5795. // Method chaining
  5796. addMethodChaining( 'toVar', Var );
  5797. addMethodChaining( 'toConst', Const );
  5798. addMethodChaining( 'toVarIntent', VarIntent );
  5799. /**
  5800. * This node is used to build a sub-build in the node system.
  5801. *
  5802. * @augments Node
  5803. * @param {Node} node - The node to be built in the sub-build.
  5804. * @param {string} name - The name of the sub-build.
  5805. * @param {?string} [nodeType=null] - The type of the node, if known.
  5806. */
  5807. class SubBuildNode extends Node {
  5808. static get type() {
  5809. return 'SubBuild';
  5810. }
  5811. constructor( node, name, nodeType = null ) {
  5812. super( nodeType );
  5813. /**
  5814. * The node to be built in the sub-build.
  5815. *
  5816. * @type {Node}
  5817. */
  5818. this.node = node;
  5819. /**
  5820. * The name of the sub-build.
  5821. *
  5822. * @type {string}
  5823. */
  5824. this.name = name;
  5825. /**
  5826. * This flag can be used for type testing.
  5827. *
  5828. * @type {boolean}
  5829. * @readonly
  5830. * @default true
  5831. */
  5832. this.isSubBuildNode = true;
  5833. }
  5834. getNodeType( builder ) {
  5835. if ( this.nodeType !== null ) return this.nodeType;
  5836. builder.addSubBuild( this.name );
  5837. const nodeType = this.node.getNodeType( builder );
  5838. builder.removeSubBuild();
  5839. return nodeType;
  5840. }
  5841. build( builder, ...params ) {
  5842. builder.addSubBuild( this.name );
  5843. const data = this.node.build( builder, ...params );
  5844. builder.removeSubBuild();
  5845. return data;
  5846. }
  5847. }
  5848. /**
  5849. * Creates a new sub-build node.
  5850. *
  5851. * @tsl
  5852. * @function
  5853. * @param {Node} node - The node to be built in the sub-build.
  5854. * @param {string} name - The name of the sub-build.
  5855. * @param {?string} [type=null] - The type of the node, if known.
  5856. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5857. */
  5858. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5859. /**
  5860. * Class for representing shader varyings as nodes. Varyings are create from
  5861. * existing nodes like the following:
  5862. *
  5863. * ```js
  5864. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5865. * ```
  5866. *
  5867. * @augments Node
  5868. */
  5869. class VaryingNode extends Node {
  5870. static get type() {
  5871. return 'VaryingNode';
  5872. }
  5873. /**
  5874. * Constructs a new varying node.
  5875. *
  5876. * @param {Node} node - The node for which a varying should be created.
  5877. * @param {?string} name - The name of the varying in the shader.
  5878. */
  5879. constructor( node, name = null ) {
  5880. super();
  5881. /**
  5882. * The node for which a varying should be created.
  5883. *
  5884. * @type {Node}
  5885. */
  5886. this.node = node;
  5887. /**
  5888. * The name of the varying in the shader. If no name is defined,
  5889. * the node system auto-generates one.
  5890. *
  5891. * @type {?string}
  5892. * @default null
  5893. */
  5894. this.name = name;
  5895. /**
  5896. * This flag can be used for type testing.
  5897. *
  5898. * @type {boolean}
  5899. * @readonly
  5900. * @default true
  5901. */
  5902. this.isVaryingNode = true;
  5903. /**
  5904. * The interpolation type of the varying data.
  5905. *
  5906. * @type {?string}
  5907. * @default null
  5908. */
  5909. this.interpolationType = null;
  5910. /**
  5911. * The interpolation sampling type of varying data.
  5912. *
  5913. * @type {?string}
  5914. * @default null
  5915. */
  5916. this.interpolationSampling = null;
  5917. /**
  5918. * This flag is used for global cache.
  5919. *
  5920. * @type {boolean}
  5921. * @default true
  5922. */
  5923. this.global = true;
  5924. }
  5925. /**
  5926. * Defines the interpolation type of the varying.
  5927. *
  5928. * @param {string} type - The interpolation type.
  5929. * @param {?string} sampling - The interpolation sampling type
  5930. * @return {VaryingNode} A reference to this node.
  5931. */
  5932. setInterpolation( type, sampling = null ) {
  5933. this.interpolationType = type;
  5934. this.interpolationSampling = sampling;
  5935. return this;
  5936. }
  5937. getHash( builder ) {
  5938. return this.name || super.getHash( builder );
  5939. }
  5940. getNodeType( builder ) {
  5941. // VaryingNode is auto type
  5942. return this.node.getNodeType( builder );
  5943. }
  5944. /**
  5945. * This method performs the setup of a varying node with the current node builder.
  5946. *
  5947. * @param {NodeBuilder} builder - The current node builder.
  5948. * @return {NodeVarying} The node varying from the node builder.
  5949. */
  5950. setupVarying( builder ) {
  5951. const properties = builder.getNodeProperties( this );
  5952. let varying = properties.varying;
  5953. if ( varying === undefined ) {
  5954. const name = this.name;
  5955. const type = this.getNodeType( builder );
  5956. const interpolationType = this.interpolationType;
  5957. const interpolationSampling = this.interpolationSampling;
  5958. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5959. properties.node = subBuild( this.node, 'VERTEX' );
  5960. }
  5961. // this property can be used to check if the varying can be optimized for a variable
  5962. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5963. return varying;
  5964. }
  5965. setup( builder ) {
  5966. this.setupVarying( builder );
  5967. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5968. }
  5969. analyze( builder ) {
  5970. this.setupVarying( builder );
  5971. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5972. }
  5973. generate( builder ) {
  5974. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5975. const properties = builder.getNodeProperties( this );
  5976. const varying = this.setupVarying( builder );
  5977. if ( properties[ propertyKey ] === undefined ) {
  5978. const type = this.getNodeType( builder );
  5979. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5980. // force node run in vertex stage
  5981. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5982. properties[ propertyKey ] = propertyName;
  5983. }
  5984. return builder.getPropertyName( varying );
  5985. }
  5986. }
  5987. /**
  5988. * TSL function for creating a varying node.
  5989. *
  5990. * @tsl
  5991. * @function
  5992. * @param {Node} node - The node for which a varying should be created.
  5993. * @param {?string} name - The name of the varying in the shader.
  5994. * @returns {VaryingNode}
  5995. */
  5996. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5997. /**
  5998. * Computes a node in the vertex stage.
  5999. *
  6000. * @tsl
  6001. * @function
  6002. * @param {Node} node - The node which should be executed in the vertex stage.
  6003. * @returns {VaryingNode}
  6004. */
  6005. const vertexStage = ( node ) => varying( node );
  6006. addMethodChaining( 'toVarying', varying );
  6007. addMethodChaining( 'toVertexStage', vertexStage );
  6008. // Deprecated
  6009. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6010. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6011. return varying( ...params );
  6012. } );
  6013. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6014. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6015. return varying( ...params );
  6016. } );
  6017. /**
  6018. * Converts the given color value from sRGB to linear-sRGB color space.
  6019. *
  6020. * @tsl
  6021. * @function
  6022. * @param {Node<vec3>} color - The sRGB color.
  6023. * @return {Node<vec3>} The linear-sRGB color.
  6024. */
  6025. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6026. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6027. const b = color.mul( 0.0773993808 );
  6028. const factor = color.lessThanEqual( 0.04045 );
  6029. const rgbResult = mix( a, b, factor );
  6030. return rgbResult;
  6031. } ).setLayout( {
  6032. name: 'sRGBTransferEOTF',
  6033. type: 'vec3',
  6034. inputs: [
  6035. { name: 'color', type: 'vec3' }
  6036. ]
  6037. } );
  6038. /**
  6039. * Converts the given color value from linear-sRGB to sRGB color space.
  6040. *
  6041. * @tsl
  6042. * @function
  6043. * @param {Node<vec3>} color - The linear-sRGB color.
  6044. * @return {Node<vec3>} The sRGB color.
  6045. */
  6046. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6047. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6048. const b = color.mul( 12.92 );
  6049. const factor = color.lessThanEqual( 0.0031308 );
  6050. const rgbResult = mix( a, b, factor );
  6051. return rgbResult;
  6052. } ).setLayout( {
  6053. name: 'sRGBTransferOETF',
  6054. type: 'vec3',
  6055. inputs: [
  6056. { name: 'color', type: 'vec3' }
  6057. ]
  6058. } );
  6059. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6060. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6061. /**
  6062. * This node represents a color space conversion. Meaning it converts
  6063. * a color value from a source to a target color space.
  6064. *
  6065. * @augments TempNode
  6066. */
  6067. class ColorSpaceNode extends TempNode {
  6068. static get type() {
  6069. return 'ColorSpaceNode';
  6070. }
  6071. /**
  6072. * Constructs a new color space node.
  6073. *
  6074. * @param {Node} colorNode - Represents the color to convert.
  6075. * @param {string} source - The source color space.
  6076. * @param {string} target - The target color space.
  6077. */
  6078. constructor( colorNode, source, target ) {
  6079. super( 'vec4' );
  6080. /**
  6081. * Represents the color to convert.
  6082. *
  6083. * @type {Node}
  6084. */
  6085. this.colorNode = colorNode;
  6086. /**
  6087. * The source color space.
  6088. *
  6089. * @type {string}
  6090. */
  6091. this.source = source;
  6092. /**
  6093. * The target color space.
  6094. *
  6095. * @type {string}
  6096. */
  6097. this.target = target;
  6098. }
  6099. /**
  6100. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6101. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6102. * color management and renderer.
  6103. *
  6104. * @param {NodeBuilder} builder - The current node builder.
  6105. * @param {string} colorSpace - The color space to resolve.
  6106. * @return {string} The resolved color space.
  6107. */
  6108. resolveColorSpace( builder, colorSpace ) {
  6109. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6110. return ColorManagement.workingColorSpace;
  6111. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6112. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6113. }
  6114. return colorSpace;
  6115. }
  6116. setup( builder ) {
  6117. const { colorNode } = this;
  6118. const source = this.resolveColorSpace( builder, this.source );
  6119. const target = this.resolveColorSpace( builder, this.target );
  6120. let outputNode = colorNode;
  6121. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6122. return outputNode;
  6123. }
  6124. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6125. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6126. }
  6127. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6128. outputNode = vec4(
  6129. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6130. outputNode.a
  6131. );
  6132. }
  6133. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6134. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6135. }
  6136. return outputNode;
  6137. }
  6138. }
  6139. /**
  6140. * TSL function for converting a given color node from the current working color space to the given color space.
  6141. *
  6142. * @tsl
  6143. * @function
  6144. * @param {Node} node - Represents the node to convert.
  6145. * @param {string} targetColorSpace - The target color space.
  6146. * @returns {ColorSpaceNode}
  6147. */
  6148. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6149. /**
  6150. * TSL function for converting a given color node from the given color space to the current working color space.
  6151. *
  6152. * @tsl
  6153. * @function
  6154. * @param {Node} node - Represents the node to convert.
  6155. * @param {string} sourceColorSpace - The source color space.
  6156. * @returns {ColorSpaceNode}
  6157. */
  6158. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6159. /**
  6160. * TSL function for converting a given color node from one color space to another one.
  6161. *
  6162. * @tsl
  6163. * @function
  6164. * @param {Node} node - Represents the node to convert.
  6165. * @param {string} sourceColorSpace - The source color space.
  6166. * @param {string} targetColorSpace - The target color space.
  6167. * @returns {ColorSpaceNode}
  6168. */
  6169. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6170. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6171. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6172. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6173. /**
  6174. * This class is only relevant if the referenced property is array-like.
  6175. * In this case, `ReferenceElementNode` allows to refer to a specific
  6176. * element inside the data structure via an index.
  6177. *
  6178. * @augments ArrayElementNode
  6179. */
  6180. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6181. static get type() {
  6182. return 'ReferenceElementNode';
  6183. }
  6184. /**
  6185. * Constructs a new reference element node.
  6186. *
  6187. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6188. * @param {Node} indexNode - The index node that defines the element access.
  6189. */
  6190. constructor( referenceNode, indexNode ) {
  6191. super( referenceNode, indexNode );
  6192. /**
  6193. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6194. * property references to the current node.
  6195. *
  6196. * @type {?ReferenceBaseNode}
  6197. * @default null
  6198. */
  6199. this.referenceNode = referenceNode;
  6200. /**
  6201. * This flag can be used for type testing.
  6202. *
  6203. * @type {boolean}
  6204. * @readonly
  6205. * @default true
  6206. */
  6207. this.isReferenceElementNode = true;
  6208. }
  6209. /**
  6210. * This method is overwritten since the node type is inferred from
  6211. * the uniform type of the reference node.
  6212. *
  6213. * @return {string} The node type.
  6214. */
  6215. getNodeType() {
  6216. return this.referenceNode.uniformType;
  6217. }
  6218. generate( builder ) {
  6219. const snippet = super.generate( builder );
  6220. const arrayType = this.referenceNode.getNodeType();
  6221. const elementType = this.getNodeType();
  6222. return builder.format( snippet, arrayType, elementType );
  6223. }
  6224. };
  6225. /**
  6226. * Base class for nodes which establishes a reference to a property of another object.
  6227. * In this way, the value of the node is automatically linked to the value of
  6228. * referenced object. Reference nodes internally represent the linked value
  6229. * as a uniform.
  6230. *
  6231. * @augments Node
  6232. */
  6233. class ReferenceBaseNode extends Node {
  6234. static get type() {
  6235. return 'ReferenceBaseNode';
  6236. }
  6237. /**
  6238. * Constructs a new reference base node.
  6239. *
  6240. * @param {string} property - The name of the property the node refers to.
  6241. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6242. * @param {?Object} [object=null] - The object the property belongs to.
  6243. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6244. */
  6245. constructor( property, uniformType, object = null, count = null ) {
  6246. super();
  6247. /**
  6248. * The name of the property the node refers to.
  6249. *
  6250. * @type {string}
  6251. */
  6252. this.property = property;
  6253. /**
  6254. * The uniform type that should be used to represent the property value.
  6255. *
  6256. * @type {string}
  6257. */
  6258. this.uniformType = uniformType;
  6259. /**
  6260. * The object the property belongs to.
  6261. *
  6262. * @type {?Object}
  6263. * @default null
  6264. */
  6265. this.object = object;
  6266. /**
  6267. * When the linked property is an array, this parameter defines its length.
  6268. *
  6269. * @type {?number}
  6270. * @default null
  6271. */
  6272. this.count = count;
  6273. /**
  6274. * The property name might have dots so nested properties can be referred.
  6275. * The hierarchy of the names is stored inside this array.
  6276. *
  6277. * @type {Array<string>}
  6278. */
  6279. this.properties = property.split( '.' );
  6280. /**
  6281. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6282. * since the final reference might be updated from calling code.
  6283. *
  6284. * @type {?Object}
  6285. * @default null
  6286. */
  6287. this.reference = object;
  6288. /**
  6289. * The uniform node that holds the value of the reference node.
  6290. *
  6291. * @type {UniformNode}
  6292. * @default null
  6293. */
  6294. this.node = null;
  6295. /**
  6296. * The uniform group of the internal uniform.
  6297. *
  6298. * @type {UniformGroupNode}
  6299. * @default null
  6300. */
  6301. this.group = null;
  6302. /**
  6303. * Overwritten since reference nodes are updated per object.
  6304. *
  6305. * @type {string}
  6306. * @default 'object'
  6307. */
  6308. this.updateType = NodeUpdateType.OBJECT;
  6309. }
  6310. /**
  6311. * Sets the uniform group for this reference node.
  6312. *
  6313. * @param {UniformGroupNode} group - The uniform group to set.
  6314. * @return {ReferenceBaseNode} A reference to this node.
  6315. */
  6316. setGroup( group ) {
  6317. this.group = group;
  6318. return this;
  6319. }
  6320. /**
  6321. * When the referred property is array-like, this method can be used
  6322. * to access elements via an index node.
  6323. *
  6324. * @param {IndexNode} indexNode - indexNode.
  6325. * @return {ReferenceElementNode} A reference to an element.
  6326. */
  6327. element( indexNode ) {
  6328. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6329. }
  6330. /**
  6331. * Sets the node type which automatically defines the internal
  6332. * uniform type.
  6333. *
  6334. * @param {string} uniformType - The type to set.
  6335. */
  6336. setNodeType( uniformType ) {
  6337. const node = uniform( null, uniformType );
  6338. if ( this.group !== null ) {
  6339. node.setGroup( this.group );
  6340. }
  6341. this.node = node;
  6342. }
  6343. /**
  6344. * This method is overwritten since the node type is inferred from
  6345. * the type of the reference node.
  6346. *
  6347. * @param {NodeBuilder} builder - The current node builder.
  6348. * @return {string} The node type.
  6349. */
  6350. getNodeType( builder ) {
  6351. if ( this.node === null ) {
  6352. this.updateReference( builder );
  6353. this.updateValue();
  6354. }
  6355. return this.node.getNodeType( builder );
  6356. }
  6357. /**
  6358. * Returns the property value from the given referred object.
  6359. *
  6360. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6361. * @return {any} The value.
  6362. */
  6363. getValueFromReference( object = this.reference ) {
  6364. const { properties } = this;
  6365. let value = object[ properties[ 0 ] ];
  6366. for ( let i = 1; i < properties.length; i ++ ) {
  6367. value = value[ properties[ i ] ];
  6368. }
  6369. return value;
  6370. }
  6371. /**
  6372. * Allows to update the reference based on the given state. The state is only
  6373. * evaluated {@link ReferenceBaseNode#object} is not set.
  6374. *
  6375. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6376. * @return {Object} The updated reference.
  6377. */
  6378. updateReference( state ) {
  6379. this.reference = this.object !== null ? this.object : state.object;
  6380. return this.reference;
  6381. }
  6382. /**
  6383. * The output of the reference node is the internal uniform node.
  6384. *
  6385. * @return {UniformNode} The output node.
  6386. */
  6387. setup() {
  6388. this.updateValue();
  6389. return this.node;
  6390. }
  6391. /**
  6392. * Overwritten to update the internal uniform value.
  6393. *
  6394. * @param {NodeFrame} frame - A reference to the current node frame.
  6395. */
  6396. update( /*frame*/ ) {
  6397. this.updateValue();
  6398. }
  6399. /**
  6400. * Retrieves the value from the referred object property and uses it
  6401. * to updated the internal uniform.
  6402. */
  6403. updateValue() {
  6404. if ( this.node === null ) this.setNodeType( this.uniformType );
  6405. const value = this.getValueFromReference();
  6406. if ( Array.isArray( value ) ) {
  6407. this.node.array = value;
  6408. } else {
  6409. this.node.value = value;
  6410. }
  6411. }
  6412. }
  6413. /**
  6414. * TSL function for creating a reference base node.
  6415. *
  6416. * @tsl
  6417. * @function
  6418. * @param {string} name - The name of the property the node refers to.
  6419. * @param {string} type - The uniform type that should be used to represent the property value.
  6420. * @param {Object} object - The object the property belongs to.
  6421. * @returns {ReferenceBaseNode}
  6422. */
  6423. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6424. /**
  6425. * This node is a special type of reference node which is intended
  6426. * for linking renderer properties with node values.
  6427. * ```js
  6428. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6429. * ```
  6430. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6431. * automatically be updated.
  6432. *
  6433. * @augments ReferenceBaseNode
  6434. */
  6435. class RendererReferenceNode extends ReferenceBaseNode {
  6436. static get type() {
  6437. return 'RendererReferenceNode';
  6438. }
  6439. /**
  6440. * Constructs a new renderer reference node.
  6441. *
  6442. * @param {string} property - The name of the property the node refers to.
  6443. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6444. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6445. * the node refers to the renderer of the current state.
  6446. */
  6447. constructor( property, inputType, renderer = null ) {
  6448. super( property, inputType, renderer );
  6449. /**
  6450. * The renderer the property belongs to. When no renderer is set,
  6451. * the node refers to the renderer of the current state.
  6452. *
  6453. * @type {?Renderer}
  6454. * @default null
  6455. */
  6456. this.renderer = renderer;
  6457. this.setGroup( renderGroup );
  6458. }
  6459. /**
  6460. * Updates the reference based on the given state. The state is only evaluated
  6461. * {@link RendererReferenceNode#renderer} is not set.
  6462. *
  6463. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6464. * @return {Object} The updated reference.
  6465. */
  6466. updateReference( state ) {
  6467. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6468. return this.reference;
  6469. }
  6470. }
  6471. /**
  6472. * TSL function for creating a renderer reference node.
  6473. *
  6474. * @tsl
  6475. * @function
  6476. * @param {string} name - The name of the property the node refers to.
  6477. * @param {string} type - The uniform type that should be used to represent the property value.
  6478. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6479. * the node refers to the renderer of the current state.
  6480. * @returns {RendererReferenceNode}
  6481. */
  6482. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6483. /**
  6484. * This node represents a tone mapping operation.
  6485. *
  6486. * @augments TempNode
  6487. */
  6488. class ToneMappingNode extends TempNode {
  6489. static get type() {
  6490. return 'ToneMappingNode';
  6491. }
  6492. /**
  6493. * Constructs a new tone mapping node.
  6494. *
  6495. * @param {number} toneMapping - The tone mapping type.
  6496. * @param {Node} exposureNode - The tone mapping exposure.
  6497. * @param {Node} [colorNode=null] - The color node to process.
  6498. */
  6499. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6500. super( 'vec3' );
  6501. /**
  6502. * The tone mapping type.
  6503. *
  6504. * @type {number}
  6505. */
  6506. this.toneMapping = toneMapping;
  6507. /**
  6508. * The tone mapping exposure.
  6509. *
  6510. * @type {Node}
  6511. * @default null
  6512. */
  6513. this.exposureNode = exposureNode;
  6514. /**
  6515. * Represents the color to process.
  6516. *
  6517. * @type {?Node}
  6518. * @default null
  6519. */
  6520. this.colorNode = colorNode;
  6521. }
  6522. /**
  6523. * Overwrites the default `customCacheKey()` implementation by including the tone
  6524. * mapping type into the cache key.
  6525. *
  6526. * @return {number} The hash.
  6527. */
  6528. customCacheKey() {
  6529. return hash$1( this.toneMapping );
  6530. }
  6531. setup( builder ) {
  6532. const colorNode = this.colorNode || builder.context.color;
  6533. const toneMapping = this.toneMapping;
  6534. if ( toneMapping === NoToneMapping ) return colorNode;
  6535. let outputNode = null;
  6536. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6537. if ( toneMappingFn !== null ) {
  6538. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6539. } else {
  6540. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6541. outputNode = colorNode;
  6542. }
  6543. return outputNode;
  6544. }
  6545. }
  6546. /**
  6547. * TSL function for creating a tone mapping node.
  6548. *
  6549. * @tsl
  6550. * @function
  6551. * @param {number} mapping - The tone mapping type.
  6552. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6553. * @param {Node<vec3> | Color} color - The color node to process.
  6554. * @returns {ToneMappingNode<vec3>}
  6555. */
  6556. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6557. /**
  6558. * TSL object that represents the global tone mapping exposure of the renderer.
  6559. *
  6560. * @tsl
  6561. * @type {RendererReferenceNode<vec3>}
  6562. */
  6563. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6564. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6565. /**
  6566. * In earlier `three.js` versions it was only possible to define attribute data
  6567. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6568. * on the node level.
  6569. * ```js
  6570. * const geometry = new THREE.PlaneGeometry();
  6571. * const positionAttribute = geometry.getAttribute( 'position' );
  6572. *
  6573. * const colors = [];
  6574. * for ( let i = 0; i < position.count; i ++ ) {
  6575. * colors.push( 1, 0, 0 );
  6576. * }
  6577. *
  6578. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6579. * ```
  6580. * This new approach is especially interesting when geometry data are generated via
  6581. * compute shaders. The below line converts a storage buffer into an attribute node.
  6582. * ```js
  6583. * material.positionNode = positionBuffer.toAttribute();
  6584. * ```
  6585. * @augments InputNode
  6586. */
  6587. class BufferAttributeNode extends InputNode {
  6588. static get type() {
  6589. return 'BufferAttributeNode';
  6590. }
  6591. /**
  6592. * Constructs a new buffer attribute node.
  6593. *
  6594. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6595. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6596. * @param {number} [bufferStride=0] - The buffer stride.
  6597. * @param {number} [bufferOffset=0] - The buffer offset.
  6598. */
  6599. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6600. super( value, bufferType );
  6601. /**
  6602. * This flag can be used for type testing.
  6603. *
  6604. * @type {boolean}
  6605. * @readonly
  6606. * @default true
  6607. */
  6608. this.isBufferNode = true;
  6609. /**
  6610. * The buffer type (e.g. `'vec3'`).
  6611. *
  6612. * @type {?string}
  6613. * @default null
  6614. */
  6615. this.bufferType = bufferType;
  6616. /**
  6617. * The buffer stride.
  6618. *
  6619. * @type {number}
  6620. * @default 0
  6621. */
  6622. this.bufferStride = bufferStride;
  6623. /**
  6624. * The buffer offset.
  6625. *
  6626. * @type {number}
  6627. * @default 0
  6628. */
  6629. this.bufferOffset = bufferOffset;
  6630. /**
  6631. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6632. * if you are planning to update the attribute data per frame.
  6633. *
  6634. * @type {number}
  6635. * @default StaticDrawUsage
  6636. */
  6637. this.usage = StaticDrawUsage;
  6638. /**
  6639. * Whether the attribute is instanced or not.
  6640. *
  6641. * @type {boolean}
  6642. * @default false
  6643. */
  6644. this.instanced = false;
  6645. /**
  6646. * A reference to the buffer attribute.
  6647. *
  6648. * @type {?BufferAttribute}
  6649. * @default null
  6650. */
  6651. this.attribute = null;
  6652. /**
  6653. * `BufferAttributeNode` sets this property to `true` by default.
  6654. *
  6655. * @type {boolean}
  6656. * @default true
  6657. */
  6658. this.global = true;
  6659. if ( value && value.isBufferAttribute === true ) {
  6660. this.attribute = value;
  6661. this.usage = value.usage;
  6662. this.instanced = value.isInstancedBufferAttribute;
  6663. }
  6664. }
  6665. /**
  6666. * This method is overwritten since the attribute data might be shared
  6667. * and thus the hash should be shared as well.
  6668. *
  6669. * @param {NodeBuilder} builder - The current node builder.
  6670. * @return {string} The hash.
  6671. */
  6672. getHash( builder ) {
  6673. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6674. let bufferData = builder.globalCache.getData( this.value );
  6675. if ( bufferData === undefined ) {
  6676. bufferData = {
  6677. node: this
  6678. };
  6679. builder.globalCache.setData( this.value, bufferData );
  6680. }
  6681. return bufferData.node.uuid;
  6682. }
  6683. return this.uuid;
  6684. }
  6685. /**
  6686. * This method is overwritten since the node type is inferred from
  6687. * the buffer attribute.
  6688. *
  6689. * @param {NodeBuilder} builder - The current node builder.
  6690. * @return {string} The node type.
  6691. */
  6692. getNodeType( builder ) {
  6693. if ( this.bufferType === null ) {
  6694. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6695. }
  6696. return this.bufferType;
  6697. }
  6698. /**
  6699. * Depending on which value was passed to the node, `setup()` behaves
  6700. * differently. If no instance of `BufferAttribute` was passed, the method
  6701. * creates an internal attribute and configures it respectively.
  6702. *
  6703. * @param {NodeBuilder} builder - The current node builder.
  6704. */
  6705. setup( builder ) {
  6706. if ( this.attribute !== null ) return;
  6707. const type = this.getNodeType( builder );
  6708. const array = this.value;
  6709. const itemSize = builder.getTypeLength( type );
  6710. const stride = this.bufferStride || itemSize;
  6711. const offset = this.bufferOffset;
  6712. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6713. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6714. buffer.setUsage( this.usage );
  6715. this.attribute = bufferAttribute;
  6716. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6717. }
  6718. /**
  6719. * Generates the code snippet of the buffer attribute node.
  6720. *
  6721. * @param {NodeBuilder} builder - The current node builder.
  6722. * @return {string} The generated code snippet.
  6723. */
  6724. generate( builder ) {
  6725. const nodeType = this.getNodeType( builder );
  6726. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6727. const propertyName = builder.getPropertyName( nodeAttribute );
  6728. let output = null;
  6729. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6730. this.name = propertyName;
  6731. output = propertyName;
  6732. } else {
  6733. const nodeVarying = varying( this );
  6734. output = nodeVarying.build( builder, nodeType );
  6735. }
  6736. return output;
  6737. }
  6738. /**
  6739. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6740. *
  6741. * @param {NodeBuilder} builder - The current node builder.
  6742. * @return {string} The input type.
  6743. */
  6744. getInputType( /*builder*/ ) {
  6745. return 'bufferAttribute';
  6746. }
  6747. /**
  6748. * Sets the `usage` property to the given value.
  6749. *
  6750. * @param {number} value - The usage to set.
  6751. * @return {BufferAttributeNode} A reference to this node.
  6752. */
  6753. setUsage( value ) {
  6754. this.usage = value;
  6755. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6756. this.attribute.usage = value;
  6757. }
  6758. return this;
  6759. }
  6760. /**
  6761. * Sets the `instanced` property to the given value.
  6762. *
  6763. * @param {boolean} value - The value to set.
  6764. * @return {BufferAttributeNode} A reference to this node.
  6765. */
  6766. setInstanced( value ) {
  6767. this.instanced = value;
  6768. return this;
  6769. }
  6770. }
  6771. /**
  6772. * TSL function for creating a buffer attribute node.
  6773. *
  6774. * @tsl
  6775. * @function
  6776. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6777. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6778. * @param {number} [stride=0] - The buffer stride.
  6779. * @param {number} [offset=0] - The buffer offset.
  6780. * @returns {BufferAttributeNode}
  6781. */
  6782. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6783. /**
  6784. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6785. * Use this function if attribute data are updated per frame.
  6786. *
  6787. * @tsl
  6788. * @function
  6789. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6790. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6791. * @param {number} [stride=0] - The buffer stride.
  6792. * @param {number} [offset=0] - The buffer offset.
  6793. * @returns {BufferAttributeNode}
  6794. */
  6795. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6796. /**
  6797. * TSL function for creating a buffer attribute node but with enabled instancing
  6798. *
  6799. * @tsl
  6800. * @function
  6801. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6802. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6803. * @param {number} [stride=0] - The buffer stride.
  6804. * @param {number} [offset=0] - The buffer offset.
  6805. * @returns {BufferAttributeNode}
  6806. */
  6807. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6808. /**
  6809. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6810. *
  6811. * @tsl
  6812. * @function
  6813. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6814. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6815. * @param {number} [stride=0] - The buffer stride.
  6816. * @param {number} [offset=0] - The buffer offset.
  6817. * @returns {BufferAttributeNode}
  6818. */
  6819. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6820. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6821. /**
  6822. * TODO
  6823. *
  6824. * @augments Node
  6825. */
  6826. class ComputeNode extends Node {
  6827. static get type() {
  6828. return 'ComputeNode';
  6829. }
  6830. /**
  6831. * Constructs a new compute node.
  6832. *
  6833. * @param {Node} computeNode - TODO
  6834. * @param {Array<number>} workgroupSize - TODO.
  6835. */
  6836. constructor( computeNode, workgroupSize ) {
  6837. super( 'void' );
  6838. /**
  6839. * This flag can be used for type testing.
  6840. *
  6841. * @type {boolean}
  6842. * @readonly
  6843. * @default true
  6844. */
  6845. this.isComputeNode = true;
  6846. /**
  6847. * TODO
  6848. *
  6849. * @type {Node}
  6850. */
  6851. this.computeNode = computeNode;
  6852. /**
  6853. * TODO
  6854. *
  6855. * @type {Array<number>}
  6856. * @default [ 64 ]
  6857. */
  6858. this.workgroupSize = workgroupSize;
  6859. /**
  6860. * TODO
  6861. *
  6862. * @type {number}
  6863. */
  6864. this.count = null;
  6865. /**
  6866. * TODO
  6867. *
  6868. * @type {number}
  6869. */
  6870. this.version = 1;
  6871. /**
  6872. * The name or label of the uniform.
  6873. *
  6874. * @type {string}
  6875. * @default ''
  6876. */
  6877. this.name = '';
  6878. /**
  6879. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6880. * is executed once per object by default.
  6881. *
  6882. * @type {string}
  6883. * @default 'object'
  6884. */
  6885. this.updateBeforeType = NodeUpdateType.OBJECT;
  6886. /**
  6887. * TODO
  6888. *
  6889. * @type {?Function}
  6890. */
  6891. this.onInitFunction = null;
  6892. }
  6893. setCount( count ) {
  6894. this.count = count;
  6895. return this;
  6896. }
  6897. getCount() {
  6898. return this.count;
  6899. }
  6900. /**
  6901. * Executes the `dispose` event for this node.
  6902. */
  6903. dispose() {
  6904. this.dispatchEvent( { type: 'dispose' } );
  6905. }
  6906. /**
  6907. * Sets the {@link ComputeNode#name} property.
  6908. *
  6909. * @param {string} name - The name of the uniform.
  6910. * @return {ComputeNode} A reference to this node.
  6911. */
  6912. setName( name ) {
  6913. this.name = name;
  6914. return this;
  6915. }
  6916. /**
  6917. * Sets the {@link ComputeNode#name} property.
  6918. *
  6919. * @deprecated
  6920. * @param {string} name - The name of the uniform.
  6921. * @return {ComputeNode} A reference to this node.
  6922. */
  6923. label( name ) {
  6924. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6925. return this.setName( name );
  6926. }
  6927. /**
  6928. * TODO
  6929. *
  6930. * @param {Function} callback - TODO.
  6931. * @return {ComputeNode} A reference to this node.
  6932. */
  6933. onInit( callback ) {
  6934. this.onInitFunction = callback;
  6935. return this;
  6936. }
  6937. /**
  6938. * The method execute the compute for this node.
  6939. *
  6940. * @param {NodeFrame} frame - A reference to the current node frame.
  6941. */
  6942. updateBefore( { renderer } ) {
  6943. renderer.compute( this );
  6944. }
  6945. setup( builder ) {
  6946. const result = this.computeNode.build( builder );
  6947. if ( result ) {
  6948. const properties = builder.getNodeProperties( this );
  6949. properties.outputComputeNode = result.outputNode;
  6950. result.outputNode = null;
  6951. }
  6952. return result;
  6953. }
  6954. generate( builder, output ) {
  6955. const { shaderStage } = builder;
  6956. if ( shaderStage === 'compute' ) {
  6957. const snippet = this.computeNode.build( builder, 'void' );
  6958. if ( snippet !== '' ) {
  6959. builder.addLineFlowCode( snippet, this );
  6960. }
  6961. } else {
  6962. const properties = builder.getNodeProperties( this );
  6963. const outputComputeNode = properties.outputComputeNode;
  6964. if ( outputComputeNode ) {
  6965. return outputComputeNode.build( builder, output );
  6966. }
  6967. }
  6968. }
  6969. }
  6970. /**
  6971. * TSL function for creating a compute kernel node.
  6972. *
  6973. * @tsl
  6974. * @function
  6975. * @param {Node} node - TODO
  6976. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6977. * @returns {AtomicFunctionNode}
  6978. */
  6979. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6980. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6981. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6982. }
  6983. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6984. const val = workgroupSize[ i ];
  6985. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6986. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6987. }
  6988. }
  6989. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6990. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6991. //
  6992. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6993. };
  6994. /**
  6995. * TSL function for creating a compute node.
  6996. *
  6997. * @tsl
  6998. * @function
  6999. * @param {Node} node - TODO
  7000. * @param {number} count - TODO.
  7001. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7002. * @returns {AtomicFunctionNode}
  7003. */
  7004. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7005. addMethodChaining( 'compute', compute );
  7006. addMethodChaining( 'computeKernel', computeKernel );
  7007. /**
  7008. * This node can be used as a cache management component for another node.
  7009. * Caching is in general used by default in {@link NodeBuilder} but this node
  7010. * allows the usage of a shared parent cache during the build process.
  7011. *
  7012. * @augments Node
  7013. */
  7014. class IsolateNode extends Node {
  7015. static get type() {
  7016. return 'IsolateNode';
  7017. }
  7018. /**
  7019. * Constructs a new cache node.
  7020. *
  7021. * @param {Node} node - The node that should be cached.
  7022. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7023. */
  7024. constructor( node, parent = true ) {
  7025. super();
  7026. /**
  7027. * The node that should be cached.
  7028. *
  7029. * @type {Node}
  7030. */
  7031. this.node = node;
  7032. /**
  7033. * Whether this node refers to a shared parent cache or not.
  7034. *
  7035. * @type {boolean}
  7036. * @default true
  7037. */
  7038. this.parent = parent;
  7039. /**
  7040. * This flag can be used for type testing.
  7041. *
  7042. * @type {boolean}
  7043. * @readonly
  7044. * @default true
  7045. */
  7046. this.isIsolateNode = true;
  7047. }
  7048. getNodeType( builder ) {
  7049. const previousCache = builder.getCache();
  7050. const cache = builder.getCacheFromNode( this, this.parent );
  7051. builder.setCache( cache );
  7052. const nodeType = this.node.getNodeType( builder );
  7053. builder.setCache( previousCache );
  7054. return nodeType;
  7055. }
  7056. build( builder, ...params ) {
  7057. const previousCache = builder.getCache();
  7058. const cache = builder.getCacheFromNode( this, this.parent );
  7059. builder.setCache( cache );
  7060. const data = this.node.build( builder, ...params );
  7061. builder.setCache( previousCache );
  7062. return data;
  7063. }
  7064. setParent( parent ) {
  7065. this.parent = parent;
  7066. return this;
  7067. }
  7068. getParent() {
  7069. return this.parent;
  7070. }
  7071. }
  7072. /**
  7073. * TSL function for creating a cache node.
  7074. *
  7075. * @tsl
  7076. * @function
  7077. * @param {Node} node - The node that should be cached.
  7078. * @returns {IsolateNode}
  7079. */
  7080. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7081. /**
  7082. * TSL function for creating a cache node.
  7083. *
  7084. * @tsl
  7085. * @function
  7086. * @deprecated
  7087. * @param {Node} node - The node that should be cached.
  7088. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7089. * @returns {IsolateNode}
  7090. */
  7091. function cache( node, parent = true ) {
  7092. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7093. return isolate( node ).setParent( parent );
  7094. }
  7095. addMethodChaining( 'cache', cache );
  7096. addMethodChaining( 'isolate', isolate );
  7097. /**
  7098. * The class generates the code of a given node but returns another node in the output.
  7099. * This can be used to call a method or node that does not return a value, i.e.
  7100. * type `void` on an input where returning a value is required. Example:
  7101. *
  7102. * ```js
  7103. * material.colorNode = myColor.bypass( runVoidFn() )
  7104. *```
  7105. *
  7106. * @augments Node
  7107. */
  7108. class BypassNode extends Node {
  7109. static get type() {
  7110. return 'BypassNode';
  7111. }
  7112. /**
  7113. * Constructs a new bypass node.
  7114. *
  7115. * @param {Node} outputNode - The output node.
  7116. * @param {Node} callNode - The call node.
  7117. */
  7118. constructor( outputNode, callNode ) {
  7119. super();
  7120. /**
  7121. * This flag can be used for type testing.
  7122. *
  7123. * @type {boolean}
  7124. * @readonly
  7125. * @default true
  7126. */
  7127. this.isBypassNode = true;
  7128. /**
  7129. * The output node.
  7130. *
  7131. * @type {Node}
  7132. */
  7133. this.outputNode = outputNode;
  7134. /**
  7135. * The call node.
  7136. *
  7137. * @type {Node}
  7138. */
  7139. this.callNode = callNode;
  7140. }
  7141. getNodeType( builder ) {
  7142. return this.outputNode.getNodeType( builder );
  7143. }
  7144. generate( builder ) {
  7145. const snippet = this.callNode.build( builder, 'void' );
  7146. if ( snippet !== '' ) {
  7147. builder.addLineFlowCode( snippet, this );
  7148. }
  7149. return this.outputNode.build( builder );
  7150. }
  7151. }
  7152. /**
  7153. * TSL function for creating a bypass node.
  7154. *
  7155. * @tsl
  7156. * @function
  7157. * @param {Node} outputNode - The output node.
  7158. * @param {Node} callNode - The call node.
  7159. * @returns {BypassNode}
  7160. */
  7161. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7162. addMethodChaining( 'bypass', bypass );
  7163. /**
  7164. * This node allows to remap a node value from one range into another. E.g a value of
  7165. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7166. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7167. *
  7168. * @augments Node
  7169. */
  7170. class RemapNode extends Node {
  7171. static get type() {
  7172. return 'RemapNode';
  7173. }
  7174. /**
  7175. * Constructs a new remap node.
  7176. *
  7177. * @param {Node} node - The node that should be remapped.
  7178. * @param {Node} inLowNode - The source or current lower bound of the range.
  7179. * @param {Node} inHighNode - The source or current upper bound of the range.
  7180. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7181. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7182. */
  7183. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7184. super();
  7185. /**
  7186. * The node that should be remapped.
  7187. *
  7188. * @type {Node}
  7189. */
  7190. this.node = node;
  7191. /**
  7192. * The source or current lower bound of the range.
  7193. *
  7194. * @type {Node}
  7195. */
  7196. this.inLowNode = inLowNode;
  7197. /**
  7198. * The source or current upper bound of the range.
  7199. *
  7200. * @type {Node}
  7201. */
  7202. this.inHighNode = inHighNode;
  7203. /**
  7204. * The target lower bound of the range.
  7205. *
  7206. * @type {Node}
  7207. * @default float(0)
  7208. */
  7209. this.outLowNode = outLowNode;
  7210. /**
  7211. * The target upper bound of the range.
  7212. *
  7213. * @type {Node}
  7214. * @default float(1)
  7215. */
  7216. this.outHighNode = outHighNode;
  7217. /**
  7218. * Whether the node value should be clamped before
  7219. * remapping it to the target range.
  7220. *
  7221. * @type {boolean}
  7222. * @default true
  7223. */
  7224. this.doClamp = true;
  7225. }
  7226. setup() {
  7227. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7228. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7229. if ( doClamp === true ) t = t.clamp();
  7230. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7231. }
  7232. }
  7233. /**
  7234. * TSL function for creating a remap node.
  7235. *
  7236. * @tsl
  7237. * @function
  7238. * @param {Node} node - The node that should be remapped.
  7239. * @param {Node} inLowNode - The source or current lower bound of the range.
  7240. * @param {Node} inHighNode - The source or current upper bound of the range.
  7241. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7242. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7243. * @returns {RemapNode}
  7244. */
  7245. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7246. /**
  7247. * TSL function for creating a remap node, but with enabled clamping.
  7248. *
  7249. * @tsl
  7250. * @function
  7251. * @param {Node} node - The node that should be remapped.
  7252. * @param {Node} inLowNode - The source or current lower bound of the range.
  7253. * @param {Node} inHighNode - The source or current upper bound of the range.
  7254. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7255. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7256. * @returns {RemapNode}
  7257. */
  7258. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7259. addMethodChaining( 'remap', remap );
  7260. addMethodChaining( 'remapClamp', remapClamp );
  7261. /**
  7262. * This class can be used to implement basic expressions in shader code.
  7263. * Basic examples for that are `return`, `continue` or `discard` statements.
  7264. *
  7265. * @augments Node
  7266. */
  7267. class ExpressionNode extends Node {
  7268. static get type() {
  7269. return 'ExpressionNode';
  7270. }
  7271. /**
  7272. * Constructs a new expression node.
  7273. *
  7274. * @param {string} [snippet=''] - The native code snippet.
  7275. * @param {string} [nodeType='void'] - The node type.
  7276. */
  7277. constructor( snippet = '', nodeType = 'void' ) {
  7278. super( nodeType );
  7279. /**
  7280. * The native code snippet.
  7281. *
  7282. * @type {string}
  7283. * @default ''
  7284. */
  7285. this.snippet = snippet;
  7286. }
  7287. generate( builder, output ) {
  7288. const type = this.getNodeType( builder );
  7289. const snippet = this.snippet;
  7290. if ( type === 'void' ) {
  7291. builder.addLineFlowCode( snippet, this );
  7292. } else {
  7293. return builder.format( snippet, type, output );
  7294. }
  7295. }
  7296. }
  7297. /**
  7298. * TSL function for creating an expression node.
  7299. *
  7300. * @tsl
  7301. * @function
  7302. * @param {string} [snippet] - The native code snippet.
  7303. * @param {?string} [nodeType='void'] - The node type.
  7304. * @returns {ExpressionNode}
  7305. */
  7306. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7307. /**
  7308. * Represents a `discard` shader operation in TSL.
  7309. *
  7310. * @tsl
  7311. * @function
  7312. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7313. * @return {Node} The `discard` expression.
  7314. */
  7315. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7316. /**
  7317. * Represents a `return` shader operation in TSL.
  7318. *
  7319. * @tsl
  7320. * @function
  7321. * @return {ExpressionNode} The `return` expression.
  7322. */
  7323. const Return = () => expression( 'return' ).toStack();
  7324. addMethodChaining( 'discard', Discard );
  7325. /**
  7326. * Normally, tone mapping and color conversion happens automatically
  7327. * before outputting pixel too the default (screen) framebuffer. In certain
  7328. * post processing setups this happens to late because certain effects
  7329. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7330. * to apply tone mapping and color space conversion at an arbitrary point
  7331. * in the effect chain.
  7332. *
  7333. * When applying tone mapping and color space conversion manually with this node,
  7334. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7335. *
  7336. * ```js
  7337. * const postProcessing = new PostProcessing( renderer );
  7338. * postProcessing.outputColorTransform = false;
  7339. *
  7340. * const scenePass = pass( scene, camera );
  7341. * const outputPass = renderOutput( scenePass );
  7342. *
  7343. * postProcessing.outputNode = outputPass;
  7344. * ```
  7345. *
  7346. * @augments TempNode
  7347. */
  7348. class RenderOutputNode extends TempNode {
  7349. static get type() {
  7350. return 'RenderOutputNode';
  7351. }
  7352. /**
  7353. * Constructs a new render output node.
  7354. *
  7355. * @param {Node} colorNode - The color node to process.
  7356. * @param {?number} toneMapping - The tone mapping type.
  7357. * @param {?string} outputColorSpace - The output color space.
  7358. */
  7359. constructor( colorNode, toneMapping, outputColorSpace ) {
  7360. super( 'vec4' );
  7361. /**
  7362. * The color node to process.
  7363. *
  7364. * @type {Node}
  7365. */
  7366. this.colorNode = colorNode;
  7367. /**
  7368. * The tone mapping type.
  7369. *
  7370. * @type {?number}
  7371. */
  7372. this.toneMapping = toneMapping;
  7373. /**
  7374. * The output color space.
  7375. *
  7376. * @type {?string}
  7377. */
  7378. this.outputColorSpace = outputColorSpace;
  7379. /**
  7380. * This flag can be used for type testing.
  7381. *
  7382. * @type {boolean}
  7383. * @readonly
  7384. * @default true
  7385. */
  7386. this.isRenderOutputNode = true;
  7387. }
  7388. setup( { context } ) {
  7389. let outputNode = this.colorNode || context.color;
  7390. // tone mapping
  7391. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7392. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7393. if ( toneMapping !== NoToneMapping ) {
  7394. outputNode = outputNode.toneMapping( toneMapping );
  7395. }
  7396. // working to output color space
  7397. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7398. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7399. }
  7400. return outputNode;
  7401. }
  7402. }
  7403. /**
  7404. * TSL function for creating a posterize node.
  7405. *
  7406. * @tsl
  7407. * @function
  7408. * @param {Node} color - The color node to process.
  7409. * @param {?number} [toneMapping=null] - The tone mapping type.
  7410. * @param {?string} [outputColorSpace=null] - The output color space.
  7411. * @returns {RenderOutputNode}
  7412. */
  7413. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7414. addMethodChaining( 'renderOutput', renderOutput );
  7415. class DebugNode extends TempNode {
  7416. static get type() {
  7417. return 'DebugNode';
  7418. }
  7419. constructor( node, callback = null ) {
  7420. super();
  7421. this.node = node;
  7422. this.callback = callback;
  7423. }
  7424. getNodeType( builder ) {
  7425. return this.node.getNodeType( builder );
  7426. }
  7427. setup( builder ) {
  7428. return this.node.build( builder );
  7429. }
  7430. analyze( builder ) {
  7431. return this.node.build( builder );
  7432. }
  7433. generate( builder ) {
  7434. const callback = this.callback;
  7435. const snippet = this.node.build( builder );
  7436. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7437. const border = '-'.repeat( title.length );
  7438. let code = '';
  7439. code += '// #' + title + '#\n';
  7440. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7441. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7442. code += '// #' + border + '#\n';
  7443. if ( callback !== null ) {
  7444. callback( builder, code );
  7445. } else {
  7446. log$1( code );
  7447. }
  7448. return snippet;
  7449. }
  7450. }
  7451. /**
  7452. * TSL function for creating a debug node.
  7453. *
  7454. * @tsl
  7455. * @function
  7456. * @param {Node} node - The node to debug.
  7457. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7458. * @returns {DebugNode}
  7459. */
  7460. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7461. addMethodChaining( 'debug', debug );
  7462. /**
  7463. * InspectorBase is the base class for all inspectors.
  7464. *
  7465. * @class InspectorBase
  7466. */
  7467. class InspectorBase {
  7468. /**
  7469. * Creates a new InspectorBase.
  7470. */
  7471. constructor() {
  7472. /**
  7473. * The renderer associated with this inspector.
  7474. *
  7475. * @type {WebGLRenderer}
  7476. * @private
  7477. */
  7478. this._renderer = null;
  7479. /**
  7480. * The current frame being processed.
  7481. *
  7482. * @type {Object}
  7483. */
  7484. this.currentFrame = null;
  7485. }
  7486. /**
  7487. * Returns the node frame for the current renderer.
  7488. *
  7489. * @return {Object} The node frame.
  7490. */
  7491. get nodeFrame() {
  7492. return this._renderer._nodes.nodeFrame;
  7493. }
  7494. /**
  7495. * Sets the renderer for this inspector.
  7496. *
  7497. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7498. * @return {InspectorBase} This inspector instance.
  7499. */
  7500. setRenderer( renderer ) {
  7501. this._renderer = renderer;
  7502. return this;
  7503. }
  7504. /**
  7505. * Returns the renderer associated with this inspector.
  7506. *
  7507. * @return {WebGLRenderer} The associated renderer.
  7508. */
  7509. getRenderer() {
  7510. return this._renderer;
  7511. }
  7512. /**
  7513. * Initializes the inspector.
  7514. */
  7515. init() { }
  7516. /**
  7517. * Called when a frame begins.
  7518. */
  7519. begin() { }
  7520. /**
  7521. * Called when a frame ends.
  7522. */
  7523. finish() { }
  7524. /**
  7525. * Inspects a node.
  7526. *
  7527. * @param {Node} node - The node to inspect.
  7528. */
  7529. inspect( /*node*/ ) { }
  7530. /**
  7531. * When a compute operation is performed.
  7532. *
  7533. * @param {ComputeNode} computeNode - The compute node being executed.
  7534. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7535. */
  7536. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7537. /**
  7538. * Called when a compute operation begins.
  7539. *
  7540. * @param {string} uid - A unique identifier for the render context.
  7541. * @param {ComputeNode} computeNode - The compute node being executed.
  7542. */
  7543. beginCompute( /*uid, computeNode*/ ) { }
  7544. /**
  7545. * Called when a compute operation ends.
  7546. *
  7547. * @param {string} uid - A unique identifier for the render context.
  7548. * @param {ComputeNode} computeNode - The compute node being executed.
  7549. */
  7550. finishCompute( /*uid*/ ) { }
  7551. /**
  7552. * Called when a render operation begins.
  7553. *
  7554. * @param {string} uid - A unique identifier for the render context.
  7555. * @param {Scene} scene - The scene being rendered.
  7556. * @param {Camera} camera - The camera being used for rendering.
  7557. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7558. */
  7559. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7560. /**
  7561. * Called when an animation loop ends.
  7562. *
  7563. * @param {string} uid - A unique identifier for the render context.
  7564. */
  7565. finishRender( /*uid*/ ) { }
  7566. /**
  7567. * Called when a texture copy operation is performed.
  7568. *
  7569. * @param {Texture} srcTexture - The source texture.
  7570. * @param {Texture} dstTexture - The destination texture.
  7571. */
  7572. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7573. /**
  7574. * Called when a framebuffer copy operation is performed.
  7575. *
  7576. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7577. */
  7578. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7579. }
  7580. /**
  7581. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7582. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7583. *
  7584. * @augments Node
  7585. */
  7586. class InspectorNode extends Node {
  7587. /**
  7588. * Returns the type of the node.
  7589. *
  7590. * @returns {string}
  7591. */
  7592. static get type() {
  7593. return 'InspectorNode';
  7594. }
  7595. /**
  7596. * Creates an InspectorNode.
  7597. *
  7598. * @param {Node} node - The node to inspect.
  7599. * @param {string} [name=''] - Optional name for the inspector node.
  7600. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7601. */
  7602. constructor( node, name = '', callback = null ) {
  7603. super();
  7604. this.node = node;
  7605. this.name = name;
  7606. this.callback = callback;
  7607. this.updateType = NodeUpdateType.FRAME;
  7608. this.isInspectorNode = true;
  7609. }
  7610. /**
  7611. * Returns the name of the inspector node.
  7612. *
  7613. * @returns {string}
  7614. */
  7615. getName() {
  7616. return this.name || this.node.name;
  7617. }
  7618. /**
  7619. * Updates the inspector node, allowing inspection of the wrapped node.
  7620. *
  7621. * @param {NodeFrame} frame - A reference to the current node frame.
  7622. */
  7623. update( frame ) {
  7624. frame.renderer.inspector.inspect( this );
  7625. }
  7626. /**
  7627. * Returns the type of the wrapped node.
  7628. *
  7629. * @param {NodeBuilder} builder - The node builder.
  7630. * @returns {string}
  7631. */
  7632. getNodeType( builder ) {
  7633. return this.node.getNodeType( builder );
  7634. }
  7635. /**
  7636. * Sets up the inspector node.
  7637. *
  7638. * @param {NodeBuilder} builder - The node builder.
  7639. * @returns {Node} The setup node.
  7640. */
  7641. setup( builder ) {
  7642. let node = this.node;
  7643. if ( builder.context.inspector === true && this.callback !== null ) {
  7644. node = this.callback( node );
  7645. }
  7646. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7647. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7648. }
  7649. return node;
  7650. }
  7651. }
  7652. /**
  7653. * Creates an inspector node to wrap around a given node for inspection purposes.
  7654. *
  7655. * @tsl
  7656. * @param {Node} node - The node to inspect.
  7657. * @param {string} [name=''] - Optional name for the inspector node.
  7658. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7659. * @returns {Node} The inspector node.
  7660. */
  7661. function inspector( node, name = '', callback = null ) {
  7662. node = nodeObject( node );
  7663. return node.before( new InspectorNode( node, name, callback ) );
  7664. }
  7665. addMethodChaining( 'toInspector', inspector );
  7666. function addNodeElement( name/*, nodeElement*/ ) {
  7667. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7668. }
  7669. /**
  7670. * Base class for representing shader attributes as nodes.
  7671. *
  7672. * @augments Node
  7673. */
  7674. class AttributeNode extends Node {
  7675. static get type() {
  7676. return 'AttributeNode';
  7677. }
  7678. /**
  7679. * Constructs a new attribute node.
  7680. *
  7681. * @param {string} attributeName - The name of the attribute.
  7682. * @param {?string} nodeType - The node type.
  7683. */
  7684. constructor( attributeName, nodeType = null ) {
  7685. super( nodeType );
  7686. /**
  7687. * `AttributeNode` sets this property to `true` by default.
  7688. *
  7689. * @type {boolean}
  7690. * @default true
  7691. */
  7692. this.global = true;
  7693. this._attributeName = attributeName;
  7694. }
  7695. getHash( builder ) {
  7696. return this.getAttributeName( builder );
  7697. }
  7698. getNodeType( builder ) {
  7699. let nodeType = this.nodeType;
  7700. if ( nodeType === null ) {
  7701. const attributeName = this.getAttributeName( builder );
  7702. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7703. const attribute = builder.geometry.getAttribute( attributeName );
  7704. nodeType = builder.getTypeFromAttribute( attribute );
  7705. } else {
  7706. nodeType = 'float';
  7707. }
  7708. }
  7709. return nodeType;
  7710. }
  7711. /**
  7712. * Sets the attribute name to the given value. The method can be
  7713. * overwritten in derived classes if the final name must be computed
  7714. * analytically.
  7715. *
  7716. * @param {string} attributeName - The name of the attribute.
  7717. * @return {AttributeNode} A reference to this node.
  7718. */
  7719. setAttributeName( attributeName ) {
  7720. this._attributeName = attributeName;
  7721. return this;
  7722. }
  7723. /**
  7724. * Returns the attribute name of this node. The method can be
  7725. * overwritten in derived classes if the final name must be computed
  7726. * analytically.
  7727. *
  7728. * @param {NodeBuilder} builder - The current node builder.
  7729. * @return {string} The attribute name.
  7730. */
  7731. getAttributeName( /*builder*/ ) {
  7732. return this._attributeName;
  7733. }
  7734. generate( builder ) {
  7735. const attributeName = this.getAttributeName( builder );
  7736. const nodeType = this.getNodeType( builder );
  7737. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7738. if ( geometryAttribute === true ) {
  7739. const attribute = builder.geometry.getAttribute( attributeName );
  7740. const attributeType = builder.getTypeFromAttribute( attribute );
  7741. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7742. if ( builder.shaderStage === 'vertex' ) {
  7743. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7744. } else {
  7745. const nodeVarying = varying( this );
  7746. return nodeVarying.build( builder, nodeType );
  7747. }
  7748. } else {
  7749. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7750. return builder.generateConst( nodeType );
  7751. }
  7752. }
  7753. serialize( data ) {
  7754. super.serialize( data );
  7755. data.global = this.global;
  7756. data._attributeName = this._attributeName;
  7757. }
  7758. deserialize( data ) {
  7759. super.deserialize( data );
  7760. this.global = data.global;
  7761. this._attributeName = data._attributeName;
  7762. }
  7763. }
  7764. /**
  7765. * TSL function for creating an attribute node.
  7766. *
  7767. * @tsl
  7768. * @function
  7769. * @param {string} name - The name of the attribute.
  7770. * @param {?string} [nodeType=null] - The node type.
  7771. * @returns {AttributeNode}
  7772. */
  7773. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7774. /**
  7775. * TSL function for creating an uv attribute node with the given index.
  7776. *
  7777. * @tsl
  7778. * @function
  7779. * @param {number} [index=0] - The uv index.
  7780. * @return {AttributeNode<vec2>} The uv attribute node.
  7781. */
  7782. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7783. /**
  7784. * A node that represents the dimensions of a texture. The texture size is
  7785. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7786. * or `textureSize()`.
  7787. *
  7788. * @augments Node
  7789. */
  7790. class TextureSizeNode extends Node {
  7791. static get type() {
  7792. return 'TextureSizeNode';
  7793. }
  7794. /**
  7795. * Constructs a new texture size node.
  7796. *
  7797. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7798. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7799. */
  7800. constructor( textureNode, levelNode = null ) {
  7801. super( 'uvec2' );
  7802. /**
  7803. * This flag can be used for type testing.
  7804. *
  7805. * @type {boolean}
  7806. * @readonly
  7807. * @default true
  7808. */
  7809. this.isTextureSizeNode = true;
  7810. /**
  7811. * A texture node which size should be retrieved.
  7812. *
  7813. * @type {TextureNode}
  7814. */
  7815. this.textureNode = textureNode;
  7816. /**
  7817. * A level node which defines the requested mip.
  7818. *
  7819. * @type {Node<int>}
  7820. * @default null
  7821. */
  7822. this.levelNode = levelNode;
  7823. }
  7824. generate( builder, output ) {
  7825. const textureProperty = this.textureNode.build( builder, 'property' );
  7826. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7827. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7828. }
  7829. }
  7830. /**
  7831. * TSL function for creating a texture size node.
  7832. *
  7833. * @tsl
  7834. * @function
  7835. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7836. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7837. * @returns {TextureSizeNode}
  7838. */
  7839. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7840. /**
  7841. * A special type of uniform node that computes the
  7842. * maximum mipmap level for a given texture node.
  7843. *
  7844. * ```js
  7845. * const level = maxMipLevel( textureNode );
  7846. * ```
  7847. *
  7848. * @augments UniformNode
  7849. */
  7850. class MaxMipLevelNode extends UniformNode {
  7851. static get type() {
  7852. return 'MaxMipLevelNode';
  7853. }
  7854. /**
  7855. * Constructs a new max mip level node.
  7856. *
  7857. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7858. */
  7859. constructor( textureNode ) {
  7860. super( 0 );
  7861. /**
  7862. * The texture node to compute the max mip level for.
  7863. *
  7864. * @private
  7865. * @type {TextureNode}
  7866. */
  7867. this._textureNode = textureNode;
  7868. /**
  7869. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7870. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7871. *
  7872. * @type {string}
  7873. * @default 'frame'
  7874. */
  7875. this.updateType = NodeUpdateType.FRAME;
  7876. }
  7877. /**
  7878. * The texture node to compute the max mip level for.
  7879. *
  7880. * @readonly
  7881. * @type {TextureNode}
  7882. */
  7883. get textureNode() {
  7884. return this._textureNode;
  7885. }
  7886. /**
  7887. * The texture.
  7888. *
  7889. * @readonly
  7890. * @type {Texture}
  7891. */
  7892. get texture() {
  7893. return this._textureNode.value;
  7894. }
  7895. update() {
  7896. const texture = this.texture;
  7897. const images = texture.images;
  7898. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7899. if ( image && image.width !== undefined ) {
  7900. const { width, height } = image;
  7901. this.value = Math.log2( Math.max( width, height ) );
  7902. }
  7903. }
  7904. }
  7905. /**
  7906. * TSL function for creating a max mip level node.
  7907. *
  7908. * @tsl
  7909. * @function
  7910. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7911. * @returns {MaxMipLevelNode}
  7912. */
  7913. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7914. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7915. /**
  7916. * This type of uniform node represents a 2D texture.
  7917. *
  7918. * @augments UniformNode
  7919. */
  7920. class TextureNode extends UniformNode {
  7921. static get type() {
  7922. return 'TextureNode';
  7923. }
  7924. /**
  7925. * Constructs a new texture node.
  7926. *
  7927. * @param {Texture} [value=EmptyTexture] - The texture.
  7928. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7929. * @param {?Node<int>} [levelNode=null] - The level node.
  7930. * @param {?Node<float>} [biasNode=null] - The bias node.
  7931. */
  7932. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7933. super( value );
  7934. /**
  7935. * This flag can be used for type testing.
  7936. *
  7937. * @type {boolean}
  7938. * @readonly
  7939. * @default true
  7940. */
  7941. this.isTextureNode = true;
  7942. /**
  7943. * Represents the texture coordinates.
  7944. *
  7945. * @type {?Node<vec2|vec3>}
  7946. * @default null
  7947. */
  7948. this.uvNode = uvNode;
  7949. /**
  7950. * Represents the mip level that should be selected.
  7951. *
  7952. * @type {?Node<int>}
  7953. * @default null
  7954. */
  7955. this.levelNode = levelNode;
  7956. /**
  7957. * Represents the bias to be applied during level-of-detail computation.
  7958. *
  7959. * @type {?Node<float>}
  7960. * @default null
  7961. */
  7962. this.biasNode = biasNode;
  7963. /**
  7964. * Represents a reference value a texture sample is compared to.
  7965. *
  7966. * @type {?Node<float>}
  7967. * @default null
  7968. */
  7969. this.compareNode = null;
  7970. /**
  7971. * When using texture arrays, the depth node defines the layer to select.
  7972. *
  7973. * @type {?Node<int>}
  7974. * @default null
  7975. */
  7976. this.depthNode = null;
  7977. /**
  7978. * When defined, a texture is sampled using explicit gradients.
  7979. *
  7980. * @type {?Array<Node<vec2>>}
  7981. * @default null
  7982. */
  7983. this.gradNode = null;
  7984. /**
  7985. * Represents the optional texel offset applied to the unnormalized texture
  7986. * coordinate before sampling the texture.
  7987. *
  7988. * @type {?Node<ivec2|ivec3>}
  7989. * @default null
  7990. */
  7991. this.offsetNode = null;
  7992. /**
  7993. * Whether texture values should be sampled or fetched.
  7994. *
  7995. * @type {boolean}
  7996. * @default true
  7997. */
  7998. this.sampler = true;
  7999. /**
  8000. * Whether the uv transformation matrix should be
  8001. * automatically updated or not. Use `setUpdateMatrix()`
  8002. * if you want to change the value of the property.
  8003. *
  8004. * @type {boolean}
  8005. * @default false
  8006. */
  8007. this.updateMatrix = false;
  8008. /**
  8009. * By default the `update()` method is not executed. Depending on
  8010. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8011. * is executed per object.
  8012. *
  8013. * @type {string}
  8014. * @default 'none'
  8015. */
  8016. this.updateType = NodeUpdateType.NONE;
  8017. /**
  8018. * The reference node.
  8019. *
  8020. * @type {?Node}
  8021. * @default null
  8022. */
  8023. this.referenceNode = null;
  8024. /**
  8025. * The texture value is stored in a private property.
  8026. *
  8027. * @private
  8028. * @type {Texture}
  8029. */
  8030. this._value = value;
  8031. /**
  8032. * The uniform node that represents the uv transformation matrix.
  8033. *
  8034. * @private
  8035. * @type {?UniformNode<mat3>}
  8036. * @default null
  8037. */
  8038. this._matrixUniform = null;
  8039. /**
  8040. * The uniform node that represents the y-flip. Only required for WebGL.
  8041. *
  8042. * @private
  8043. * @type {?UniformNode<bool>}
  8044. * @default null
  8045. */
  8046. this._flipYUniform = null;
  8047. this.setUpdateMatrix( uvNode === null );
  8048. }
  8049. set value( value ) {
  8050. if ( this.referenceNode ) {
  8051. this.referenceNode.value = value;
  8052. } else {
  8053. this._value = value;
  8054. }
  8055. }
  8056. /**
  8057. * The texture value.
  8058. *
  8059. * @type {Texture}
  8060. */
  8061. get value() {
  8062. return this.referenceNode ? this.referenceNode.value : this._value;
  8063. }
  8064. /**
  8065. * Overwritten since the uniform hash is defined by the texture's UUID.
  8066. *
  8067. * @param {NodeBuilder} builder - The current node builder.
  8068. * @return {string} The uniform hash.
  8069. */
  8070. getUniformHash( /*builder*/ ) {
  8071. return this.value.uuid;
  8072. }
  8073. /**
  8074. * Overwritten since the node type is inferred from the texture type.
  8075. *
  8076. * @param {NodeBuilder} builder - The current node builder.
  8077. * @return {string} The node type.
  8078. */
  8079. getNodeType( /*builder*/ ) {
  8080. if ( this.value.isDepthTexture === true ) return 'float';
  8081. if ( this.value.type === UnsignedIntType ) {
  8082. return 'uvec4';
  8083. } else if ( this.value.type === IntType ) {
  8084. return 'ivec4';
  8085. }
  8086. return 'vec4';
  8087. }
  8088. /**
  8089. * Overwrites the default implementation to return a fixed value `'texture'`.
  8090. *
  8091. * @param {NodeBuilder} builder - The current node builder.
  8092. * @return {string} The input type.
  8093. */
  8094. getInputType( /*builder*/ ) {
  8095. return 'texture';
  8096. }
  8097. /**
  8098. * Returns a default uvs based on the current texture's channel.
  8099. *
  8100. * @return {AttributeNode<vec2>} The default uvs.
  8101. */
  8102. getDefaultUV() {
  8103. return uv$1( this.value.channel );
  8104. }
  8105. /**
  8106. * Overwritten to always return the texture reference of the node.
  8107. *
  8108. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8109. * @return {Texture} The texture reference.
  8110. */
  8111. updateReference( /*state*/ ) {
  8112. return this.value;
  8113. }
  8114. /**
  8115. * Transforms the given uv node with the texture transformation matrix.
  8116. *
  8117. * @param {Node} uvNode - The uv node to transform.
  8118. * @return {Node} The transformed uv node.
  8119. */
  8120. getTransformedUV( uvNode ) {
  8121. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8122. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8123. }
  8124. /**
  8125. * Defines whether the uv transformation matrix should automatically be updated or not.
  8126. *
  8127. * @param {boolean} value - The update toggle.
  8128. * @return {TextureNode} A reference to this node.
  8129. */
  8130. setUpdateMatrix( value ) {
  8131. this.updateMatrix = value;
  8132. return this;
  8133. }
  8134. /**
  8135. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8136. * to modify the uv node for correct sampling.
  8137. *
  8138. * @param {NodeBuilder} builder - The current node builder.
  8139. * @param {Node} uvNode - The uv node to setup.
  8140. * @return {Node} The updated uv node.
  8141. */
  8142. setupUV( builder, uvNode ) {
  8143. if ( builder.isFlipY() ) {
  8144. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8145. uvNode = uvNode.toVar();
  8146. if ( this.sampler ) {
  8147. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8148. } else {
  8149. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8150. }
  8151. }
  8152. return uvNode;
  8153. }
  8154. /**
  8155. * Setups texture node by preparing the internal nodes for code generation.
  8156. *
  8157. * @param {NodeBuilder} builder - The current node builder.
  8158. */
  8159. setup( builder ) {
  8160. const properties = builder.getNodeProperties( this );
  8161. properties.referenceNode = this.referenceNode;
  8162. //
  8163. const texture = this.value;
  8164. if ( ! texture || texture.isTexture !== true ) {
  8165. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8166. }
  8167. //
  8168. const uvNode = Fn( () => {
  8169. let uvNode = this.uvNode;
  8170. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8171. uvNode = builder.context.getUV( this, builder );
  8172. }
  8173. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8174. if ( this.updateMatrix === true ) {
  8175. uvNode = this.getTransformedUV( uvNode );
  8176. }
  8177. uvNode = this.setupUV( builder, uvNode );
  8178. //
  8179. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8180. //
  8181. return uvNode;
  8182. } )();
  8183. //
  8184. let levelNode = this.levelNode;
  8185. if ( levelNode === null && builder.context.getTextureLevel ) {
  8186. levelNode = builder.context.getTextureLevel( this );
  8187. }
  8188. //
  8189. properties.uvNode = uvNode;
  8190. properties.levelNode = levelNode;
  8191. properties.biasNode = this.biasNode;
  8192. properties.compareNode = this.compareNode;
  8193. properties.gradNode = this.gradNode;
  8194. properties.depthNode = this.depthNode;
  8195. properties.offsetNode = this.offsetNode;
  8196. }
  8197. /**
  8198. * Generates the uv code snippet.
  8199. *
  8200. * @param {NodeBuilder} builder - The current node builder.
  8201. * @param {Node} uvNode - The uv node to generate code for.
  8202. * @return {string} The generated code snippet.
  8203. */
  8204. generateUV( builder, uvNode ) {
  8205. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8206. }
  8207. /**
  8208. * Generates the offset code snippet.
  8209. *
  8210. * @param {NodeBuilder} builder - The current node builder.
  8211. * @param {Node} offsetNode - The offset node to generate code for.
  8212. * @return {string} The generated code snippet.
  8213. */
  8214. generateOffset( builder, offsetNode ) {
  8215. return offsetNode.build( builder, 'ivec2' );
  8216. }
  8217. /**
  8218. * Generates the snippet for the texture sampling.
  8219. *
  8220. * @param {NodeBuilder} builder - The current node builder.
  8221. * @param {string} textureProperty - The texture property.
  8222. * @param {string} uvSnippet - The uv snippet.
  8223. * @param {?string} levelSnippet - The level snippet.
  8224. * @param {?string} biasSnippet - The bias snippet.
  8225. * @param {?string} depthSnippet - The depth snippet.
  8226. * @param {?string} compareSnippet - The compare snippet.
  8227. * @param {?Array<string>} gradSnippet - The grad snippet.
  8228. * @param {?string} offsetSnippet - The offset snippet.
  8229. * @return {string} The generated code snippet.
  8230. */
  8231. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8232. const texture = this.value;
  8233. let snippet;
  8234. if ( biasSnippet ) {
  8235. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8236. } else if ( gradSnippet ) {
  8237. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8238. } else if ( compareSnippet ) {
  8239. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8240. } else if ( this.sampler === false ) {
  8241. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8242. } else if ( levelSnippet ) {
  8243. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8244. } else {
  8245. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8246. }
  8247. return snippet;
  8248. }
  8249. /**
  8250. * Generates the code snippet of the texture node.
  8251. *
  8252. * @param {NodeBuilder} builder - The current node builder.
  8253. * @param {string} output - The current output.
  8254. * @return {string} The generated code snippet.
  8255. */
  8256. generate( builder, output ) {
  8257. const texture = this.value;
  8258. const properties = builder.getNodeProperties( this );
  8259. const textureProperty = super.generate( builder, 'property' );
  8260. if ( /^sampler/.test( output ) ) {
  8261. return textureProperty + '_sampler';
  8262. } else if ( builder.isReference( output ) ) {
  8263. return textureProperty;
  8264. } else {
  8265. const nodeData = builder.getDataFromNode( this );
  8266. let propertyName = nodeData.propertyName;
  8267. if ( propertyName === undefined ) {
  8268. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8269. const uvSnippet = this.generateUV( builder, uvNode );
  8270. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8271. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8272. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8273. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8274. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8275. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8276. const nodeVar = builder.getVarFromNode( this );
  8277. propertyName = builder.getPropertyName( nodeVar );
  8278. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8279. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8280. nodeData.snippet = snippet;
  8281. nodeData.propertyName = propertyName;
  8282. }
  8283. let snippet = propertyName;
  8284. const nodeType = this.getNodeType( builder );
  8285. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8286. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8287. }
  8288. return builder.format( snippet, nodeType, output );
  8289. }
  8290. }
  8291. /**
  8292. * Sets the sampler value.
  8293. *
  8294. * @param {boolean} value - The sampler value to set.
  8295. * @return {TextureNode} A reference to this texture node.
  8296. */
  8297. setSampler( value ) {
  8298. this.sampler = value;
  8299. return this;
  8300. }
  8301. /**
  8302. * Returns the sampler value.
  8303. *
  8304. * @return {boolean} The sampler value.
  8305. */
  8306. getSampler() {
  8307. return this.sampler;
  8308. }
  8309. // @TODO: Move to TSL
  8310. /**
  8311. * @function
  8312. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8313. *
  8314. * @param {Node} uvNode - The uv node.
  8315. * @return {TextureNode} A texture node representing the texture sample.
  8316. */
  8317. uv( uvNode ) { // @deprecated, r172
  8318. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8319. return this.sample( uvNode );
  8320. }
  8321. /**
  8322. * Samples the texture with the given uv node.
  8323. *
  8324. * @param {Node} uvNode - The uv node.
  8325. * @return {TextureNode} A texture node representing the texture sample.
  8326. */
  8327. sample( uvNode ) {
  8328. const textureNode = this.clone();
  8329. textureNode.uvNode = nodeObject( uvNode );
  8330. textureNode.referenceNode = this.getBase();
  8331. return nodeObject( textureNode );
  8332. }
  8333. /**
  8334. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8335. *
  8336. * @param {Node<uvec2>} uvNode - The uv node.
  8337. * @returns {TextureNode} A texture node representing the texture load.
  8338. */
  8339. load( uvNode ) {
  8340. return this.sample( uvNode ).setSampler( false );
  8341. }
  8342. /**
  8343. * Samples a blurred version of the texture by defining an internal bias.
  8344. *
  8345. * @param {Node<float>} amountNode - How blurred the texture should be.
  8346. * @return {TextureNode} A texture node representing the texture sample.
  8347. */
  8348. blur( amountNode ) {
  8349. const textureNode = this.clone();
  8350. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8351. textureNode.referenceNode = this.getBase();
  8352. const map = textureNode.value;
  8353. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8354. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8355. textureNode.biasNode = null;
  8356. }
  8357. return nodeObject( textureNode );
  8358. }
  8359. /**
  8360. * Samples a specific mip of the texture.
  8361. *
  8362. * @param {Node<int>} levelNode - The mip level to sample.
  8363. * @return {TextureNode} A texture node representing the texture sample.
  8364. */
  8365. level( levelNode ) {
  8366. const textureNode = this.clone();
  8367. textureNode.levelNode = nodeObject( levelNode );
  8368. textureNode.referenceNode = this.getBase();
  8369. return nodeObject( textureNode );
  8370. }
  8371. /**
  8372. * Returns the texture size of the requested level.
  8373. *
  8374. * @param {Node<int>} levelNode - The level to compute the size for.
  8375. * @return {TextureSizeNode} The texture size.
  8376. */
  8377. size( levelNode ) {
  8378. return textureSize( this, levelNode );
  8379. }
  8380. /**
  8381. * Samples the texture with the given bias.
  8382. *
  8383. * @param {Node<float>} biasNode - The bias node.
  8384. * @return {TextureNode} A texture node representing the texture sample.
  8385. */
  8386. bias( biasNode ) {
  8387. const textureNode = this.clone();
  8388. textureNode.biasNode = nodeObject( biasNode );
  8389. textureNode.referenceNode = this.getBase();
  8390. return nodeObject( textureNode );
  8391. }
  8392. /**
  8393. * Returns the base texture of this node.
  8394. * @return {TextureNode} The base texture node.
  8395. */
  8396. getBase() {
  8397. return this.referenceNode ? this.referenceNode.getBase() : this;
  8398. }
  8399. /**
  8400. * Samples the texture by executing a compare operation.
  8401. *
  8402. * @param {Node<float>} compareNode - The node that defines the compare value.
  8403. * @return {TextureNode} A texture node representing the texture sample.
  8404. */
  8405. compare( compareNode ) {
  8406. const textureNode = this.clone();
  8407. textureNode.compareNode = nodeObject( compareNode );
  8408. textureNode.referenceNode = this.getBase();
  8409. return nodeObject( textureNode );
  8410. }
  8411. /**
  8412. * Samples the texture using an explicit gradient.
  8413. *
  8414. * @param {Node<vec2>} gradNodeX - The gradX node.
  8415. * @param {Node<vec2>} gradNodeY - The gradY node.
  8416. * @return {TextureNode} A texture node representing the texture sample.
  8417. */
  8418. grad( gradNodeX, gradNodeY ) {
  8419. const textureNode = this.clone();
  8420. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8421. textureNode.referenceNode = this.getBase();
  8422. return nodeObject( textureNode );
  8423. }
  8424. /**
  8425. * Samples the texture by defining a depth node.
  8426. *
  8427. * @param {Node<int>} depthNode - The depth node.
  8428. * @return {TextureNode} A texture node representing the texture sample.
  8429. */
  8430. depth( depthNode ) {
  8431. const textureNode = this.clone();
  8432. textureNode.depthNode = nodeObject( depthNode );
  8433. textureNode.referenceNode = this.getBase();
  8434. return nodeObject( textureNode );
  8435. }
  8436. /**
  8437. * Samples the texture by defining an offset node.
  8438. *
  8439. * @param {Node<ivec2>} offsetNode - The offset node.
  8440. * @return {TextureNode} A texture node representing the texture sample.
  8441. */
  8442. offset( offsetNode ) {
  8443. const textureNode = this.clone();
  8444. textureNode.offsetNode = nodeObject( offsetNode );
  8445. textureNode.referenceNode = this.getBase();
  8446. return nodeObject( textureNode );
  8447. }
  8448. // --
  8449. serialize( data ) {
  8450. super.serialize( data );
  8451. data.value = this.value.toJSON( data.meta ).uuid;
  8452. data.sampler = this.sampler;
  8453. data.updateMatrix = this.updateMatrix;
  8454. data.updateType = this.updateType;
  8455. }
  8456. deserialize( data ) {
  8457. super.deserialize( data );
  8458. this.value = data.meta.textures[ data.value ];
  8459. this.sampler = data.sampler;
  8460. this.updateMatrix = data.updateMatrix;
  8461. this.updateType = data.updateType;
  8462. }
  8463. /**
  8464. * The update is used to implement the update of the uv transformation matrix.
  8465. */
  8466. update() {
  8467. const texture = this.value;
  8468. const matrixUniform = this._matrixUniform;
  8469. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8470. if ( texture.matrixAutoUpdate === true ) {
  8471. texture.updateMatrix();
  8472. }
  8473. //
  8474. const flipYUniform = this._flipYUniform;
  8475. if ( flipYUniform !== null ) {
  8476. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8477. }
  8478. }
  8479. /**
  8480. * Clones the texture node.
  8481. *
  8482. * @return {TextureNode} The cloned texture node.
  8483. */
  8484. clone() {
  8485. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8486. newNode.sampler = this.sampler;
  8487. newNode.depthNode = this.depthNode;
  8488. newNode.compareNode = this.compareNode;
  8489. newNode.gradNode = this.gradNode;
  8490. newNode.offsetNode = this.offsetNode;
  8491. return newNode;
  8492. }
  8493. }
  8494. /**
  8495. * TSL function for creating a texture node.
  8496. *
  8497. * @tsl
  8498. * @function
  8499. * @param {?Texture} value - The texture.
  8500. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8501. * @param {?Node<int>} [levelNode=null] - The level node.
  8502. * @param {?Node<float>} [biasNode=null] - The bias node.
  8503. * @returns {TextureNode}
  8504. */
  8505. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8506. /**
  8507. * TSL function for creating a texture node or sample a texture node already existing.
  8508. *
  8509. * @tsl
  8510. * @function
  8511. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8512. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8513. * @param {?Node<int>} [levelNode=null] - The level node.
  8514. * @param {?Node<float>} [biasNode=null] - The bias node.
  8515. * @returns {TextureNode}
  8516. */
  8517. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8518. let textureNode;
  8519. if ( value && value.isTextureNode === true ) {
  8520. textureNode = nodeObject( value.clone() );
  8521. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8522. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8523. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8524. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8525. } else {
  8526. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8527. }
  8528. return textureNode;
  8529. };
  8530. /**
  8531. * TSL function for creating a uniform texture node.
  8532. *
  8533. * @tsl
  8534. * @function
  8535. * @param {?Texture} value - The texture.
  8536. * @returns {TextureNode}
  8537. */
  8538. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8539. /**
  8540. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8541. *
  8542. * @tsl
  8543. * @function
  8544. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8545. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8546. * @param {?Node<int>} [levelNode=null] - The level node.
  8547. * @param {?Node<float>} [biasNode=null] - The bias node.
  8548. * @returns {TextureNode}
  8549. */
  8550. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8551. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8552. /**
  8553. * Converts a texture or texture node to a sampler.
  8554. *
  8555. * @tsl
  8556. * @function
  8557. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8558. * @returns {Node}
  8559. */
  8560. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8561. /**
  8562. * Converts a texture or texture node to a sampler comparison.
  8563. *
  8564. * @tsl
  8565. * @function
  8566. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8567. * @returns {Node}
  8568. */
  8569. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8570. /**
  8571. * A special type of uniform node which represents array-like data
  8572. * as uniform buffers. The access usually happens via `element()`
  8573. * which returns an instance of {@link ArrayElementNode}. For example:
  8574. *
  8575. * ```js
  8576. * const bufferNode = buffer( array, 'mat4', count );
  8577. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8578. * ```
  8579. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8580. * since it handles more input types and automatically cares about buffer paddings.
  8581. *
  8582. * @augments UniformNode
  8583. */
  8584. class BufferNode extends UniformNode {
  8585. static get type() {
  8586. return 'BufferNode';
  8587. }
  8588. /**
  8589. * Constructs a new buffer node.
  8590. *
  8591. * @param {Array<number>} value - Array-like buffer data.
  8592. * @param {string} bufferType - The data type of the buffer.
  8593. * @param {number} [bufferCount=0] - The count of buffer elements.
  8594. */
  8595. constructor( value, bufferType, bufferCount = 0 ) {
  8596. super( value, bufferType );
  8597. /**
  8598. * This flag can be used for type testing.
  8599. *
  8600. * @type {boolean}
  8601. * @readonly
  8602. * @default true
  8603. */
  8604. this.isBufferNode = true;
  8605. /**
  8606. * The data type of the buffer.
  8607. *
  8608. * @type {string}
  8609. */
  8610. this.bufferType = bufferType;
  8611. /**
  8612. * The uniform node that holds the value of the reference node.
  8613. *
  8614. * @type {number}
  8615. * @default 0
  8616. */
  8617. this.bufferCount = bufferCount;
  8618. }
  8619. /**
  8620. * The data type of the buffer elements.
  8621. *
  8622. * @param {NodeBuilder} builder - The current node builder.
  8623. * @return {string} The element type.
  8624. */
  8625. getElementType( builder ) {
  8626. return this.getNodeType( builder );
  8627. }
  8628. /**
  8629. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8630. *
  8631. * @param {NodeBuilder} builder - The current node builder.
  8632. * @return {string} The input type.
  8633. */
  8634. getInputType( /*builder*/ ) {
  8635. return 'buffer';
  8636. }
  8637. }
  8638. /**
  8639. * TSL function for creating a buffer node.
  8640. *
  8641. * @tsl
  8642. * @function
  8643. * @param {Array<number>} value - Array-like buffer data.
  8644. * @param {string} type - The data type of a buffer element.
  8645. * @param {number} count - The count of buffer elements.
  8646. * @returns {BufferNode}
  8647. */
  8648. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8649. /**
  8650. * Represents the element access on uniform array nodes.
  8651. *
  8652. * @augments ArrayElementNode
  8653. */
  8654. class UniformArrayElementNode extends ArrayElementNode {
  8655. static get type() {
  8656. return 'UniformArrayElementNode';
  8657. }
  8658. /**
  8659. * Constructs a new buffer node.
  8660. *
  8661. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8662. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8663. */
  8664. constructor( uniformArrayNode, indexNode ) {
  8665. super( uniformArrayNode, indexNode );
  8666. /**
  8667. * This flag can be used for type testing.
  8668. *
  8669. * @type {boolean}
  8670. * @readonly
  8671. * @default true
  8672. */
  8673. this.isArrayBufferElementNode = true;
  8674. }
  8675. generate( builder ) {
  8676. const snippet = super.generate( builder );
  8677. const type = this.getNodeType();
  8678. const paddedType = this.node.getPaddedType();
  8679. return builder.format( snippet, paddedType, type );
  8680. }
  8681. }
  8682. /**
  8683. * Similar to {@link BufferNode} this module represents array-like data as
  8684. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8685. * data types in the array (e.g `three.js` primitives) and automatically
  8686. * manage buffer padding. It should be the first choice when working with
  8687. * uniforms buffers.
  8688. * ```js
  8689. * const tintColors = uniformArray( [
  8690. * new Color( 1, 0, 0 ),
  8691. * new Color( 0, 1, 0 ),
  8692. * new Color( 0, 0, 1 )
  8693. * ], 'color' );
  8694. *
  8695. * const redColor = tintColors.element( 0 );
  8696. *
  8697. * @augments BufferNode
  8698. */
  8699. class UniformArrayNode extends BufferNode {
  8700. static get type() {
  8701. return 'UniformArrayNode';
  8702. }
  8703. /**
  8704. * Constructs a new uniform array node.
  8705. *
  8706. * @param {Array<any>} value - Array holding the buffer data.
  8707. * @param {?string} [elementType=null] - The data type of a buffer element.
  8708. */
  8709. constructor( value, elementType = null ) {
  8710. super( null );
  8711. /**
  8712. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8713. * hold number primitives as well as three.js objects like vectors, matrices
  8714. * or colors.
  8715. *
  8716. * @type {Array<any>}
  8717. */
  8718. this.array = value;
  8719. /**
  8720. * The data type of an array element.
  8721. *
  8722. * @type {string}
  8723. */
  8724. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8725. /**
  8726. * The padded type. Uniform buffers must conform to a certain buffer layout
  8727. * so a separate type is computed to ensure correct buffer size.
  8728. *
  8729. * @type {string}
  8730. */
  8731. this.paddedType = this.getPaddedType();
  8732. /**
  8733. * Overwritten since uniform array nodes are updated per render.
  8734. *
  8735. * @type {string}
  8736. * @default 'render'
  8737. */
  8738. this.updateType = NodeUpdateType.RENDER;
  8739. /**
  8740. * This flag can be used for type testing.
  8741. *
  8742. * @type {boolean}
  8743. * @readonly
  8744. * @default true
  8745. */
  8746. this.isArrayBufferNode = true;
  8747. }
  8748. /**
  8749. * This method is overwritten since the node type is inferred from the
  8750. * {@link UniformArrayNode#paddedType}.
  8751. *
  8752. * @param {NodeBuilder} builder - The current node builder.
  8753. * @return {string} The node type.
  8754. */
  8755. getNodeType( /*builder*/ ) {
  8756. return this.paddedType;
  8757. }
  8758. /**
  8759. * The data type of the array elements.
  8760. *
  8761. * @param {NodeBuilder} builder - The current node builder.
  8762. * @return {string} The element type.
  8763. */
  8764. getElementType() {
  8765. return this.elementType;
  8766. }
  8767. /**
  8768. * Returns the padded type based on the element type.
  8769. *
  8770. * @return {string} The padded type.
  8771. */
  8772. getPaddedType() {
  8773. const elementType = this.elementType;
  8774. let paddedType = 'vec4';
  8775. if ( elementType === 'mat2' ) {
  8776. paddedType = 'mat2';
  8777. } else if ( /mat/.test( elementType ) === true ) {
  8778. paddedType = 'mat4';
  8779. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8780. paddedType = 'ivec4';
  8781. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8782. paddedType = 'uvec4';
  8783. }
  8784. return paddedType;
  8785. }
  8786. /**
  8787. * The update makes sure to correctly transfer the data from the (complex) objects
  8788. * in the array to the internal, correctly padded value buffer.
  8789. *
  8790. * @param {NodeFrame} frame - A reference to the current node frame.
  8791. */
  8792. update( /*frame*/ ) {
  8793. const { array, value } = this;
  8794. const elementType = this.elementType;
  8795. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8796. for ( let i = 0; i < array.length; i ++ ) {
  8797. const index = i * 4;
  8798. value[ index ] = array[ i ];
  8799. }
  8800. } else if ( elementType === 'color' ) {
  8801. for ( let i = 0; i < array.length; i ++ ) {
  8802. const index = i * 4;
  8803. const vector = array[ i ];
  8804. value[ index ] = vector.r;
  8805. value[ index + 1 ] = vector.g;
  8806. value[ index + 2 ] = vector.b || 0;
  8807. //value[ index + 3 ] = vector.a || 0;
  8808. }
  8809. } else if ( elementType === 'mat2' ) {
  8810. for ( let i = 0; i < array.length; i ++ ) {
  8811. const index = i * 4;
  8812. const matrix = array[ i ];
  8813. value[ index ] = matrix.elements[ 0 ];
  8814. value[ index + 1 ] = matrix.elements[ 1 ];
  8815. value[ index + 2 ] = matrix.elements[ 2 ];
  8816. value[ index + 3 ] = matrix.elements[ 3 ];
  8817. }
  8818. } else if ( elementType === 'mat3' ) {
  8819. for ( let i = 0; i < array.length; i ++ ) {
  8820. const index = i * 16;
  8821. const matrix = array[ i ];
  8822. value[ index ] = matrix.elements[ 0 ];
  8823. value[ index + 1 ] = matrix.elements[ 1 ];
  8824. value[ index + 2 ] = matrix.elements[ 2 ];
  8825. value[ index + 4 ] = matrix.elements[ 3 ];
  8826. value[ index + 5 ] = matrix.elements[ 4 ];
  8827. value[ index + 6 ] = matrix.elements[ 5 ];
  8828. value[ index + 8 ] = matrix.elements[ 6 ];
  8829. value[ index + 9 ] = matrix.elements[ 7 ];
  8830. value[ index + 10 ] = matrix.elements[ 8 ];
  8831. value[ index + 15 ] = 1;
  8832. }
  8833. } else if ( elementType === 'mat4' ) {
  8834. for ( let i = 0; i < array.length; i ++ ) {
  8835. const index = i * 16;
  8836. const matrix = array[ i ];
  8837. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8838. value[ index + i ] = matrix.elements[ i ];
  8839. }
  8840. }
  8841. } else {
  8842. for ( let i = 0; i < array.length; i ++ ) {
  8843. const index = i * 4;
  8844. const vector = array[ i ];
  8845. value[ index ] = vector.x;
  8846. value[ index + 1 ] = vector.y;
  8847. value[ index + 2 ] = vector.z || 0;
  8848. value[ index + 3 ] = vector.w || 0;
  8849. }
  8850. }
  8851. }
  8852. /**
  8853. * Implement the value buffer creation based on the array data.
  8854. *
  8855. * @param {NodeBuilder} builder - A reference to the current node builder.
  8856. * @return {null}
  8857. */
  8858. setup( builder ) {
  8859. const length = this.array.length;
  8860. const elementType = this.elementType;
  8861. let arrayType = Float32Array;
  8862. const paddedType = this.paddedType;
  8863. const paddedElementLength = builder.getTypeLength( paddedType );
  8864. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8865. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8866. this.value = new arrayType( length * paddedElementLength );
  8867. this.bufferCount = length;
  8868. this.bufferType = paddedType;
  8869. return super.setup( builder );
  8870. }
  8871. /**
  8872. * Overwrites the default `element()` method to provide element access
  8873. * based on {@link UniformArrayNode}.
  8874. *
  8875. * @param {IndexNode} indexNode - The index node.
  8876. * @return {UniformArrayElementNode}
  8877. */
  8878. element( indexNode ) {
  8879. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8880. }
  8881. }
  8882. /**
  8883. * TSL function for creating an uniform array node.
  8884. *
  8885. * @tsl
  8886. * @function
  8887. * @param {Array<any>} values - Array-like data.
  8888. * @param {?string} [nodeType] - The data type of the array elements.
  8889. * @returns {UniformArrayNode}
  8890. */
  8891. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8892. /**
  8893. * The node allows to set values for built-in shader variables. That is
  8894. * required for features like hardware-accelerated vertex clipping.
  8895. *
  8896. * @augments Node
  8897. */
  8898. class BuiltinNode extends Node {
  8899. /**
  8900. * Constructs a new builtin node.
  8901. *
  8902. * @param {string} name - The name of the built-in shader variable.
  8903. */
  8904. constructor( name ) {
  8905. super( 'float' );
  8906. /**
  8907. * The name of the built-in shader variable.
  8908. *
  8909. * @type {string}
  8910. */
  8911. this.name = name;
  8912. /**
  8913. * This flag can be used for type testing.
  8914. *
  8915. * @type {boolean}
  8916. * @readonly
  8917. * @default true
  8918. */
  8919. this.isBuiltinNode = true;
  8920. }
  8921. /**
  8922. * Generates the code snippet of the builtin node.
  8923. *
  8924. * @param {NodeBuilder} builder - The current node builder.
  8925. * @return {string} The generated code snippet.
  8926. */
  8927. generate( /* builder */ ) {
  8928. return this.name;
  8929. }
  8930. }
  8931. /**
  8932. * TSL function for creating a builtin node.
  8933. *
  8934. * @tsl
  8935. * @function
  8936. * @param {string} name - The name of the built-in shader variable.
  8937. * @returns {BuiltinNode}
  8938. */
  8939. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8940. let _screenSizeVec, _viewportVec;
  8941. /**
  8942. * This node provides a collection of screen related metrics.
  8943. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8944. * resolution or viewport data as well as fragment or uv coordinates.
  8945. *
  8946. * @augments Node
  8947. */
  8948. class ScreenNode extends Node {
  8949. static get type() {
  8950. return 'ScreenNode';
  8951. }
  8952. /**
  8953. * Constructs a new screen node.
  8954. *
  8955. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  8956. */
  8957. constructor( scope ) {
  8958. super();
  8959. /**
  8960. * The node represents different metric depending on which scope is selected.
  8961. *
  8962. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8963. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8964. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8965. * - `ScreenNode.UV`: Normalized coordinates.
  8966. * - `ScreenNode.DPR`: Device pixel ratio.
  8967. *
  8968. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  8969. */
  8970. this.scope = scope;
  8971. /**
  8972. * This output node.
  8973. *
  8974. * @type {?Node}
  8975. * @default null
  8976. */
  8977. this._output = null;
  8978. /**
  8979. * This flag can be used for type testing.
  8980. *
  8981. * @type {boolean}
  8982. * @readonly
  8983. * @default true
  8984. */
  8985. this.isViewportNode = true;
  8986. }
  8987. /**
  8988. * This method is overwritten since the node type depends on the selected scope.
  8989. *
  8990. * @return {('float'|'vec2'|'vec4')} The node type.
  8991. */
  8992. getNodeType() {
  8993. if ( this.scope === ScreenNode.DPR ) return 'float';
  8994. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8995. else return 'vec2';
  8996. }
  8997. /**
  8998. * This method is overwritten since the node's update type depends on the selected scope.
  8999. *
  9000. * @return {NodeUpdateType} The update type.
  9001. */
  9002. getUpdateType() {
  9003. let updateType = NodeUpdateType.NONE;
  9004. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9005. updateType = NodeUpdateType.RENDER;
  9006. }
  9007. this.updateType = updateType;
  9008. return updateType;
  9009. }
  9010. /**
  9011. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9012. * from the current renderer.
  9013. *
  9014. * @param {NodeFrame} frame - A reference to the current node frame.
  9015. */
  9016. update( { renderer } ) {
  9017. const renderTarget = renderer.getRenderTarget();
  9018. if ( this.scope === ScreenNode.VIEWPORT ) {
  9019. if ( renderTarget !== null ) {
  9020. _viewportVec.copy( renderTarget.viewport );
  9021. } else {
  9022. renderer.getViewport( _viewportVec );
  9023. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9024. }
  9025. } else if ( this.scope === ScreenNode.DPR ) {
  9026. this._output.value = renderer.getPixelRatio();
  9027. } else {
  9028. if ( renderTarget !== null ) {
  9029. _screenSizeVec.width = renderTarget.width;
  9030. _screenSizeVec.height = renderTarget.height;
  9031. } else {
  9032. renderer.getDrawingBufferSize( _screenSizeVec );
  9033. }
  9034. }
  9035. }
  9036. setup( /*builder*/ ) {
  9037. const scope = this.scope;
  9038. let output = null;
  9039. if ( scope === ScreenNode.SIZE ) {
  9040. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9041. } else if ( scope === ScreenNode.VIEWPORT ) {
  9042. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9043. } else if ( scope === ScreenNode.DPR ) {
  9044. output = uniform( 1 );
  9045. } else {
  9046. output = vec2( screenCoordinate.div( screenSize ) );
  9047. }
  9048. this._output = output;
  9049. return output;
  9050. }
  9051. generate( builder ) {
  9052. if ( this.scope === ScreenNode.COORDINATE ) {
  9053. let coord = builder.getFragCoord();
  9054. if ( builder.isFlipY() ) {
  9055. // follow webgpu standards
  9056. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9057. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9058. }
  9059. return coord;
  9060. }
  9061. return super.generate( builder );
  9062. }
  9063. }
  9064. ScreenNode.COORDINATE = 'coordinate';
  9065. ScreenNode.VIEWPORT = 'viewport';
  9066. ScreenNode.SIZE = 'size';
  9067. ScreenNode.UV = 'uv';
  9068. ScreenNode.DPR = 'dpr';
  9069. // Screen
  9070. /**
  9071. * TSL object that represents the current DPR.
  9072. *
  9073. * @tsl
  9074. * @type {ScreenNode<float>}
  9075. */
  9076. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9077. /**
  9078. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9079. *
  9080. * @tsl
  9081. * @type {ScreenNode<vec2>}
  9082. */
  9083. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9084. /**
  9085. * TSL object that represents the screen resolution in physical pixel units.
  9086. *
  9087. * @tsl
  9088. * @type {ScreenNode<vec2>}
  9089. */
  9090. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9091. /**
  9092. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9093. *
  9094. * @tsl
  9095. * @type {ScreenNode<vec2>}
  9096. */
  9097. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9098. // Viewport
  9099. /**
  9100. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9101. *
  9102. * @tsl
  9103. * @type {ScreenNode<vec4>}
  9104. */
  9105. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9106. /**
  9107. * TSL object that represents the viewport resolution in physical pixel units.
  9108. *
  9109. * @tsl
  9110. * @type {ScreenNode<vec2>}
  9111. */
  9112. const viewportSize = viewport.zw;
  9113. /**
  9114. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9115. *
  9116. * @tsl
  9117. * @type {ScreenNode<vec2>}
  9118. */
  9119. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9120. /**
  9121. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9122. *
  9123. * @tsl
  9124. * @type {ScreenNode<vec2>}
  9125. */
  9126. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9127. // Deprecated
  9128. /**
  9129. * @deprecated since r169. Use {@link screenSize} instead.
  9130. */
  9131. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9132. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9133. return screenSize;
  9134. }, 'vec2' ).once() )();
  9135. /**
  9136. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9137. *
  9138. * @tsl
  9139. * @type {UniformNode<uint>}
  9140. */
  9141. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9142. /**
  9143. * TSL object that represents the `near` value of the camera used for the current render.
  9144. *
  9145. * @tsl
  9146. * @type {UniformNode<float>}
  9147. */
  9148. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9149. /**
  9150. * TSL object that represents the `far` value of the camera used for the current render.
  9151. *
  9152. * @tsl
  9153. * @type {UniformNode<float>}
  9154. */
  9155. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9156. /**
  9157. * TSL object that represents the projection matrix of the camera used for the current render.
  9158. *
  9159. * @tsl
  9160. * @type {UniformNode<mat4>}
  9161. */
  9162. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9163. let cameraProjectionMatrix;
  9164. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9165. const matrices = [];
  9166. for ( const subCamera of camera.cameras ) {
  9167. matrices.push( subCamera.projectionMatrix );
  9168. }
  9169. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9170. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9171. } else {
  9172. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9173. }
  9174. return cameraProjectionMatrix;
  9175. } ).once() )();
  9176. /**
  9177. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9178. *
  9179. * @tsl
  9180. * @type {UniformNode<mat4>}
  9181. */
  9182. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9183. let cameraProjectionMatrixInverse;
  9184. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9185. const matrices = [];
  9186. for ( const subCamera of camera.cameras ) {
  9187. matrices.push( subCamera.projectionMatrixInverse );
  9188. }
  9189. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9190. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9191. } else {
  9192. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9193. }
  9194. return cameraProjectionMatrixInverse;
  9195. } ).once() )();
  9196. /**
  9197. * TSL object that represents the view matrix of the camera used for the current render.
  9198. *
  9199. * @tsl
  9200. * @type {UniformNode<mat4>}
  9201. */
  9202. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9203. let cameraViewMatrix;
  9204. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9205. const matrices = [];
  9206. for ( const subCamera of camera.cameras ) {
  9207. matrices.push( subCamera.matrixWorldInverse );
  9208. }
  9209. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9210. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9211. } else {
  9212. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9213. }
  9214. return cameraViewMatrix;
  9215. } ).once() )();
  9216. /**
  9217. * TSL object that represents the world matrix of the camera used for the current render.
  9218. *
  9219. * @tsl
  9220. * @type {UniformNode<mat4>}
  9221. */
  9222. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9223. let cameraWorldMatrix;
  9224. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9225. const matrices = [];
  9226. for ( const subCamera of camera.cameras ) {
  9227. matrices.push( subCamera.matrixWorld );
  9228. }
  9229. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9230. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9231. } else {
  9232. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9233. }
  9234. return cameraWorldMatrix;
  9235. } ).once() )();
  9236. /**
  9237. * TSL object that represents the normal matrix of the camera used for the current render.
  9238. *
  9239. * @tsl
  9240. * @type {UniformNode<mat3>}
  9241. */
  9242. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9243. let cameraNormalMatrix;
  9244. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9245. const matrices = [];
  9246. for ( const subCamera of camera.cameras ) {
  9247. matrices.push( subCamera.normalMatrix );
  9248. }
  9249. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9250. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9251. } else {
  9252. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9253. }
  9254. return cameraNormalMatrix;
  9255. } ).once() )();
  9256. /**
  9257. * TSL object that represents the position in world space of the camera used for the current render.
  9258. *
  9259. * @tsl
  9260. * @type {UniformNode<vec3>}
  9261. */
  9262. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9263. let cameraPosition;
  9264. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9265. const positions = [];
  9266. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9267. positions.push( new Vector3() );
  9268. }
  9269. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9270. const subCameras = camera.cameras;
  9271. const array = self.array;
  9272. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9273. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9274. }
  9275. } );
  9276. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9277. } else {
  9278. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9279. }
  9280. return cameraPosition;
  9281. } ).once() )();
  9282. /**
  9283. * TSL object that represents the viewport of the camera used for the current render.
  9284. *
  9285. * @tsl
  9286. * @type {UniformNode<vec4>}
  9287. */
  9288. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9289. let cameraViewport;
  9290. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9291. const viewports = [];
  9292. for ( const subCamera of camera.cameras ) {
  9293. viewports.push( subCamera.viewport );
  9294. }
  9295. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9296. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9297. } else {
  9298. // Fallback for single camera
  9299. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9300. }
  9301. return cameraViewport;
  9302. } ).once() )();
  9303. const _sphere = /*@__PURE__*/ new Sphere();
  9304. /**
  9305. * This node can be used to access transformation related metrics of 3D objects.
  9306. * Depending on the selected scope, a different metric is represented as a uniform
  9307. * in the shader. The following scopes are supported:
  9308. *
  9309. * - `POSITION`: The object's position in world space.
  9310. * - `VIEW_POSITION`: The object's position in view/camera space.
  9311. * - `DIRECTION`: The object's direction in world space.
  9312. * - `SCALE`: The object's scale in world space.
  9313. * - `WORLD_MATRIX`: The object's matrix in world space.
  9314. *
  9315. * @augments Node
  9316. */
  9317. class Object3DNode extends Node {
  9318. static get type() {
  9319. return 'Object3DNode';
  9320. }
  9321. /**
  9322. * Constructs a new object 3D node.
  9323. *
  9324. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9325. * @param {?Object3D} [object3d=null] - The 3D object.
  9326. */
  9327. constructor( scope, object3d = null ) {
  9328. super();
  9329. /**
  9330. * The node reports a different type of transformation depending on the scope.
  9331. *
  9332. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9333. */
  9334. this.scope = scope;
  9335. /**
  9336. * The 3D object.
  9337. *
  9338. * @type {?Object3D}
  9339. * @default null
  9340. */
  9341. this.object3d = object3d;
  9342. /**
  9343. * Overwritten since this type of node is updated per object.
  9344. *
  9345. * @type {string}
  9346. * @default 'object'
  9347. */
  9348. this.updateType = NodeUpdateType.OBJECT;
  9349. /**
  9350. * Holds the value of the node as a uniform.
  9351. *
  9352. * @type {UniformNode}
  9353. */
  9354. this.uniformNode = new UniformNode( null );
  9355. }
  9356. /**
  9357. * Overwritten since the node type is inferred from the scope.
  9358. *
  9359. * @return {('mat4'|'vec3'|'float')} The node type.
  9360. */
  9361. getNodeType() {
  9362. const scope = this.scope;
  9363. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9364. return 'mat4';
  9365. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9366. return 'vec3';
  9367. } else if ( scope === Object3DNode.RADIUS ) {
  9368. return 'float';
  9369. }
  9370. }
  9371. /**
  9372. * Updates the uniform value depending on the scope.
  9373. *
  9374. * @param {NodeFrame} frame - The current node frame.
  9375. */
  9376. update( frame ) {
  9377. const object = this.object3d;
  9378. const uniformNode = this.uniformNode;
  9379. const scope = this.scope;
  9380. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9381. uniformNode.value = object.matrixWorld;
  9382. } else if ( scope === Object3DNode.POSITION ) {
  9383. uniformNode.value = uniformNode.value || new Vector3();
  9384. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9385. } else if ( scope === Object3DNode.SCALE ) {
  9386. uniformNode.value = uniformNode.value || new Vector3();
  9387. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9388. } else if ( scope === Object3DNode.DIRECTION ) {
  9389. uniformNode.value = uniformNode.value || new Vector3();
  9390. object.getWorldDirection( uniformNode.value );
  9391. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9392. const camera = frame.camera;
  9393. uniformNode.value = uniformNode.value || new Vector3();
  9394. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9395. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9396. } else if ( scope === Object3DNode.RADIUS ) {
  9397. const geometry = frame.object.geometry;
  9398. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9399. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9400. uniformNode.value = _sphere.radius;
  9401. }
  9402. }
  9403. /**
  9404. * Generates the code snippet of the uniform node. The node type of the uniform
  9405. * node also depends on the selected scope.
  9406. *
  9407. * @param {NodeBuilder} builder - The current node builder.
  9408. * @return {string} The generated code snippet.
  9409. */
  9410. generate( builder ) {
  9411. const scope = this.scope;
  9412. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9413. this.uniformNode.nodeType = 'mat4';
  9414. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9415. this.uniformNode.nodeType = 'vec3';
  9416. } else if ( scope === Object3DNode.RADIUS ) {
  9417. this.uniformNode.nodeType = 'float';
  9418. }
  9419. return this.uniformNode.build( builder );
  9420. }
  9421. serialize( data ) {
  9422. super.serialize( data );
  9423. data.scope = this.scope;
  9424. }
  9425. deserialize( data ) {
  9426. super.deserialize( data );
  9427. this.scope = data.scope;
  9428. }
  9429. }
  9430. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9431. Object3DNode.POSITION = 'position';
  9432. Object3DNode.SCALE = 'scale';
  9433. Object3DNode.VIEW_POSITION = 'viewPosition';
  9434. Object3DNode.DIRECTION = 'direction';
  9435. Object3DNode.RADIUS = 'radius';
  9436. /**
  9437. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9438. *
  9439. * @tsl
  9440. * @function
  9441. * @param {?Object3D} [object3d] - The 3D object.
  9442. * @returns {Object3DNode<vec3>}
  9443. */
  9444. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9445. /**
  9446. * TSL function for creating an object 3D node that represents the object's world matrix.
  9447. *
  9448. * @tsl
  9449. * @function
  9450. * @param {?Object3D} [object3d] - The 3D object.
  9451. * @returns {Object3DNode<mat4>}
  9452. */
  9453. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9454. /**
  9455. * TSL function for creating an object 3D node that represents the object's position in world space.
  9456. *
  9457. * @tsl
  9458. * @function
  9459. * @param {?Object3D} [object3d] - The 3D object.
  9460. * @returns {Object3DNode<vec3>}
  9461. */
  9462. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9463. /**
  9464. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9465. *
  9466. * @tsl
  9467. * @function
  9468. * @param {?Object3D} [object3d] - The 3D object.
  9469. * @returns {Object3DNode<vec3>}
  9470. */
  9471. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9472. /**
  9473. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9474. *
  9475. * @tsl
  9476. * @function
  9477. * @param {?Object3D} [object3d] - The 3D object.
  9478. * @returns {Object3DNode<vec3>}
  9479. */
  9480. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9481. /**
  9482. * TSL function for creating an object 3D node that represents the object's radius.
  9483. *
  9484. * @tsl
  9485. * @function
  9486. * @param {?Object3D} [object3d] - The 3D object.
  9487. * @returns {Object3DNode<float>}
  9488. */
  9489. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9490. /**
  9491. * This type of node is a specialized version of `Object3DNode`
  9492. * with larger set of model related metrics. Unlike `Object3DNode`,
  9493. * `ModelNode` extracts the reference to the 3D object from the
  9494. * current node frame state.
  9495. *
  9496. * @augments Object3DNode
  9497. */
  9498. class ModelNode extends Object3DNode {
  9499. static get type() {
  9500. return 'ModelNode';
  9501. }
  9502. /**
  9503. * Constructs a new object model node.
  9504. *
  9505. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9506. */
  9507. constructor( scope ) {
  9508. super( scope );
  9509. }
  9510. /**
  9511. * Extracts the model reference from the frame state and then
  9512. * updates the uniform value depending on the scope.
  9513. *
  9514. * @param {NodeFrame} frame - The current node frame.
  9515. */
  9516. update( frame ) {
  9517. this.object3d = frame.object;
  9518. super.update( frame );
  9519. }
  9520. }
  9521. /**
  9522. * TSL object that represents the object's direction in world space.
  9523. *
  9524. * @tsl
  9525. * @type {ModelNode<vec3>}
  9526. */
  9527. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9528. /**
  9529. * TSL object that represents the object's world matrix.
  9530. *
  9531. * @tsl
  9532. * @type {ModelNode<mat4>}
  9533. */
  9534. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9535. /**
  9536. * TSL object that represents the object's position in world space.
  9537. *
  9538. * @tsl
  9539. * @type {ModelNode<vec3>}
  9540. */
  9541. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9542. /**
  9543. * TSL object that represents the object's scale in world space.
  9544. *
  9545. * @tsl
  9546. * @type {ModelNode<vec3>}
  9547. */
  9548. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9549. /**
  9550. * TSL object that represents the object's position in view/camera space.
  9551. *
  9552. * @tsl
  9553. * @type {ModelNode<vec3>}
  9554. */
  9555. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9556. /**
  9557. * TSL object that represents the object's radius.
  9558. *
  9559. * @tsl
  9560. * @type {ModelNode<float>}
  9561. */
  9562. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9563. /**
  9564. * TSL object that represents the object's normal matrix.
  9565. *
  9566. * @tsl
  9567. * @type {UniformNode<mat3>}
  9568. */
  9569. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9570. /**
  9571. * TSL object that represents the object's inverse world matrix.
  9572. *
  9573. * @tsl
  9574. * @type {UniformNode<mat4>}
  9575. */
  9576. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9577. /**
  9578. * TSL object that represents the object's model view matrix.
  9579. *
  9580. * @tsl
  9581. * @type {Node<mat4>}
  9582. */
  9583. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9584. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9585. } ).once() )().toVar( 'modelViewMatrix' );
  9586. // GPU Precision
  9587. /**
  9588. * TSL object that represents the object's model view in `mediump` precision.
  9589. *
  9590. * @tsl
  9591. * @type {Node<mat4>}
  9592. */
  9593. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9594. // CPU Precision
  9595. /**
  9596. * TSL object that represents the object's model view in `highp` precision
  9597. * which is achieved by computing the matrix in JS and not in the shader.
  9598. *
  9599. * @tsl
  9600. * @type {Node<mat4>}
  9601. */
  9602. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9603. builder.context.isHighPrecisionModelViewMatrix = true;
  9604. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9605. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9606. } );
  9607. } ).once() )().toVar( 'highpModelViewMatrix' );
  9608. /**
  9609. * TSL object that represents the object's model normal view in `highp` precision
  9610. * which is achieved by computing the matrix in JS and not in the shader.
  9611. *
  9612. * @tsl
  9613. * @type {Node<mat3>}
  9614. */
  9615. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9616. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9617. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9618. if ( isHighPrecisionModelViewMatrix !== true ) {
  9619. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9620. }
  9621. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9622. } );
  9623. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9624. /**
  9625. * TSL object that represents the position attribute of the current rendered object.
  9626. *
  9627. * @tsl
  9628. * @type {AttributeNode<vec3>}
  9629. */
  9630. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9631. /**
  9632. * TSL object that represents the vertex position in local space of the current rendered object.
  9633. *
  9634. * @tsl
  9635. * @type {AttributeNode<vec3>}
  9636. */
  9637. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9638. /**
  9639. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9640. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9641. *
  9642. * @tsl
  9643. * @type {AttributeNode<vec3>}
  9644. */
  9645. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9646. /**
  9647. * TSL object that represents the vertex position in world space of the current rendered object.
  9648. *
  9649. * @tsl
  9650. * @type {VaryingNode<vec3>}
  9651. */
  9652. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9653. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9654. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9655. /**
  9656. * TSL object that represents the position world direction of the current rendered object.
  9657. *
  9658. * @tsl
  9659. * @type {Node<vec3>}
  9660. */
  9661. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9662. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9663. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9664. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9665. /**
  9666. * TSL object that represents the vertex position in view space of the current rendered object.
  9667. *
  9668. * @tsl
  9669. * @type {VaryingNode<vec3>}
  9670. */
  9671. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9672. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9673. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9674. /**
  9675. * TSL object that represents the position view direction of the current rendered object.
  9676. *
  9677. * @tsl
  9678. * @type {VaryingNode<vec3>}
  9679. */
  9680. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9681. /**
  9682. * This node can be used to evaluate whether a primitive is front or back facing.
  9683. *
  9684. * @augments Node
  9685. */
  9686. class FrontFacingNode extends Node {
  9687. static get type() {
  9688. return 'FrontFacingNode';
  9689. }
  9690. /**
  9691. * Constructs a new front facing node.
  9692. */
  9693. constructor() {
  9694. super( 'bool' );
  9695. /**
  9696. * This flag can be used for type testing.
  9697. *
  9698. * @type {boolean}
  9699. * @readonly
  9700. * @default true
  9701. */
  9702. this.isFrontFacingNode = true;
  9703. }
  9704. generate( builder ) {
  9705. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9706. //
  9707. const { material } = builder;
  9708. if ( material.side === BackSide ) {
  9709. return 'false';
  9710. }
  9711. return builder.getFrontFacing();
  9712. }
  9713. }
  9714. /**
  9715. * TSL object that represents whether a primitive is front or back facing
  9716. *
  9717. * @tsl
  9718. * @type {FrontFacingNode<bool>}
  9719. */
  9720. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9721. /**
  9722. * TSL object that represents the front facing status as a number instead of a bool.
  9723. * `1` means front facing, `-1` means back facing.
  9724. *
  9725. * @tsl
  9726. * @type {Node<float>}
  9727. */
  9728. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9729. /**
  9730. * Converts a direction vector to a face direction vector based on the material's side.
  9731. *
  9732. * If the material is set to `BackSide`, the direction is inverted.
  9733. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9734. *
  9735. * @tsl
  9736. * @param {Node<vec3>} direction - The direction vector to convert.
  9737. * @returns {Node<vec3>} The converted direction vector.
  9738. */
  9739. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9740. const side = material.side;
  9741. if ( side === BackSide ) {
  9742. direction = direction.mul( -1 );
  9743. } else if ( side === DoubleSide ) {
  9744. direction = direction.mul( faceDirection );
  9745. }
  9746. return direction;
  9747. } );
  9748. /**
  9749. * TSL object that represents the normal attribute of the current rendered object in local space.
  9750. *
  9751. * @tsl
  9752. * @type {Node<vec3>}
  9753. */
  9754. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9755. /**
  9756. * TSL object that represents the vertex normal of the current rendered object in local space.
  9757. *
  9758. * @tsl
  9759. * @type {Node<vec3>}
  9760. */
  9761. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9762. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9763. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9764. return vec3( 0, 1, 0 );
  9765. }
  9766. return normalGeometry;
  9767. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9768. /**
  9769. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9770. *
  9771. * @tsl
  9772. * @type {Node<vec3>}
  9773. */
  9774. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9775. /**
  9776. * TSL object that represents the vertex normal of the current rendered object in view space.
  9777. *
  9778. * @tsl
  9779. * @type {Node<vec3>}
  9780. */
  9781. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9782. let node;
  9783. if ( builder.material.flatShading === true ) {
  9784. node = normalFlat;
  9785. } else {
  9786. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9787. }
  9788. return node;
  9789. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9790. /**
  9791. * TSL object that represents the vertex normal of the current rendered object in world space.
  9792. *
  9793. * @tsl
  9794. * @type {Node<vec3>}
  9795. */
  9796. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9797. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9798. if ( builder.material.flatShading !== true ) {
  9799. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9800. }
  9801. return normal.normalize().toVar( 'normalWorldGeometry' );
  9802. }, 'vec3' ).once() )();
  9803. /**
  9804. * TSL object that represents the vertex normal of the current rendered object in view space.
  9805. *
  9806. * @tsl
  9807. * @type {Node<vec3>}
  9808. */
  9809. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9810. let node;
  9811. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9812. node = normalViewGeometry;
  9813. if ( material.flatShading !== true ) {
  9814. node = directionToFaceDirection( node );
  9815. }
  9816. } else {
  9817. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9818. node = context.setupNormal().context( { getUV: null } );
  9819. }
  9820. return node;
  9821. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9822. /**
  9823. * TSL object that represents the vertex normal of the current rendered object in world space.
  9824. *
  9825. * @tsl
  9826. * @type {Node<vec3>}
  9827. */
  9828. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9829. /**
  9830. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9831. *
  9832. * @tsl
  9833. * @type {Node<vec3>}
  9834. */
  9835. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9836. let node;
  9837. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9838. node = normalView;
  9839. } else {
  9840. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9841. node = context.setupClearcoatNormal().context( { getUV: null } );
  9842. }
  9843. return node;
  9844. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9845. /**
  9846. * Transforms the normal with the given matrix.
  9847. *
  9848. * @tsl
  9849. * @function
  9850. * @param {Node<vec3>} normal - The normal.
  9851. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9852. * @return {Node<vec3>} The transformed normal.
  9853. */
  9854. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9855. const m = mat3( matrix );
  9856. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9857. return m.mul( transformedNormal ).xyz;
  9858. } );
  9859. /**
  9860. * Transforms the given normal from local to view space.
  9861. *
  9862. * @tsl
  9863. * @function
  9864. * @param {Node<vec3>} normal - The normal.
  9865. * @param {NodeBuilder} builder - The current node builder.
  9866. * @return {Node<vec3>} The transformed normal.
  9867. */
  9868. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9869. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9870. if ( modelNormalViewMatrix !== null ) {
  9871. return modelNormalViewMatrix.transformDirection( normal );
  9872. }
  9873. //
  9874. const transformedNormal = modelNormalMatrix.mul( normal );
  9875. return cameraViewMatrix.transformDirection( transformedNormal );
  9876. } );
  9877. // Deprecated
  9878. /**
  9879. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9880. *
  9881. * @tsl
  9882. * @type {Node<vec3>}
  9883. * @deprecated since r178. Use `normalView` instead.
  9884. */
  9885. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9886. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9887. return normalView;
  9888. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9889. /**
  9890. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9891. *
  9892. * @tsl
  9893. * @type {Node<vec3>}
  9894. * @deprecated since r178. Use `normalWorld` instead.
  9895. */
  9896. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9897. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9898. return normalWorld;
  9899. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9900. /**
  9901. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9902. *
  9903. * @tsl
  9904. * @type {Node<vec3>}
  9905. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9906. */
  9907. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9908. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9909. return clearcoatNormalView;
  9910. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9911. const _e1$1 = /*@__PURE__*/ new Euler();
  9912. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9913. /**
  9914. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9915. *
  9916. * @tsl
  9917. * @type {UniformNode<float>}
  9918. */
  9919. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9920. /**
  9921. * TSL object that represents the intensity of environment maps of PBR materials.
  9922. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9923. *
  9924. * @tsl
  9925. * @type {Node<float>}
  9926. */
  9927. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9928. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9929. } );
  9930. /**
  9931. * TSL object that represents the rotation of environment maps.
  9932. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9933. * rotation of `scene.environment` instead.
  9934. *
  9935. * @tsl
  9936. * @type {Node<mat4>}
  9937. */
  9938. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9939. return frame.material;
  9940. } ).onObjectUpdate( function ( { material, scene } ) {
  9941. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9942. if ( rotation ) {
  9943. _e1$1.copy( rotation );
  9944. _m1$1.makeRotationFromEuler( _e1$1 );
  9945. } else {
  9946. _m1$1.identity();
  9947. }
  9948. return _m1$1;
  9949. } );
  9950. /**
  9951. * The reflect vector in view space.
  9952. *
  9953. * @tsl
  9954. * @type {Node<vec3>}
  9955. */
  9956. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9957. /**
  9958. * The refract vector in view space.
  9959. *
  9960. * @tsl
  9961. * @type {Node<vec3>}
  9962. */
  9963. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9964. /**
  9965. * Used for sampling cube maps when using cube reflection mapping.
  9966. *
  9967. * @tsl
  9968. * @type {Node<vec3>}
  9969. */
  9970. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9971. /**
  9972. * Used for sampling cube maps when using cube refraction mapping.
  9973. *
  9974. * @tsl
  9975. * @type {Node<vec3>}
  9976. */
  9977. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9978. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9979. /**
  9980. * This type of uniform node represents a cube texture.
  9981. *
  9982. * @augments TextureNode
  9983. */
  9984. class CubeTextureNode extends TextureNode {
  9985. static get type() {
  9986. return 'CubeTextureNode';
  9987. }
  9988. /**
  9989. * Constructs a new cube texture node.
  9990. *
  9991. * @param {CubeTexture} value - The cube texture.
  9992. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9993. * @param {?Node<int>} [levelNode=null] - The level node.
  9994. * @param {?Node<float>} [biasNode=null] - The bias node.
  9995. */
  9996. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9997. super( value, uvNode, levelNode, biasNode );
  9998. /**
  9999. * This flag can be used for type testing.
  10000. *
  10001. * @type {boolean}
  10002. * @readonly
  10003. * @default true
  10004. */
  10005. this.isCubeTextureNode = true;
  10006. }
  10007. /**
  10008. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10009. *
  10010. * @param {NodeBuilder} builder - The current node builder.
  10011. * @return {string} The input type.
  10012. */
  10013. getInputType( /*builder*/ ) {
  10014. return 'cubeTexture';
  10015. }
  10016. /**
  10017. * Returns a default uvs based on the mapping type of the cube texture.
  10018. *
  10019. * @return {Node<vec3>} The default uv attribute.
  10020. */
  10021. getDefaultUV() {
  10022. const texture = this.value;
  10023. if ( texture.mapping === CubeReflectionMapping ) {
  10024. return reflectVector;
  10025. } else if ( texture.mapping === CubeRefractionMapping ) {
  10026. return refractVector;
  10027. } else {
  10028. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10029. return vec3( 0, 0, 0 );
  10030. }
  10031. }
  10032. /**
  10033. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10034. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10035. *
  10036. * @param {boolean} value - The update toggle.
  10037. */
  10038. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10039. /**
  10040. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10041. * to modify the uv node for correct sampling.
  10042. *
  10043. * @param {NodeBuilder} builder - The current node builder.
  10044. * @param {Node} uvNode - The uv node to setup.
  10045. * @return {Node} The updated uv node.
  10046. */
  10047. setupUV( builder, uvNode ) {
  10048. const texture = this.value;
  10049. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10050. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10051. }
  10052. return materialEnvRotation.mul( uvNode );
  10053. }
  10054. /**
  10055. * Generates the uv code snippet.
  10056. *
  10057. * @param {NodeBuilder} builder - The current node builder.
  10058. * @param {Node} cubeUV - The uv node to generate code for.
  10059. * @return {string} The generated code snippet.
  10060. */
  10061. generateUV( builder, cubeUV ) {
  10062. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10063. }
  10064. }
  10065. /**
  10066. * TSL function for creating a cube texture node.
  10067. *
  10068. * @tsl
  10069. * @function
  10070. * @param {CubeTexture} value - The cube texture.
  10071. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10072. * @param {?Node<int>} [levelNode=null] - The level node.
  10073. * @param {?Node<float>} [biasNode=null] - The bias node.
  10074. * @returns {CubeTextureNode}
  10075. */
  10076. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10077. /**
  10078. * TSL function for creating a cube texture uniform node.
  10079. *
  10080. * @tsl
  10081. * @function
  10082. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10083. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10084. * @param {?Node<int>} [levelNode=null] - The level node.
  10085. * @param {?Node<float>} [biasNode=null] - The bias node.
  10086. * @returns {CubeTextureNode}
  10087. */
  10088. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10089. let textureNode;
  10090. if ( value && value.isCubeTextureNode === true ) {
  10091. textureNode = nodeObject( value.clone() );
  10092. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10093. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10094. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10095. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10096. } else {
  10097. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10098. }
  10099. return textureNode;
  10100. };
  10101. /**
  10102. * TSL function for creating a uniform cube texture node.
  10103. *
  10104. * @tsl
  10105. * @function
  10106. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10107. * @returns {CubeTextureNode}
  10108. */
  10109. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10110. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10111. /**
  10112. * This class is only relevant if the referenced property is array-like.
  10113. * In this case, `ReferenceElementNode` allows to refer to a specific
  10114. * element inside the data structure via an index.
  10115. *
  10116. * @augments ArrayElementNode
  10117. */
  10118. class ReferenceElementNode extends ArrayElementNode {
  10119. static get type() {
  10120. return 'ReferenceElementNode';
  10121. }
  10122. /**
  10123. * Constructs a new reference element node.
  10124. *
  10125. * @param {?ReferenceNode} referenceNode - The reference node.
  10126. * @param {Node} indexNode - The index node that defines the element access.
  10127. */
  10128. constructor( referenceNode, indexNode ) {
  10129. super( referenceNode, indexNode );
  10130. /**
  10131. * Similar to {@link ReferenceNode#reference}, an additional
  10132. * property references to the current node.
  10133. *
  10134. * @type {?ReferenceNode}
  10135. * @default null
  10136. */
  10137. this.referenceNode = referenceNode;
  10138. /**
  10139. * This flag can be used for type testing.
  10140. *
  10141. * @type {boolean}
  10142. * @readonly
  10143. * @default true
  10144. */
  10145. this.isReferenceElementNode = true;
  10146. }
  10147. /**
  10148. * This method is overwritten since the node type is inferred from
  10149. * the uniform type of the reference node.
  10150. *
  10151. * @return {string} The node type.
  10152. */
  10153. getNodeType() {
  10154. return this.referenceNode.uniformType;
  10155. }
  10156. generate( builder ) {
  10157. const snippet = super.generate( builder );
  10158. const arrayType = this.referenceNode.getNodeType();
  10159. const elementType = this.getNodeType();
  10160. return builder.format( snippet, arrayType, elementType );
  10161. }
  10162. }
  10163. /**
  10164. * This type of node establishes a reference to a property of another object.
  10165. * In this way, the value of the node is automatically linked to the value of
  10166. * referenced object. Reference nodes internally represent the linked value
  10167. * as a uniform.
  10168. *
  10169. * @augments Node
  10170. */
  10171. class ReferenceNode extends Node {
  10172. static get type() {
  10173. return 'ReferenceNode';
  10174. }
  10175. /**
  10176. * Constructs a new reference node.
  10177. *
  10178. * @param {string} property - The name of the property the node refers to.
  10179. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10180. * @param {?Object} [object=null] - The object the property belongs to.
  10181. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10182. */
  10183. constructor( property, uniformType, object = null, count = null ) {
  10184. super();
  10185. /**
  10186. * The name of the property the node refers to.
  10187. *
  10188. * @type {string}
  10189. */
  10190. this.property = property;
  10191. /**
  10192. * The uniform type that should be used to represent the property value.
  10193. *
  10194. * @type {string}
  10195. */
  10196. this.uniformType = uniformType;
  10197. /**
  10198. * The object the property belongs to.
  10199. *
  10200. * @type {?Object}
  10201. * @default null
  10202. */
  10203. this.object = object;
  10204. /**
  10205. * When the linked property is an array, this parameter defines its length.
  10206. *
  10207. * @type {?number}
  10208. * @default null
  10209. */
  10210. this.count = count;
  10211. /**
  10212. * The property name might have dots so nested properties can be referred.
  10213. * The hierarchy of the names is stored inside this array.
  10214. *
  10215. * @type {Array<string>}
  10216. */
  10217. this.properties = property.split( '.' );
  10218. /**
  10219. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10220. * since the final reference might be updated from calling code.
  10221. *
  10222. * @type {?Object}
  10223. * @default null
  10224. */
  10225. this.reference = object;
  10226. /**
  10227. * The uniform node that holds the value of the reference node.
  10228. *
  10229. * @type {UniformNode}
  10230. * @default null
  10231. */
  10232. this.node = null;
  10233. /**
  10234. * The uniform group of the internal uniform.
  10235. *
  10236. * @type {UniformGroupNode}
  10237. * @default null
  10238. */
  10239. this.group = null;
  10240. /**
  10241. * An optional label of the internal uniform node.
  10242. *
  10243. * @type {?string}
  10244. * @default null
  10245. */
  10246. this.name = null;
  10247. /**
  10248. * Overwritten since reference nodes are updated per object.
  10249. *
  10250. * @type {string}
  10251. * @default 'object'
  10252. */
  10253. this.updateType = NodeUpdateType.OBJECT;
  10254. }
  10255. /**
  10256. * When the referred property is array-like, this method can be used
  10257. * to access elements via an index node.
  10258. *
  10259. * @param {IndexNode} indexNode - indexNode.
  10260. * @return {ReferenceElementNode} A reference to an element.
  10261. */
  10262. element( indexNode ) {
  10263. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10264. }
  10265. /**
  10266. * Sets the uniform group for this reference node.
  10267. *
  10268. * @param {UniformGroupNode} group - The uniform group to set.
  10269. * @return {ReferenceNode} A reference to this node.
  10270. */
  10271. setGroup( group ) {
  10272. this.group = group;
  10273. return this;
  10274. }
  10275. /**
  10276. * Sets the name for the internal uniform.
  10277. *
  10278. * @param {string} name - The label to set.
  10279. * @return {ReferenceNode} A reference to this node.
  10280. */
  10281. setName( name ) {
  10282. this.name = name;
  10283. return this;
  10284. }
  10285. /**
  10286. * Sets the label for the internal uniform.
  10287. *
  10288. * @deprecated
  10289. * @param {string} name - The label to set.
  10290. * @return {ReferenceNode} A reference to this node.
  10291. */
  10292. label( name ) {
  10293. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10294. return this.setName( name );
  10295. }
  10296. /**
  10297. * Sets the node type which automatically defines the internal
  10298. * uniform type.
  10299. *
  10300. * @param {string} uniformType - The type to set.
  10301. */
  10302. setNodeType( uniformType ) {
  10303. let node = null;
  10304. if ( this.count !== null ) {
  10305. node = buffer( null, uniformType, this.count );
  10306. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10307. node = uniformArray( null, uniformType );
  10308. } else if ( uniformType === 'texture' ) {
  10309. node = texture( null );
  10310. } else if ( uniformType === 'cubeTexture' ) {
  10311. node = cubeTexture( null );
  10312. } else {
  10313. node = uniform( null, uniformType );
  10314. }
  10315. if ( this.group !== null ) {
  10316. node.setGroup( this.group );
  10317. }
  10318. if ( this.name !== null ) node.setName( this.name );
  10319. this.node = node;
  10320. }
  10321. /**
  10322. * This method is overwritten since the node type is inferred from
  10323. * the type of the reference node.
  10324. *
  10325. * @param {NodeBuilder} builder - The current node builder.
  10326. * @return {string} The node type.
  10327. */
  10328. getNodeType( builder ) {
  10329. if ( this.node === null ) {
  10330. this.updateReference( builder );
  10331. this.updateValue();
  10332. }
  10333. return this.node.getNodeType( builder );
  10334. }
  10335. /**
  10336. * Returns the property value from the given referred object.
  10337. *
  10338. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10339. * @return {any} The value.
  10340. */
  10341. getValueFromReference( object = this.reference ) {
  10342. const { properties } = this;
  10343. let value = object[ properties[ 0 ] ];
  10344. for ( let i = 1; i < properties.length; i ++ ) {
  10345. value = value[ properties[ i ] ];
  10346. }
  10347. return value;
  10348. }
  10349. /**
  10350. * Allows to update the reference based on the given state. The state is only
  10351. * evaluated {@link ReferenceNode#object} is not set.
  10352. *
  10353. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10354. * @return {Object} The updated reference.
  10355. */
  10356. updateReference( state ) {
  10357. this.reference = this.object !== null ? this.object : state.object;
  10358. return this.reference;
  10359. }
  10360. /**
  10361. * The output of the reference node is the internal uniform node.
  10362. *
  10363. * @param {NodeBuilder} builder - The current node builder.
  10364. * @return {UniformNode} The output node.
  10365. */
  10366. setup( /* builder */ ) {
  10367. this.updateValue();
  10368. return this.node;
  10369. }
  10370. /**
  10371. * Overwritten to update the internal uniform value.
  10372. *
  10373. * @param {NodeFrame} frame - A reference to the current node frame.
  10374. */
  10375. update( /*frame*/ ) {
  10376. this.updateValue();
  10377. }
  10378. /**
  10379. * Retrieves the value from the referred object property and uses it
  10380. * to updated the internal uniform.
  10381. */
  10382. updateValue() {
  10383. if ( this.node === null ) this.setNodeType( this.uniformType );
  10384. const value = this.getValueFromReference();
  10385. if ( Array.isArray( value ) ) {
  10386. this.node.array = value;
  10387. } else {
  10388. this.node.value = value;
  10389. }
  10390. }
  10391. }
  10392. /**
  10393. * TSL function for creating a reference node.
  10394. *
  10395. * @tsl
  10396. * @function
  10397. * @param {string} name - The name of the property the node refers to.
  10398. * @param {string} type - The uniform type that should be used to represent the property value.
  10399. * @param {?Object} [object] - The object the property belongs to.
  10400. * @returns {ReferenceNode}
  10401. */
  10402. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10403. /**
  10404. * TSL function for creating a reference node. Use this function if you want need a reference
  10405. * to an array-like property that should be represented as a uniform buffer.
  10406. *
  10407. * @tsl
  10408. * @function
  10409. * @param {string} name - The name of the property the node refers to.
  10410. * @param {string} type - The uniform type that should be used to represent the property value.
  10411. * @param {number} count - The number of value inside the array-like object.
  10412. * @param {Object} object - An array-like object the property belongs to.
  10413. * @returns {ReferenceNode}
  10414. */
  10415. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10416. /**
  10417. * This node is a special type of reference node which is intended
  10418. * for linking material properties with node values.
  10419. * ```js
  10420. * const opacityNode = materialReference( 'opacity', 'float', material );
  10421. * ```
  10422. * When changing `material.opacity`, the node value of `opacityNode` will
  10423. * automatically be updated.
  10424. *
  10425. * @augments ReferenceNode
  10426. */
  10427. class MaterialReferenceNode extends ReferenceNode {
  10428. static get type() {
  10429. return 'MaterialReferenceNode';
  10430. }
  10431. /**
  10432. * Constructs a new material reference node.
  10433. *
  10434. * @param {string} property - The name of the property the node refers to.
  10435. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10436. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10437. * the node refers to the material of the current rendered object.
  10438. */
  10439. constructor( property, inputType, material = null ) {
  10440. super( property, inputType, material );
  10441. /**
  10442. * The material the property belongs to. When no material is set,
  10443. * the node refers to the material of the current rendered object.
  10444. *
  10445. * @type {?Material}
  10446. * @default null
  10447. */
  10448. this.material = material;
  10449. /**
  10450. * This flag can be used for type testing.
  10451. *
  10452. * @type {boolean}
  10453. * @readonly
  10454. * @default true
  10455. */
  10456. this.isMaterialReferenceNode = true;
  10457. }
  10458. /**
  10459. * Updates the reference based on the given state. The state is only evaluated
  10460. * {@link MaterialReferenceNode#material} is not set.
  10461. *
  10462. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10463. * @return {Object} The updated reference.
  10464. */
  10465. updateReference( state ) {
  10466. this.reference = this.material !== null ? this.material : state.material;
  10467. return this.reference;
  10468. }
  10469. }
  10470. /**
  10471. * TSL function for creating a material reference node.
  10472. *
  10473. * @tsl
  10474. * @function
  10475. * @param {string} name - The name of the property the node refers to.
  10476. * @param {string} type - The uniform type that should be used to represent the property value.
  10477. * @param {?Material} [material=null] - The material the property belongs to.
  10478. * When no material is set, the node refers to the material of the current rendered object.
  10479. * @returns {MaterialReferenceNode}
  10480. */
  10481. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10482. // Normal Mapping Without Precomputed Tangents
  10483. // http://www.thetenthplanet.de/archives/1180
  10484. const uv = uv$1();
  10485. const q0 = positionView.dFdx();
  10486. const q1 = positionView.dFdy();
  10487. const st0 = uv.dFdx();
  10488. const st1 = uv.dFdy();
  10489. const N = normalView;
  10490. const q1perp = q1.cross( N );
  10491. const q0perp = N.cross( q0 );
  10492. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10493. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10494. const det = T.dot( T ).max( B.dot( B ) );
  10495. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10496. /**
  10497. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10498. * Useful for normal mapping without precomputed tangents.
  10499. *
  10500. * Reference: http://www.thetenthplanet.de/archives/1180
  10501. *
  10502. * @tsl
  10503. * @type {Node<vec3>}
  10504. */
  10505. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10506. /**
  10507. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10508. * Complements the tangentViewFrame for constructing the tangent space basis.
  10509. *
  10510. * Reference: http://www.thetenthplanet.de/archives/1180
  10511. *
  10512. * @tsl
  10513. * @type {Node<vec3>}
  10514. */
  10515. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10516. /**
  10517. * TSL object that represents the tangent attribute of the current rendered object.
  10518. *
  10519. * @tsl
  10520. * @type {Node<vec4>}
  10521. */
  10522. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10523. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10524. builder.geometry.computeTangents();
  10525. }
  10526. return attribute( 'tangent', 'vec4' );
  10527. } )();
  10528. /**
  10529. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10530. *
  10531. * @tsl
  10532. * @type {Node<vec3>}
  10533. */
  10534. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10535. /**
  10536. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10537. *
  10538. * @tsl
  10539. * @type {Node<vec3>}
  10540. */
  10541. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10542. let node;
  10543. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10544. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10545. } else {
  10546. node = tangentViewFrame;
  10547. }
  10548. if ( material.flatShading !== true ) {
  10549. node = directionToFaceDirection( node );
  10550. }
  10551. return node;
  10552. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10553. /**
  10554. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10555. *
  10556. * @tsl
  10557. * @type {Node<vec3>}
  10558. */
  10559. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10560. /**
  10561. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10562. *
  10563. * @tsl
  10564. * @private
  10565. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10566. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10567. * @returns {Node<vec3>} The bitangent node.
  10568. */
  10569. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10570. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10571. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10572. bitangent = bitangent.toVarying( varyingName );
  10573. }
  10574. return bitangent;
  10575. } ).once( [ 'NORMAL' ] );
  10576. /**
  10577. * TSL object that represents the bitangent attribute of the current rendered object.
  10578. *
  10579. * @tsl
  10580. * @type {Node<vec3>}
  10581. */
  10582. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10583. /**
  10584. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10585. *
  10586. * @tsl
  10587. * @type {Node<vec3>}
  10588. */
  10589. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10590. /**
  10591. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10592. *
  10593. * @tsl
  10594. * @type {Node<vec3>}
  10595. */
  10596. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10597. let node;
  10598. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10599. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10600. } else {
  10601. node = bitangentViewFrame;
  10602. }
  10603. if ( material.flatShading !== true ) {
  10604. node = directionToFaceDirection( node );
  10605. }
  10606. return node;
  10607. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10608. /**
  10609. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10610. *
  10611. * @tsl
  10612. * @type {Node<vec3>}
  10613. */
  10614. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10615. /**
  10616. * TSL object that represents the TBN matrix in view space.
  10617. *
  10618. * @tsl
  10619. * @type {Node<mat3>}
  10620. */
  10621. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10622. /**
  10623. * TSL object that represents the parallax direction.
  10624. *
  10625. * @tsl
  10626. * @type {Node<mat3>}
  10627. */
  10628. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10629. /**
  10630. * TSL function for computing parallax uv coordinates.
  10631. *
  10632. * @tsl
  10633. * @function
  10634. * @param {Node<vec2>} uv - A uv node.
  10635. * @param {Node<vec2>} scale - A scale node.
  10636. * @returns {Node<vec2>} Parallax uv coordinates.
  10637. */
  10638. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10639. /**
  10640. * TSL function for computing bent normals.
  10641. *
  10642. * @tsl
  10643. * @function
  10644. * @returns {Node<vec3>} Bent normals.
  10645. */
  10646. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10647. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10648. let bentNormal = anisotropyB.cross( positionViewDirection );
  10649. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10650. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10651. return bentNormal;
  10652. } ).once() )();
  10653. /**
  10654. * This class can be used for applying normals maps to materials.
  10655. *
  10656. * ```js
  10657. * material.normalNode = normalMap( texture( normalTex ) );
  10658. * ```
  10659. *
  10660. * @augments TempNode
  10661. */
  10662. class NormalMapNode extends TempNode {
  10663. static get type() {
  10664. return 'NormalMapNode';
  10665. }
  10666. /**
  10667. * Constructs a new normal map node.
  10668. *
  10669. * @param {Node<vec3>} node - Represents the normal map data.
  10670. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10671. */
  10672. constructor( node, scaleNode = null ) {
  10673. super( 'vec3' );
  10674. /**
  10675. * Represents the normal map data.
  10676. *
  10677. * @type {Node<vec3>}
  10678. */
  10679. this.node = node;
  10680. /**
  10681. * Controls the intensity of the effect.
  10682. *
  10683. * @type {?Node<vec2>}
  10684. * @default null
  10685. */
  10686. this.scaleNode = scaleNode;
  10687. /**
  10688. * The normal map type.
  10689. *
  10690. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10691. * @default TangentSpaceNormalMap
  10692. */
  10693. this.normalMapType = TangentSpaceNormalMap;
  10694. }
  10695. setup( { material } ) {
  10696. const { normalMapType, scaleNode } = this;
  10697. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10698. if ( scaleNode !== null ) {
  10699. let scale = scaleNode;
  10700. if ( material.flatShading === true ) {
  10701. scale = directionToFaceDirection( scale );
  10702. }
  10703. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10704. }
  10705. let output = null;
  10706. if ( normalMapType === ObjectSpaceNormalMap ) {
  10707. output = transformNormalToView( normalMap );
  10708. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10709. output = TBNViewMatrix.mul( normalMap ).normalize();
  10710. } else {
  10711. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10712. output = normalView; // Fallback to default normal view
  10713. }
  10714. return output;
  10715. }
  10716. }
  10717. /**
  10718. * TSL function for creating a normal map node.
  10719. *
  10720. * @tsl
  10721. * @function
  10722. * @param {Node<vec3>} node - Represents the normal map data.
  10723. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10724. * @returns {NormalMapNode}
  10725. */
  10726. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10727. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10728. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10729. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10730. // It's used to preserve the same TextureNode instance
  10731. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10732. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10733. return vec2(
  10734. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10735. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10736. ).mul( bumpScale );
  10737. } );
  10738. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10739. const perturbNormalArb = Fn( ( inputs ) => {
  10740. const { surf_pos, surf_norm, dHdxy } = inputs;
  10741. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10742. const vSigmaX = surf_pos.dFdx().normalize();
  10743. const vSigmaY = surf_pos.dFdy().normalize();
  10744. const vN = surf_norm; // normalized
  10745. const R1 = vSigmaY.cross( vN );
  10746. const R2 = vN.cross( vSigmaX );
  10747. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10748. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10749. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10750. } );
  10751. /**
  10752. * This class can be used for applying bump maps to materials.
  10753. *
  10754. * ```js
  10755. * material.normalNode = bumpMap( texture( bumpTex ) );
  10756. * ```
  10757. *
  10758. * @augments TempNode
  10759. */
  10760. class BumpMapNode extends TempNode {
  10761. static get type() {
  10762. return 'BumpMapNode';
  10763. }
  10764. /**
  10765. * Constructs a new bump map node.
  10766. *
  10767. * @param {Node<float>} textureNode - Represents the bump map data.
  10768. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10769. */
  10770. constructor( textureNode, scaleNode = null ) {
  10771. super( 'vec3' );
  10772. /**
  10773. * Represents the bump map data.
  10774. *
  10775. * @type {Node<float>}
  10776. */
  10777. this.textureNode = textureNode;
  10778. /**
  10779. * Controls the intensity of the bump effect.
  10780. *
  10781. * @type {?Node<float>}
  10782. * @default null
  10783. */
  10784. this.scaleNode = scaleNode;
  10785. }
  10786. setup() {
  10787. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10788. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10789. return perturbNormalArb( {
  10790. surf_pos: positionView,
  10791. surf_norm: normalView,
  10792. dHdxy
  10793. } );
  10794. }
  10795. }
  10796. /**
  10797. * TSL function for creating a bump map node.
  10798. *
  10799. * @tsl
  10800. * @function
  10801. * @param {Node<float>} textureNode - Represents the bump map data.
  10802. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10803. * @returns {BumpMapNode}
  10804. */
  10805. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10806. const _propertyCache = new Map();
  10807. /**
  10808. * This class should simplify the node access to material properties.
  10809. * It internal uses reference nodes to make sure changes to material
  10810. * properties are automatically reflected to predefined TSL objects
  10811. * like e.g. `materialColor`.
  10812. *
  10813. * @augments Node
  10814. */
  10815. class MaterialNode extends Node {
  10816. static get type() {
  10817. return 'MaterialNode';
  10818. }
  10819. /**
  10820. * Constructs a new material node.
  10821. *
  10822. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10823. */
  10824. constructor( scope ) {
  10825. super();
  10826. /**
  10827. * The scope defines what material property is referred by the node.
  10828. *
  10829. * @type {string}
  10830. */
  10831. this.scope = scope;
  10832. }
  10833. /**
  10834. * Returns a cached reference node for the given property and type.
  10835. *
  10836. * @param {string} property - The name of the material property.
  10837. * @param {string} type - The uniform type of the property.
  10838. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10839. */
  10840. getCache( property, type ) {
  10841. let node = _propertyCache.get( property );
  10842. if ( node === undefined ) {
  10843. node = materialReference( property, type );
  10844. _propertyCache.set( property, node );
  10845. }
  10846. return node;
  10847. }
  10848. /**
  10849. * Returns a float-typed material reference node for the given property name.
  10850. *
  10851. * @param {string} property - The name of the material property.
  10852. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10853. */
  10854. getFloat( property ) {
  10855. return this.getCache( property, 'float' );
  10856. }
  10857. /**
  10858. * Returns a color-typed material reference node for the given property name.
  10859. *
  10860. * @param {string} property - The name of the material property.
  10861. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10862. */
  10863. getColor( property ) {
  10864. return this.getCache( property, 'color' );
  10865. }
  10866. /**
  10867. * Returns a texture-typed material reference node for the given property name.
  10868. *
  10869. * @param {string} property - The name of the material property.
  10870. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10871. */
  10872. getTexture( property ) {
  10873. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10874. }
  10875. /**
  10876. * The node setup is done depending on the selected scope. Multiple material properties
  10877. * might be grouped into a single node composition if they logically belong together.
  10878. *
  10879. * @param {NodeBuilder} builder - The current node builder.
  10880. * @return {Node} The node representing the selected scope.
  10881. */
  10882. setup( builder ) {
  10883. const material = builder.context.material;
  10884. const scope = this.scope;
  10885. let node = null;
  10886. if ( scope === MaterialNode.COLOR ) {
  10887. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10888. if ( material.map && material.map.isTexture === true ) {
  10889. node = colorNode.mul( this.getTexture( 'map' ) );
  10890. } else {
  10891. node = colorNode;
  10892. }
  10893. } else if ( scope === MaterialNode.OPACITY ) {
  10894. const opacityNode = this.getFloat( scope );
  10895. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10896. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10897. } else {
  10898. node = opacityNode;
  10899. }
  10900. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10901. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10902. node = this.getTexture( 'specular' ).r;
  10903. } else {
  10904. node = float( 1 );
  10905. }
  10906. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10907. const specularIntensityNode = this.getFloat( scope );
  10908. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10909. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10910. } else {
  10911. node = specularIntensityNode;
  10912. }
  10913. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10914. const specularColorNode = this.getColor( scope );
  10915. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10916. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10917. } else {
  10918. node = specularColorNode;
  10919. }
  10920. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10921. const roughnessNode = this.getFloat( scope );
  10922. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10923. node = roughnessNode.mul( this.getTexture( scope ).g );
  10924. } else {
  10925. node = roughnessNode;
  10926. }
  10927. } else if ( scope === MaterialNode.METALNESS ) {
  10928. const metalnessNode = this.getFloat( scope );
  10929. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10930. node = metalnessNode.mul( this.getTexture( scope ).b );
  10931. } else {
  10932. node = metalnessNode;
  10933. }
  10934. } else if ( scope === MaterialNode.EMISSIVE ) {
  10935. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10936. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10937. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10938. node = emissiveNode.mul( this.getTexture( scope ) );
  10939. } else {
  10940. node = emissiveNode;
  10941. }
  10942. } else if ( scope === MaterialNode.NORMAL ) {
  10943. if ( material.normalMap ) {
  10944. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10945. node.normalMapType = material.normalMapType;
  10946. } else if ( material.bumpMap ) {
  10947. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10948. } else {
  10949. node = normalView;
  10950. }
  10951. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10952. const clearcoatNode = this.getFloat( scope );
  10953. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10954. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10955. } else {
  10956. node = clearcoatNode;
  10957. }
  10958. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10959. const clearcoatRoughnessNode = this.getFloat( scope );
  10960. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10961. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10962. } else {
  10963. node = clearcoatRoughnessNode;
  10964. }
  10965. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10966. if ( material.clearcoatNormalMap ) {
  10967. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10968. } else {
  10969. node = normalView;
  10970. }
  10971. } else if ( scope === MaterialNode.SHEEN ) {
  10972. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10973. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10974. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10975. } else {
  10976. node = sheenNode;
  10977. }
  10978. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10979. const sheenRoughnessNode = this.getFloat( scope );
  10980. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10981. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10982. } else {
  10983. node = sheenRoughnessNode;
  10984. }
  10985. node = node.clamp( 0.07, 1.0 );
  10986. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10987. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10988. const anisotropyPolar = this.getTexture( scope );
  10989. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10990. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10991. } else {
  10992. node = materialAnisotropyVector;
  10993. }
  10994. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10995. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10996. if ( material.iridescenceThicknessMap ) {
  10997. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10998. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10999. } else {
  11000. node = iridescenceThicknessMaximum;
  11001. }
  11002. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11003. const transmissionNode = this.getFloat( scope );
  11004. if ( material.transmissionMap ) {
  11005. node = transmissionNode.mul( this.getTexture( scope ).r );
  11006. } else {
  11007. node = transmissionNode;
  11008. }
  11009. } else if ( scope === MaterialNode.THICKNESS ) {
  11010. const thicknessNode = this.getFloat( scope );
  11011. if ( material.thicknessMap ) {
  11012. node = thicknessNode.mul( this.getTexture( scope ).g );
  11013. } else {
  11014. node = thicknessNode;
  11015. }
  11016. } else if ( scope === MaterialNode.IOR ) {
  11017. node = this.getFloat( scope );
  11018. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11019. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11020. } else if ( scope === MaterialNode.AO ) {
  11021. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11022. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11023. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11024. } else {
  11025. const outputType = this.getNodeType( builder );
  11026. node = this.getCache( scope, outputType );
  11027. }
  11028. return node;
  11029. }
  11030. }
  11031. MaterialNode.ALPHA_TEST = 'alphaTest';
  11032. MaterialNode.COLOR = 'color';
  11033. MaterialNode.OPACITY = 'opacity';
  11034. MaterialNode.SHININESS = 'shininess';
  11035. MaterialNode.SPECULAR = 'specular';
  11036. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11037. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11038. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11039. MaterialNode.REFLECTIVITY = 'reflectivity';
  11040. MaterialNode.ROUGHNESS = 'roughness';
  11041. MaterialNode.METALNESS = 'metalness';
  11042. MaterialNode.NORMAL = 'normal';
  11043. MaterialNode.CLEARCOAT = 'clearcoat';
  11044. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11045. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11046. MaterialNode.EMISSIVE = 'emissive';
  11047. MaterialNode.ROTATION = 'rotation';
  11048. MaterialNode.SHEEN = 'sheen';
  11049. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11050. MaterialNode.ANISOTROPY = 'anisotropy';
  11051. MaterialNode.IRIDESCENCE = 'iridescence';
  11052. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11053. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11054. MaterialNode.IOR = 'ior';
  11055. MaterialNode.TRANSMISSION = 'transmission';
  11056. MaterialNode.THICKNESS = 'thickness';
  11057. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11058. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11059. MaterialNode.LINE_SCALE = 'scale';
  11060. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11061. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11062. MaterialNode.LINE_WIDTH = 'linewidth';
  11063. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11064. MaterialNode.POINT_SIZE = 'size';
  11065. MaterialNode.DISPERSION = 'dispersion';
  11066. MaterialNode.LIGHT_MAP = 'light';
  11067. MaterialNode.AO = 'ao';
  11068. /**
  11069. * TSL object that represents alpha test of the current material.
  11070. *
  11071. * @tsl
  11072. * @type {Node<float>}
  11073. */
  11074. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11075. /**
  11076. * TSL object that represents the diffuse color of the current material.
  11077. * The value is composed via `color` * `map`.
  11078. *
  11079. * @tsl
  11080. * @type {Node<vec3>}
  11081. */
  11082. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11083. /**
  11084. * TSL object that represents the shininess of the current material.
  11085. *
  11086. * @tsl
  11087. * @type {Node<float>}
  11088. */
  11089. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11090. /**
  11091. * TSL object that represents the emissive color of the current material.
  11092. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11093. *
  11094. * @tsl
  11095. * @type {Node<vec3>}
  11096. */
  11097. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11098. /**
  11099. * TSL object that represents the opacity of the current material.
  11100. * The value is composed via `opacity` * `alphaMap`.
  11101. *
  11102. * @tsl
  11103. * @type {Node<float>}
  11104. */
  11105. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11106. /**
  11107. * TSL object that represents the specular of the current material.
  11108. *
  11109. * @tsl
  11110. * @type {Node<vec3>}
  11111. */
  11112. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11113. /**
  11114. * TSL object that represents the specular intensity of the current material.
  11115. * The value is composed via `specularIntensity` * `specularMap.a`.
  11116. *
  11117. * @tsl
  11118. * @type {Node<float>}
  11119. */
  11120. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11121. /**
  11122. * TSL object that represents the specular color of the current material.
  11123. * The value is composed via `specularColor` * `specularMap.rgb`.
  11124. *
  11125. * @tsl
  11126. * @type {Node<vec3>}
  11127. */
  11128. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11129. /**
  11130. * TSL object that represents the specular strength of the current material.
  11131. * The value is composed via `specularMap.r`.
  11132. *
  11133. * @tsl
  11134. * @type {Node<float>}
  11135. */
  11136. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11137. /**
  11138. * TSL object that represents the reflectivity of the current material.
  11139. *
  11140. * @tsl
  11141. * @type {Node<float>}
  11142. */
  11143. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11144. /**
  11145. * TSL object that represents the roughness of the current material.
  11146. * The value is composed via `roughness` * `roughnessMap.g`.
  11147. *
  11148. * @tsl
  11149. * @type {Node<float>}
  11150. */
  11151. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11152. /**
  11153. * TSL object that represents the metalness of the current material.
  11154. * The value is composed via `metalness` * `metalnessMap.b`.
  11155. *
  11156. * @tsl
  11157. * @type {Node<float>}
  11158. */
  11159. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11160. /**
  11161. * TSL object that represents the normal of the current material.
  11162. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11163. *
  11164. * @tsl
  11165. * @type {Node<vec3>}
  11166. */
  11167. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11168. /**
  11169. * TSL object that represents the clearcoat of the current material.
  11170. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11171. *
  11172. * @tsl
  11173. * @type {Node<float>}
  11174. */
  11175. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11176. /**
  11177. * TSL object that represents the clearcoat roughness of the current material.
  11178. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11179. *
  11180. * @tsl
  11181. * @type {Node<float>}
  11182. */
  11183. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11184. /**
  11185. * TSL object that represents the clearcoat normal of the current material.
  11186. * The value will be either `clearcoatNormalMap` or `normalView`.
  11187. *
  11188. * @tsl
  11189. * @type {Node<vec3>}
  11190. */
  11191. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11192. /**
  11193. * TSL object that represents the rotation of the current sprite material.
  11194. *
  11195. * @tsl
  11196. * @type {Node<float>}
  11197. */
  11198. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11199. /**
  11200. * TSL object that represents the sheen color of the current material.
  11201. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11202. *
  11203. * @tsl
  11204. * @type {Node<vec3>}
  11205. */
  11206. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11207. /**
  11208. * TSL object that represents the sheen roughness of the current material.
  11209. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11210. *
  11211. * @tsl
  11212. * @type {Node<float>}
  11213. */
  11214. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11215. /**
  11216. * TSL object that represents the anisotropy of the current material.
  11217. *
  11218. * @tsl
  11219. * @type {Node<vec2>}
  11220. */
  11221. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11222. /**
  11223. * TSL object that represents the iridescence of the current material.
  11224. *
  11225. * @tsl
  11226. * @type {Node<float>}
  11227. */
  11228. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11229. /**
  11230. * TSL object that represents the iridescence IOR of the current material.
  11231. *
  11232. * @tsl
  11233. * @type {Node<float>}
  11234. */
  11235. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11236. /**
  11237. * TSL object that represents the iridescence thickness of the current material.
  11238. *
  11239. * @tsl
  11240. * @type {Node<float>}
  11241. */
  11242. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11243. /**
  11244. * TSL object that represents the transmission of the current material.
  11245. * The value is composed via `transmission` * `transmissionMap.r`.
  11246. *
  11247. * @tsl
  11248. * @type {Node<float>}
  11249. */
  11250. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11251. /**
  11252. * TSL object that represents the thickness of the current material.
  11253. * The value is composed via `thickness` * `thicknessMap.g`.
  11254. *
  11255. * @tsl
  11256. * @type {Node<float>}
  11257. */
  11258. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11259. /**
  11260. * TSL object that represents the IOR of the current material.
  11261. *
  11262. * @tsl
  11263. * @type {Node<float>}
  11264. */
  11265. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11266. /**
  11267. * TSL object that represents the attenuation distance of the current material.
  11268. *
  11269. * @tsl
  11270. * @type {Node<float>}
  11271. */
  11272. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11273. /**
  11274. * TSL object that represents the attenuation color of the current material.
  11275. *
  11276. * @tsl
  11277. * @type {Node<vec3>}
  11278. */
  11279. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11280. /**
  11281. * TSL object that represents the scale of the current dashed line material.
  11282. *
  11283. * @tsl
  11284. * @type {Node<float>}
  11285. */
  11286. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11287. /**
  11288. * TSL object that represents the dash size of the current dashed line material.
  11289. *
  11290. * @tsl
  11291. * @type {Node<float>}
  11292. */
  11293. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11294. /**
  11295. * TSL object that represents the gap size of the current dashed line material.
  11296. *
  11297. * @tsl
  11298. * @type {Node<float>}
  11299. */
  11300. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11301. /**
  11302. * TSL object that represents the line width of the current line material.
  11303. *
  11304. * @tsl
  11305. * @type {Node<float>}
  11306. */
  11307. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11308. /**
  11309. * TSL object that represents the dash offset of the current line material.
  11310. *
  11311. * @tsl
  11312. * @type {Node<float>}
  11313. */
  11314. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11315. /**
  11316. * TSL object that represents the point size of the current points material.
  11317. *
  11318. * @tsl
  11319. * @type {Node<float>}
  11320. */
  11321. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11322. /**
  11323. * TSL object that represents the dispersion of the current material.
  11324. *
  11325. * @tsl
  11326. * @type {Node<float>}
  11327. */
  11328. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11329. /**
  11330. * TSL object that represents the light map of the current material.
  11331. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11332. *
  11333. * @tsl
  11334. * @type {Node<vec3>}
  11335. */
  11336. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11337. /**
  11338. * TSL object that represents the ambient occlusion map of the current material.
  11339. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11340. *
  11341. * @tsl
  11342. * @type {Node<float>}
  11343. */
  11344. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11345. /**
  11346. * TSL object that represents the anisotropy vector of the current material.
  11347. *
  11348. * @tsl
  11349. * @type {Node<vec2>}
  11350. */
  11351. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11352. return frame.material;
  11353. } ).onRenderUpdate( function ( { material } ) {
  11354. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11355. } );
  11356. /**
  11357. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11358. *
  11359. * @tsl
  11360. * @type {VaryingNode<vec4>}
  11361. */
  11362. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11363. return builder.context.setupModelViewProjection();
  11364. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11365. /**
  11366. * This class represents shader indices of different types. The following predefined node
  11367. * objects cover frequent use cases:
  11368. *
  11369. * - `vertexIndex`: The index of a vertex within a mesh.
  11370. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11371. * - `drawIndex`: The index of a draw call.
  11372. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11373. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11374. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  11375. *
  11376. * @augments Node
  11377. */
  11378. class IndexNode extends Node {
  11379. static get type() {
  11380. return 'IndexNode';
  11381. }
  11382. /**
  11383. * Constructs a new index node.
  11384. *
  11385. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11386. */
  11387. constructor( scope ) {
  11388. super( 'uint' );
  11389. /**
  11390. * The scope of the index node.
  11391. *
  11392. * @type {string}
  11393. */
  11394. this.scope = scope;
  11395. /**
  11396. * This flag can be used for type testing.
  11397. *
  11398. * @type {boolean}
  11399. * @readonly
  11400. * @default true
  11401. */
  11402. this.isIndexNode = true;
  11403. }
  11404. generate( builder ) {
  11405. const nodeType = this.getNodeType( builder );
  11406. const scope = this.scope;
  11407. let propertyName;
  11408. if ( scope === IndexNode.VERTEX ) {
  11409. propertyName = builder.getVertexIndex();
  11410. } else if ( scope === IndexNode.INSTANCE ) {
  11411. propertyName = builder.getInstanceIndex();
  11412. } else if ( scope === IndexNode.DRAW ) {
  11413. propertyName = builder.getDrawIndex();
  11414. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11415. propertyName = builder.getInvocationLocalIndex();
  11416. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11417. propertyName = builder.getInvocationSubgroupIndex();
  11418. } else if ( scope === IndexNode.SUBGROUP ) {
  11419. propertyName = builder.getSubgroupIndex();
  11420. } else {
  11421. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11422. }
  11423. let output;
  11424. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11425. output = propertyName;
  11426. } else {
  11427. const nodeVarying = varying( this );
  11428. output = nodeVarying.build( builder, nodeType );
  11429. }
  11430. return output;
  11431. }
  11432. }
  11433. IndexNode.VERTEX = 'vertex';
  11434. IndexNode.INSTANCE = 'instance';
  11435. IndexNode.SUBGROUP = 'subgroup';
  11436. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11437. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11438. IndexNode.DRAW = 'draw';
  11439. /**
  11440. * TSL object that represents the index of a vertex within a mesh.
  11441. *
  11442. * @tsl
  11443. * @type {IndexNode}
  11444. */
  11445. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11446. /**
  11447. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11448. *
  11449. * @tsl
  11450. * @type {IndexNode}
  11451. */
  11452. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11453. /**
  11454. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11455. *
  11456. * @tsl
  11457. * @type {IndexNode}
  11458. */
  11459. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11460. /**
  11461. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11462. *
  11463. * @tsl
  11464. * @type {IndexNode}
  11465. */
  11466. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11467. /**
  11468. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11469. *
  11470. * @tsl
  11471. * @type {IndexNode}
  11472. */
  11473. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11474. /**
  11475. * TSL object that represents the index of a draw call.
  11476. *
  11477. * @tsl
  11478. * @type {IndexNode}
  11479. */
  11480. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11481. /**
  11482. * This node implements the vertex shader logic which is required
  11483. * when rendering 3D objects via instancing. The code makes sure
  11484. * vertex positions, normals and colors can be modified via instanced
  11485. * data.
  11486. *
  11487. * @augments Node
  11488. */
  11489. class InstanceNode extends Node {
  11490. static get type() {
  11491. return 'InstanceNode';
  11492. }
  11493. /**
  11494. * Constructs a new instance node.
  11495. *
  11496. * @param {number} count - The number of instances.
  11497. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11498. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11499. */
  11500. constructor( count, instanceMatrix, instanceColor = null ) {
  11501. super( 'void' );
  11502. /**
  11503. * The number of instances.
  11504. *
  11505. * @type {number}
  11506. */
  11507. this.count = count;
  11508. /**
  11509. * Instanced buffer attribute representing the transformation of instances.
  11510. *
  11511. * @type {InstancedBufferAttribute}
  11512. */
  11513. this.instanceMatrix = instanceMatrix;
  11514. /**
  11515. * Instanced buffer attribute representing the color of instances.
  11516. *
  11517. * @type {InstancedBufferAttribute}
  11518. */
  11519. this.instanceColor = instanceColor;
  11520. /**
  11521. * The node that represents the instance matrix data.
  11522. *
  11523. * @type {?Node}
  11524. */
  11525. this.instanceMatrixNode = null;
  11526. /**
  11527. * The node that represents the instance color data.
  11528. *
  11529. * @type {?Node}
  11530. * @default null
  11531. */
  11532. this.instanceColorNode = null;
  11533. /**
  11534. * The update type is set to `frame` since an update
  11535. * of instanced buffer data must be checked per frame.
  11536. *
  11537. * @type {string}
  11538. * @default 'frame'
  11539. */
  11540. this.updateType = NodeUpdateType.FRAME;
  11541. /**
  11542. * A reference to a buffer that is used by `instanceMatrixNode`.
  11543. *
  11544. * @type {?InstancedInterleavedBuffer}
  11545. */
  11546. this.buffer = null;
  11547. /**
  11548. * A reference to a buffer that is used by `instanceColorNode`.
  11549. *
  11550. * @type {?InstancedBufferAttribute}
  11551. */
  11552. this.bufferColor = null;
  11553. }
  11554. /**
  11555. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11556. * to predefined node variables for accumulation. That follows the same patterns
  11557. * like with morph and skinning nodes.
  11558. *
  11559. * @param {NodeBuilder} builder - The current node builder.
  11560. */
  11561. setup( builder ) {
  11562. const { instanceMatrix, instanceColor } = this;
  11563. const { count } = instanceMatrix;
  11564. let { instanceMatrixNode, instanceColorNode } = this;
  11565. if ( instanceMatrixNode === null ) {
  11566. // 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.
  11567. if ( count <= 1000 ) {
  11568. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11569. } else {
  11570. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11571. this.buffer = buffer;
  11572. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11573. const instanceBuffers = [
  11574. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11575. bufferFn( buffer, 'vec4', 16, 0 ),
  11576. bufferFn( buffer, 'vec4', 16, 4 ),
  11577. bufferFn( buffer, 'vec4', 16, 8 ),
  11578. bufferFn( buffer, 'vec4', 16, 12 )
  11579. ];
  11580. instanceMatrixNode = mat4( ...instanceBuffers );
  11581. }
  11582. this.instanceMatrixNode = instanceMatrixNode;
  11583. }
  11584. if ( instanceColor && instanceColorNode === null ) {
  11585. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11586. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11587. this.bufferColor = buffer;
  11588. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11589. this.instanceColorNode = instanceColorNode;
  11590. }
  11591. // POSITION
  11592. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11593. positionLocal.assign( instancePosition );
  11594. // NORMAL
  11595. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11596. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11597. // ASSIGNS
  11598. normalLocal.assign( instanceNormal );
  11599. }
  11600. // COLOR
  11601. if ( this.instanceColorNode !== null ) {
  11602. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11603. }
  11604. }
  11605. /**
  11606. * Checks if the internal buffers required an update.
  11607. *
  11608. * @param {NodeFrame} frame - The current node frame.
  11609. */
  11610. update( /*frame*/ ) {
  11611. if ( this.buffer !== null ) {
  11612. // keep update ranges in sync
  11613. this.buffer.clearUpdateRanges();
  11614. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11615. // update version if necessary
  11616. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11617. this.buffer.version = this.instanceMatrix.version;
  11618. }
  11619. }
  11620. if ( this.instanceColor && this.bufferColor !== null ) {
  11621. this.bufferColor.clearUpdateRanges();
  11622. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11623. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11624. this.bufferColor.version = this.instanceColor.version;
  11625. }
  11626. }
  11627. }
  11628. }
  11629. /**
  11630. * TSL function for creating an instance node.
  11631. *
  11632. * @tsl
  11633. * @function
  11634. * @param {number} count - The number of instances.
  11635. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11636. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11637. * @returns {InstanceNode}
  11638. */
  11639. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11640. /**
  11641. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11642. * It allows an easier setup of the instance node.
  11643. *
  11644. * @augments InstanceNode
  11645. */
  11646. class InstancedMeshNode extends InstanceNode {
  11647. static get type() {
  11648. return 'InstancedMeshNode';
  11649. }
  11650. /**
  11651. * Constructs a new instanced mesh node.
  11652. *
  11653. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11654. */
  11655. constructor( instancedMesh ) {
  11656. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11657. super( count, instanceMatrix, instanceColor );
  11658. /**
  11659. * A reference to the instanced mesh.
  11660. *
  11661. * @type {InstancedMesh}
  11662. */
  11663. this.instancedMesh = instancedMesh;
  11664. }
  11665. }
  11666. /**
  11667. * TSL function for creating an instanced mesh node.
  11668. *
  11669. * @tsl
  11670. * @function
  11671. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11672. * @returns {InstancedMeshNode}
  11673. */
  11674. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11675. /**
  11676. * This node implements the vertex shader logic which is required
  11677. * when rendering 3D objects via batching. `BatchNode` must be used
  11678. * with instances of {@link BatchedMesh}.
  11679. *
  11680. * @augments Node
  11681. */
  11682. class BatchNode extends Node {
  11683. static get type() {
  11684. return 'BatchNode';
  11685. }
  11686. /**
  11687. * Constructs a new batch node.
  11688. *
  11689. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11690. */
  11691. constructor( batchMesh ) {
  11692. super( 'void' );
  11693. /**
  11694. * A reference to batched mesh.
  11695. *
  11696. * @type {BatchedMesh}
  11697. */
  11698. this.batchMesh = batchMesh;
  11699. /**
  11700. * The batching index node.
  11701. *
  11702. * @type {?IndexNode}
  11703. * @default null
  11704. */
  11705. this.batchingIdNode = null;
  11706. }
  11707. /**
  11708. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11709. * to predefined node variables for accumulation. That follows the same patterns
  11710. * like with morph and skinning nodes.
  11711. *
  11712. * @param {NodeBuilder} builder - The current node builder.
  11713. */
  11714. setup( builder ) {
  11715. if ( this.batchingIdNode === null ) {
  11716. if ( builder.getDrawIndex() === null ) {
  11717. this.batchingIdNode = instanceIndex;
  11718. } else {
  11719. this.batchingIdNode = drawIndex;
  11720. }
  11721. }
  11722. const getIndirectIndex = Fn( ( [ id ] ) => {
  11723. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11724. const x = int( id ).mod( size );
  11725. const y = int( id ).div( size );
  11726. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11727. } ).setLayout( {
  11728. name: 'getIndirectIndex',
  11729. type: 'uint',
  11730. inputs: [
  11731. { name: 'id', type: 'int' }
  11732. ]
  11733. } );
  11734. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11735. const matricesTexture = this.batchMesh._matricesTexture;
  11736. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11737. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11738. const x = j.mod( size );
  11739. const y = j.div( size );
  11740. const batchingMatrix = mat4(
  11741. textureLoad( matricesTexture, ivec2( x, y ) ),
  11742. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11743. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11744. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11745. );
  11746. const colorsTexture = this.batchMesh._colorsTexture;
  11747. if ( colorsTexture !== null ) {
  11748. const getBatchingColor = Fn( ( [ id ] ) => {
  11749. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11750. const j = id;
  11751. const x = j.mod( size );
  11752. const y = j.div( size );
  11753. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11754. } ).setLayout( {
  11755. name: 'getBatchingColor',
  11756. type: 'vec3',
  11757. inputs: [
  11758. { name: 'id', type: 'int' }
  11759. ]
  11760. } );
  11761. const color = getBatchingColor( indirectId );
  11762. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11763. }
  11764. const bm = mat3( batchingMatrix );
  11765. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11766. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11767. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11768. normalLocal.assign( batchingNormal );
  11769. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11770. tangentLocal.mulAssign( bm );
  11771. }
  11772. }
  11773. }
  11774. /**
  11775. * TSL function for creating a batch node.
  11776. *
  11777. * @tsl
  11778. * @function
  11779. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11780. * @returns {BatchNode}
  11781. */
  11782. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11783. /**
  11784. * This class enables element access on instances of {@link StorageBufferNode}.
  11785. * In most cases, it is indirectly used when accessing elements with the
  11786. * {@link StorageBufferNode#element} method.
  11787. *
  11788. * ```js
  11789. * const position = positionStorage.element( instanceIndex );
  11790. * ```
  11791. *
  11792. * @augments ArrayElementNode
  11793. */
  11794. class StorageArrayElementNode extends ArrayElementNode {
  11795. static get type() {
  11796. return 'StorageArrayElementNode';
  11797. }
  11798. /**
  11799. * Constructs storage buffer element node.
  11800. *
  11801. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11802. * @param {Node} indexNode - The index node that defines the element access.
  11803. */
  11804. constructor( storageBufferNode, indexNode ) {
  11805. super( storageBufferNode, indexNode );
  11806. /**
  11807. * This flag can be used for type testing.
  11808. *
  11809. * @type {boolean}
  11810. * @readonly
  11811. * @default true
  11812. */
  11813. this.isStorageArrayElementNode = true;
  11814. }
  11815. /**
  11816. * The storage buffer node.
  11817. *
  11818. * @param {Node} value
  11819. * @type {StorageBufferNode}
  11820. */
  11821. set storageBufferNode( value ) {
  11822. this.node = value;
  11823. }
  11824. get storageBufferNode() {
  11825. return this.node;
  11826. }
  11827. getMemberType( builder, name ) {
  11828. const structTypeNode = this.storageBufferNode.structTypeNode;
  11829. if ( structTypeNode ) {
  11830. return structTypeNode.getMemberType( builder, name );
  11831. }
  11832. return 'void';
  11833. }
  11834. setup( builder ) {
  11835. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11836. if ( this.node.isPBO === true ) {
  11837. builder.setupPBO( this.node );
  11838. }
  11839. }
  11840. return super.setup( builder );
  11841. }
  11842. generate( builder, output ) {
  11843. let snippet;
  11844. const isAssignContext = builder.context.assign;
  11845. //
  11846. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11847. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11848. snippet = builder.generatePBO( this );
  11849. } else {
  11850. snippet = this.node.build( builder );
  11851. }
  11852. } else {
  11853. snippet = super.generate( builder );
  11854. }
  11855. if ( isAssignContext !== true ) {
  11856. const type = this.getNodeType( builder );
  11857. snippet = builder.format( snippet, type, output );
  11858. }
  11859. return snippet;
  11860. }
  11861. }
  11862. /**
  11863. * TSL function for creating a storage element node.
  11864. *
  11865. * @tsl
  11866. * @function
  11867. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11868. * @param {Node} indexNode - The index node that defines the element access.
  11869. * @returns {StorageArrayElementNode}
  11870. */
  11871. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11872. /**
  11873. * This node is used in context of compute shaders and allows to define a
  11874. * storage buffer for data. A typical workflow is to create instances of
  11875. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11876. * setup up a compute shader that writes into the buffers and then convert
  11877. * the storage buffers to attribute nodes for rendering.
  11878. *
  11879. * ```js
  11880. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11881. *
  11882. * const computeInit = Fn( () => { // the compute shader
  11883. *
  11884. * const position = positionBuffer.element( instanceIndex );
  11885. *
  11886. * // compute position data
  11887. *
  11888. * position.x = 1;
  11889. * position.y = 1;
  11890. * position.z = 1;
  11891. *
  11892. * } )().compute( particleCount );
  11893. *
  11894. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11895. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11896. *
  11897. * renderer.computeAsync( computeInit );
  11898. *
  11899. * ```
  11900. *
  11901. * @augments BufferNode
  11902. */
  11903. class StorageBufferNode extends BufferNode {
  11904. static get type() {
  11905. return 'StorageBufferNode';
  11906. }
  11907. /**
  11908. * Constructs a new storage buffer node.
  11909. *
  11910. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11911. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11912. * @param {number} [bufferCount=0] - The buffer count.
  11913. */
  11914. constructor( value, bufferType = null, bufferCount = 0 ) {
  11915. let nodeType, structTypeNode = null;
  11916. if ( bufferType && bufferType.isStruct ) {
  11917. nodeType = 'struct';
  11918. structTypeNode = bufferType.layout;
  11919. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11920. bufferCount = value.count;
  11921. }
  11922. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11923. nodeType = getTypeFromLength( value.itemSize );
  11924. bufferCount = value.count;
  11925. } else {
  11926. nodeType = bufferType;
  11927. }
  11928. super( value, nodeType, bufferCount );
  11929. /**
  11930. * This flag can be used for type testing.
  11931. *
  11932. * @type {boolean}
  11933. * @readonly
  11934. * @default true
  11935. */
  11936. this.isStorageBufferNode = true;
  11937. /**
  11938. * The buffer struct type.
  11939. *
  11940. * @type {?StructTypeNode}
  11941. * @default null
  11942. */
  11943. this.structTypeNode = structTypeNode;
  11944. /**
  11945. * The access type of the texture node.
  11946. *
  11947. * @type {string}
  11948. * @default 'readWrite'
  11949. */
  11950. this.access = NodeAccess.READ_WRITE;
  11951. /**
  11952. * Whether the node is atomic or not.
  11953. *
  11954. * @type {boolean}
  11955. * @default false
  11956. */
  11957. this.isAtomic = false;
  11958. /**
  11959. * Whether the node represents a PBO or not.
  11960. * Only relevant for WebGL.
  11961. *
  11962. * @type {boolean}
  11963. * @default false
  11964. */
  11965. this.isPBO = false;
  11966. /**
  11967. * A reference to the internal buffer attribute node.
  11968. *
  11969. * @type {?BufferAttributeNode}
  11970. * @default null
  11971. */
  11972. this._attribute = null;
  11973. /**
  11974. * A reference to the internal varying node.
  11975. *
  11976. * @type {?VaryingNode}
  11977. * @default null
  11978. */
  11979. this._varying = null;
  11980. /**
  11981. * `StorageBufferNode` sets this property to `true` by default.
  11982. *
  11983. * @type {boolean}
  11984. * @default true
  11985. */
  11986. this.global = true;
  11987. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11988. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11989. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11990. else value.isStorageBufferAttribute = true;
  11991. }
  11992. }
  11993. /**
  11994. * This method is overwritten since the buffer data might be shared
  11995. * and thus the hash should be shared as well.
  11996. *
  11997. * @param {NodeBuilder} builder - The current node builder.
  11998. * @return {string} The hash.
  11999. */
  12000. getHash( builder ) {
  12001. if ( this.bufferCount === 0 ) {
  12002. let bufferData = builder.globalCache.getData( this.value );
  12003. if ( bufferData === undefined ) {
  12004. bufferData = {
  12005. node: this
  12006. };
  12007. builder.globalCache.setData( this.value, bufferData );
  12008. }
  12009. return bufferData.node.uuid;
  12010. }
  12011. return this.uuid;
  12012. }
  12013. /**
  12014. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12015. *
  12016. * @param {NodeBuilder} builder - The current node builder.
  12017. * @return {string} The input type.
  12018. */
  12019. getInputType( /*builder*/ ) {
  12020. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12021. }
  12022. /**
  12023. * Enables element access with the given index node.
  12024. *
  12025. * @param {IndexNode} indexNode - The index node.
  12026. * @return {StorageArrayElementNode} A node representing the element access.
  12027. */
  12028. element( indexNode ) {
  12029. return storageElement( this, indexNode );
  12030. }
  12031. /**
  12032. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12033. *
  12034. * @param {boolean} value - The value so set.
  12035. * @return {StorageBufferNode} A reference to this node.
  12036. */
  12037. setPBO( value ) {
  12038. this.isPBO = value;
  12039. return this;
  12040. }
  12041. /**
  12042. * Returns the `isPBO` value.
  12043. *
  12044. * @return {boolean} Whether the node represents a PBO or not.
  12045. */
  12046. getPBO() {
  12047. return this.isPBO;
  12048. }
  12049. /**
  12050. * Defines the node access.
  12051. *
  12052. * @param {string} value - The node access.
  12053. * @return {StorageBufferNode} A reference to this node.
  12054. */
  12055. setAccess( value ) {
  12056. this.access = value;
  12057. return this;
  12058. }
  12059. /**
  12060. * Convenience method for configuring a read-only node access.
  12061. *
  12062. * @return {StorageBufferNode} A reference to this node.
  12063. */
  12064. toReadOnly() {
  12065. return this.setAccess( NodeAccess.READ_ONLY );
  12066. }
  12067. /**
  12068. * Defines whether the node is atomic or not.
  12069. *
  12070. * @param {boolean} value - The atomic flag.
  12071. * @return {StorageBufferNode} A reference to this node.
  12072. */
  12073. setAtomic( value ) {
  12074. this.isAtomic = value;
  12075. return this;
  12076. }
  12077. /**
  12078. * Convenience method for making this node atomic.
  12079. *
  12080. * @return {StorageBufferNode} A reference to this node.
  12081. */
  12082. toAtomic() {
  12083. return this.setAtomic( true );
  12084. }
  12085. /**
  12086. * Returns attribute data for this storage buffer node.
  12087. *
  12088. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12089. */
  12090. getAttributeData() {
  12091. if ( this._attribute === null ) {
  12092. this._attribute = bufferAttribute( this.value );
  12093. this._varying = varying( this._attribute );
  12094. }
  12095. return {
  12096. attribute: this._attribute,
  12097. varying: this._varying
  12098. };
  12099. }
  12100. /**
  12101. * This method is overwritten since the node type from the availability of storage buffers
  12102. * and the attribute data.
  12103. *
  12104. * @param {NodeBuilder} builder - The current node builder.
  12105. * @return {string} The node type.
  12106. */
  12107. getNodeType( builder ) {
  12108. if ( this.structTypeNode !== null ) {
  12109. return this.structTypeNode.getNodeType( builder );
  12110. }
  12111. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12112. return super.getNodeType( builder );
  12113. }
  12114. const { attribute } = this.getAttributeData();
  12115. return attribute.getNodeType( builder );
  12116. }
  12117. /**
  12118. * Returns the type of a member of the struct.
  12119. *
  12120. * @param {NodeBuilder} builder - The current node builder.
  12121. * @param {string} name - The name of the member.
  12122. * @return {string} The type of the member.
  12123. */
  12124. getMemberType( builder, name ) {
  12125. if ( this.structTypeNode !== null ) {
  12126. return this.structTypeNode.getMemberType( builder, name );
  12127. }
  12128. return 'void';
  12129. }
  12130. /**
  12131. * Generates the code snippet of the storage buffer node.
  12132. *
  12133. * @param {NodeBuilder} builder - The current node builder.
  12134. * @return {string} The generated code snippet.
  12135. */
  12136. generate( builder ) {
  12137. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12138. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12139. return super.generate( builder );
  12140. }
  12141. const { attribute, varying } = this.getAttributeData();
  12142. const output = varying.build( builder );
  12143. builder.registerTransform( output, attribute );
  12144. return output;
  12145. }
  12146. }
  12147. /**
  12148. * TSL function for creating a storage buffer node.
  12149. *
  12150. * @tsl
  12151. * @function
  12152. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12153. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12154. * @param {number} [count=0] - The buffer count.
  12155. * @returns {StorageBufferNode}
  12156. */
  12157. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12158. /**
  12159. * @tsl
  12160. * @function
  12161. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12162. *
  12163. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12164. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12165. * @param {number} count - The buffer count.
  12166. * @returns {StorageBufferNode}
  12167. */
  12168. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12169. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12170. return storage( value, type, count ).setPBO( true );
  12171. };
  12172. const _frameId = new WeakMap();
  12173. /**
  12174. * This node implements the vertex transformation shader logic which is required
  12175. * for skinning/skeletal animation.
  12176. *
  12177. * @augments Node
  12178. */
  12179. class SkinningNode extends Node {
  12180. static get type() {
  12181. return 'SkinningNode';
  12182. }
  12183. /**
  12184. * Constructs a new skinning node.
  12185. *
  12186. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12187. */
  12188. constructor( skinnedMesh ) {
  12189. super( 'void' );
  12190. /**
  12191. * The skinned mesh.
  12192. *
  12193. * @type {SkinnedMesh}
  12194. */
  12195. this.skinnedMesh = skinnedMesh;
  12196. /**
  12197. * The update type overwritten since skinning nodes are updated per object.
  12198. *
  12199. * @type {string}
  12200. */
  12201. this.updateType = NodeUpdateType.OBJECT;
  12202. //
  12203. /**
  12204. * The skin index attribute.
  12205. *
  12206. * @type {AttributeNode}
  12207. */
  12208. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12209. /**
  12210. * The skin weight attribute.
  12211. *
  12212. * @type {AttributeNode}
  12213. */
  12214. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12215. /**
  12216. * The bind matrix node.
  12217. *
  12218. * @type {Node<mat4>}
  12219. */
  12220. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12221. /**
  12222. * The bind matrix inverse node.
  12223. *
  12224. * @type {Node<mat4>}
  12225. */
  12226. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12227. /**
  12228. * The bind matrices as a uniform buffer node.
  12229. *
  12230. * @type {Node}
  12231. */
  12232. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12233. /**
  12234. * The current vertex position in local space.
  12235. *
  12236. * @type {Node<vec3>}
  12237. */
  12238. this.positionNode = positionLocal;
  12239. /**
  12240. * The result of vertex position in local space.
  12241. *
  12242. * @type {Node<vec3>}
  12243. */
  12244. this.toPositionNode = positionLocal;
  12245. /**
  12246. * The previous bind matrices as a uniform buffer node.
  12247. * Required for computing motion vectors.
  12248. *
  12249. * @type {?Node}
  12250. * @default null
  12251. */
  12252. this.previousBoneMatricesNode = null;
  12253. }
  12254. /**
  12255. * Transforms the given vertex position via skinning.
  12256. *
  12257. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12258. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12259. * @return {Node<vec3>} The transformed vertex position.
  12260. */
  12261. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12262. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12263. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12264. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12265. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12266. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12267. // POSITION
  12268. const skinVertex = bindMatrixNode.mul( position );
  12269. const skinned = add(
  12270. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12271. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12272. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12273. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12274. );
  12275. return bindMatrixInverseNode.mul( skinned ).xyz;
  12276. }
  12277. /**
  12278. * Transforms the given vertex normal via skinning.
  12279. *
  12280. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12281. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12282. * @return {Node<vec3>} The transformed vertex normal.
  12283. */
  12284. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12285. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12286. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12287. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12288. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12289. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12290. // NORMAL
  12291. let skinMatrix = add(
  12292. skinWeightNode.x.mul( boneMatX ),
  12293. skinWeightNode.y.mul( boneMatY ),
  12294. skinWeightNode.z.mul( boneMatZ ),
  12295. skinWeightNode.w.mul( boneMatW )
  12296. );
  12297. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12298. return skinMatrix.transformDirection( normal ).xyz;
  12299. }
  12300. /**
  12301. * Computes the transformed/skinned vertex position of the previous frame.
  12302. *
  12303. * @param {NodeBuilder} builder - The current node builder.
  12304. * @return {Node<vec3>} The skinned position from the previous frame.
  12305. */
  12306. getPreviousSkinnedPosition( builder ) {
  12307. const skinnedMesh = builder.object;
  12308. if ( this.previousBoneMatricesNode === null ) {
  12309. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12310. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12311. }
  12312. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12313. }
  12314. /**
  12315. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12316. * when computing motion vectors with {@link VelocityNode}.
  12317. *
  12318. * @param {NodeBuilder} builder - The current node builder.
  12319. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12320. */
  12321. needsPreviousBoneMatrices( builder ) {
  12322. const mrt = builder.renderer.getMRT();
  12323. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12324. }
  12325. /**
  12326. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12327. *
  12328. * @param {NodeBuilder} builder - The current node builder.
  12329. * @return {Node<vec3>} The transformed vertex position.
  12330. */
  12331. setup( builder ) {
  12332. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12333. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12334. }
  12335. const skinPosition = this.getSkinnedPosition();
  12336. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12337. //
  12338. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12339. const skinNormal = this.getSkinnedNormal();
  12340. normalLocal.assign( skinNormal );
  12341. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12342. tangentLocal.assign( skinNormal );
  12343. }
  12344. }
  12345. return skinPosition;
  12346. }
  12347. /**
  12348. * Generates the code snippet of the skinning node.
  12349. *
  12350. * @param {NodeBuilder} builder - The current node builder.
  12351. * @param {string} output - The current output.
  12352. * @return {string} The generated code snippet.
  12353. */
  12354. generate( builder, output ) {
  12355. if ( output !== 'void' ) {
  12356. return super.generate( builder, output );
  12357. }
  12358. }
  12359. /**
  12360. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12361. *
  12362. * @param {NodeFrame} frame - The current node frame.
  12363. */
  12364. update( frame ) {
  12365. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12366. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12367. _frameId.set( skeleton, frame.frameId );
  12368. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12369. skeleton.update();
  12370. }
  12371. }
  12372. /**
  12373. * TSL function for creating a skinning node.
  12374. *
  12375. * @tsl
  12376. * @function
  12377. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12378. * @returns {SkinningNode}
  12379. */
  12380. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12381. /**
  12382. * TSL function for computing skinning.
  12383. *
  12384. * @tsl
  12385. * @function
  12386. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12387. * @param {Node<vec3>} [toPosition=null] - The target position.
  12388. * @returns {SkinningNode}
  12389. */
  12390. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12391. const node = new SkinningNode( skinnedMesh );
  12392. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12393. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12394. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12395. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12396. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12397. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12398. node.toPositionNode = toPosition;
  12399. return nodeObject( node );
  12400. };
  12401. /**
  12402. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12403. * ```js
  12404. * Loop( count, ( { i } ) => {
  12405. *
  12406. * } );
  12407. * ```
  12408. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12409. * ```js
  12410. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12411. *
  12412. * } );
  12413. *```
  12414. * Nested loops can be defined in a compacted form:
  12415. * ```js
  12416. * Loop( 10, 5, ( { i, j } ) => {
  12417. *
  12418. * } );
  12419. * ```
  12420. * Loops that should run backwards can be defined like so:
  12421. * ```js
  12422. * Loop( { start: 10 }, () => {} );
  12423. * ```
  12424. * It is possible to execute with boolean values, similar to the `while` syntax.
  12425. * ```js
  12426. * const value = float( 0 ).toVar();
  12427. *
  12428. * Loop( value.lessThan( 10 ), () => {
  12429. *
  12430. * value.addAssign( 1 );
  12431. *
  12432. * } );
  12433. * ```
  12434. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12435. * @augments Node
  12436. */
  12437. class LoopNode extends Node {
  12438. static get type() {
  12439. return 'LoopNode';
  12440. }
  12441. /**
  12442. * Constructs a new loop node.
  12443. *
  12444. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12445. */
  12446. constructor( params = [] ) {
  12447. super();
  12448. this.params = params;
  12449. }
  12450. /**
  12451. * Returns a loop variable name based on an index. The pattern is
  12452. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12453. *
  12454. * @param {number} index - The index.
  12455. * @return {string} The loop variable name.
  12456. */
  12457. getVarName( index ) {
  12458. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12459. }
  12460. /**
  12461. * Returns properties about this node.
  12462. *
  12463. * @param {NodeBuilder} builder - The current node builder.
  12464. * @return {Object} The node properties.
  12465. */
  12466. getProperties( builder ) {
  12467. const properties = builder.getNodeProperties( this );
  12468. if ( properties.stackNode !== undefined ) return properties;
  12469. //
  12470. const inputs = {};
  12471. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12472. const param = this.params[ i ];
  12473. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12474. const type = ( param.isNode !== true && param.type ) || 'int';
  12475. inputs[ name ] = expression( name, type );
  12476. }
  12477. const stack = builder.addStack(); // TODO: cache() it
  12478. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12479. properties.stackNode = stack;
  12480. const baseParam = this.params[ 0 ];
  12481. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12482. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12483. }
  12484. builder.removeStack();
  12485. return properties;
  12486. }
  12487. /**
  12488. * This method is overwritten since the node type is inferred based on the loop configuration.
  12489. *
  12490. * @param {NodeBuilder} builder - The current node builder.
  12491. * @return {string} The node type.
  12492. */
  12493. getNodeType( builder ) {
  12494. const { returnsNode } = this.getProperties( builder );
  12495. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12496. }
  12497. setup( builder ) {
  12498. // setup properties
  12499. this.getProperties( builder );
  12500. if ( builder.fnCall ) {
  12501. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12502. shaderNodeData.hasLoop = true;
  12503. }
  12504. }
  12505. generate( builder ) {
  12506. const properties = this.getProperties( builder );
  12507. const params = this.params;
  12508. const stackNode = properties.stackNode;
  12509. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12510. const param = params[ i ];
  12511. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12512. if ( param.isNode ) {
  12513. if ( param.getNodeType( builder ) === 'bool' ) {
  12514. isWhile = true;
  12515. type = 'bool';
  12516. end = param.build( builder, type );
  12517. } else {
  12518. type = 'int';
  12519. name = this.getVarName( i );
  12520. start = '0';
  12521. end = param.build( builder, type );
  12522. condition = '<';
  12523. }
  12524. } else {
  12525. type = param.type || 'int';
  12526. name = param.name || this.getVarName( i );
  12527. start = param.start;
  12528. end = param.end;
  12529. condition = param.condition;
  12530. update = param.update;
  12531. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12532. else if ( start && start.isNode ) start = start.build( builder, type );
  12533. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12534. else if ( end && end.isNode ) end = end.build( builder, type );
  12535. if ( start !== undefined && end === undefined ) {
  12536. start = start + ' - 1';
  12537. end = '0';
  12538. condition = '>=';
  12539. } else if ( end !== undefined && start === undefined ) {
  12540. start = '0';
  12541. condition = '<';
  12542. }
  12543. if ( condition === undefined ) {
  12544. if ( Number( start ) > Number( end ) ) {
  12545. condition = '>=';
  12546. } else {
  12547. condition = '<';
  12548. }
  12549. }
  12550. }
  12551. let loopSnippet;
  12552. if ( isWhile ) {
  12553. loopSnippet = `while ( ${ end } )`;
  12554. } else {
  12555. const internalParam = { start, end};
  12556. //
  12557. const startSnippet = internalParam.start;
  12558. const endSnippet = internalParam.end;
  12559. let updateSnippet;
  12560. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12561. if ( update !== undefined && update !== null ) {
  12562. switch ( typeof update ) {
  12563. case 'function':
  12564. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12565. const snippet = flow.code.replace( /\t|;/g, '' );
  12566. updateSnippet = snippet;
  12567. break;
  12568. case 'number':
  12569. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12570. break;
  12571. case 'string':
  12572. updateSnippet = name + ' ' + update;
  12573. break;
  12574. default:
  12575. if ( update.isNode ) {
  12576. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12577. } else {
  12578. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12579. updateSnippet = 'break /* invalid update */';
  12580. }
  12581. }
  12582. } else {
  12583. if ( type === 'int' || type === 'uint' ) {
  12584. update = condition.includes( '<' ) ? '++' : '--';
  12585. } else {
  12586. update = deltaOperator() + ' 1.';
  12587. }
  12588. updateSnippet = name + ' ' + update;
  12589. }
  12590. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12591. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12592. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12593. }
  12594. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12595. }
  12596. const stackSnippet = stackNode.build( builder, 'void' );
  12597. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12598. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12599. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12600. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12601. }
  12602. builder.addFlowTab();
  12603. return returnsSnippet;
  12604. }
  12605. }
  12606. /**
  12607. * TSL function for creating a loop node.
  12608. *
  12609. * @tsl
  12610. * @function
  12611. * @param {...any} params - A list of parameters.
  12612. * @returns {LoopNode}
  12613. */
  12614. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12615. /**
  12616. * TSL function for creating a `Continue()` expression.
  12617. *
  12618. * @tsl
  12619. * @function
  12620. * @returns {ExpressionNode}
  12621. */
  12622. const Continue = () => expression( 'continue' ).toStack();
  12623. /**
  12624. * TSL function for creating a `Break()` expression.
  12625. *
  12626. * @tsl
  12627. * @function
  12628. * @returns {ExpressionNode}
  12629. */
  12630. const Break = () => expression( 'break' ).toStack();
  12631. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12632. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12633. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12634. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12635. const y = texelIndex.div( width );
  12636. const x = texelIndex.sub( y.mul( width ) );
  12637. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12638. return bufferAttrib.mul( influence );
  12639. } );
  12640. function getEntry( geometry ) {
  12641. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12642. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12643. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12644. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12645. // into an array of data textures. Each layer represents a single morph target.
  12646. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12647. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12648. let entry = _morphTextures.get( geometry );
  12649. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12650. if ( entry !== undefined ) entry.texture.dispose();
  12651. const morphTargets = geometry.morphAttributes.position || [];
  12652. const morphNormals = geometry.morphAttributes.normal || [];
  12653. const morphColors = geometry.morphAttributes.color || [];
  12654. let vertexDataCount = 0;
  12655. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12656. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12657. if ( hasMorphColors === true ) vertexDataCount = 3;
  12658. let width = geometry.attributes.position.count * vertexDataCount;
  12659. let height = 1;
  12660. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12661. if ( width > maxTextureSize ) {
  12662. height = Math.ceil( width / maxTextureSize );
  12663. width = maxTextureSize;
  12664. }
  12665. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12666. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12667. bufferTexture.type = FloatType;
  12668. bufferTexture.needsUpdate = true;
  12669. // fill buffer
  12670. const vertexDataStride = vertexDataCount * 4;
  12671. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12672. const morphTarget = morphTargets[ i ];
  12673. const morphNormal = morphNormals[ i ];
  12674. const morphColor = morphColors[ i ];
  12675. const offset = width * height * 4 * i;
  12676. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12677. const stride = j * vertexDataStride;
  12678. if ( hasMorphPosition === true ) {
  12679. _morphVec4.fromBufferAttribute( morphTarget, j );
  12680. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12681. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12682. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12683. buffer[ offset + stride + 3 ] = 0;
  12684. }
  12685. if ( hasMorphNormals === true ) {
  12686. _morphVec4.fromBufferAttribute( morphNormal, j );
  12687. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12688. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12689. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12690. buffer[ offset + stride + 7 ] = 0;
  12691. }
  12692. if ( hasMorphColors === true ) {
  12693. _morphVec4.fromBufferAttribute( morphColor, j );
  12694. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12695. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12696. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12697. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12698. }
  12699. }
  12700. }
  12701. entry = {
  12702. count: morphTargetsCount,
  12703. texture: bufferTexture,
  12704. stride: vertexDataCount,
  12705. size: new Vector2( width, height )
  12706. };
  12707. _morphTextures.set( geometry, entry );
  12708. function disposeTexture() {
  12709. bufferTexture.dispose();
  12710. _morphTextures.delete( geometry );
  12711. geometry.removeEventListener( 'dispose', disposeTexture );
  12712. }
  12713. geometry.addEventListener( 'dispose', disposeTexture );
  12714. }
  12715. return entry;
  12716. }
  12717. /**
  12718. * This node implements the vertex transformation shader logic which is required
  12719. * for morph target animation.
  12720. *
  12721. * @augments Node
  12722. */
  12723. class MorphNode extends Node {
  12724. static get type() {
  12725. return 'MorphNode';
  12726. }
  12727. /**
  12728. * Constructs a new morph node.
  12729. *
  12730. * @param {Mesh} mesh - The mesh holding the morph targets.
  12731. */
  12732. constructor( mesh ) {
  12733. super( 'void' );
  12734. /**
  12735. * The mesh holding the morph targets.
  12736. *
  12737. * @type {Mesh}
  12738. */
  12739. this.mesh = mesh;
  12740. /**
  12741. * A uniform node which represents the morph base influence value.
  12742. *
  12743. * @type {UniformNode<float>}
  12744. */
  12745. this.morphBaseInfluence = uniform( 1 );
  12746. /**
  12747. * The update type overwritten since morph nodes are updated per object.
  12748. *
  12749. * @type {string}
  12750. */
  12751. this.updateType = NodeUpdateType.OBJECT;
  12752. }
  12753. /**
  12754. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12755. *
  12756. * @param {NodeBuilder} builder - The current node builder.
  12757. */
  12758. setup( builder ) {
  12759. const { geometry } = builder;
  12760. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12761. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12762. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12763. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12764. // nodes
  12765. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12766. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12767. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12768. const width = int( size.width );
  12769. Loop( morphTargetsCount, ( { i } ) => {
  12770. const influence = float( 0 ).toVar();
  12771. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12772. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12773. } else {
  12774. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12775. }
  12776. If( influence.notEqual( 0 ), () => {
  12777. if ( hasMorphPosition === true ) {
  12778. positionLocal.addAssign( getMorph( {
  12779. bufferMap,
  12780. influence,
  12781. stride,
  12782. width,
  12783. depth: i,
  12784. offset: int( 0 )
  12785. } ) );
  12786. }
  12787. if ( hasMorphNormals === true ) {
  12788. normalLocal.addAssign( getMorph( {
  12789. bufferMap,
  12790. influence,
  12791. stride,
  12792. width,
  12793. depth: i,
  12794. offset: int( 1 )
  12795. } ) );
  12796. }
  12797. } );
  12798. } );
  12799. }
  12800. /**
  12801. * Updates the state of the morphed mesh by updating the base influence.
  12802. *
  12803. * @param {NodeFrame} frame - The current node frame.
  12804. */
  12805. update( /*frame*/ ) {
  12806. const morphBaseInfluence = this.morphBaseInfluence;
  12807. if ( this.mesh.geometry.morphTargetsRelative ) {
  12808. morphBaseInfluence.value = 1;
  12809. } else {
  12810. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12811. }
  12812. }
  12813. }
  12814. /**
  12815. * TSL function for creating a morph node.
  12816. *
  12817. * @tsl
  12818. * @function
  12819. * @param {Mesh} mesh - The mesh holding the morph targets.
  12820. * @returns {MorphNode}
  12821. */
  12822. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12823. /**
  12824. * Base class for lighting nodes.
  12825. *
  12826. * @augments Node
  12827. */
  12828. class LightingNode extends Node {
  12829. static get type() {
  12830. return 'LightingNode';
  12831. }
  12832. /**
  12833. * Constructs a new lighting node.
  12834. */
  12835. constructor() {
  12836. super( 'vec3' );
  12837. /**
  12838. * This flag can be used for type testing.
  12839. *
  12840. * @type {boolean}
  12841. * @readonly
  12842. * @default true
  12843. */
  12844. this.isLightingNode = true;
  12845. }
  12846. }
  12847. /**
  12848. * A generic class that can be used by nodes which contribute
  12849. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12850. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12851. *
  12852. * @augments LightingNode
  12853. */
  12854. class AONode extends LightingNode {
  12855. static get type() {
  12856. return 'AONode';
  12857. }
  12858. /**
  12859. * Constructs a new AO node.
  12860. *
  12861. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12862. */
  12863. constructor( aoNode = null ) {
  12864. super();
  12865. /**
  12866. * The ambient occlusion node.
  12867. *
  12868. * @type {?Node<float>}
  12869. * @default null
  12870. */
  12871. this.aoNode = aoNode;
  12872. }
  12873. setup( builder ) {
  12874. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12875. }
  12876. }
  12877. /**
  12878. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12879. * by adding lighting specific context data. It represents the runtime context of
  12880. * {@link LightsNode}.
  12881. *
  12882. * @augments ContextNode
  12883. */
  12884. class LightingContextNode extends ContextNode {
  12885. static get type() {
  12886. return 'LightingContextNode';
  12887. }
  12888. /**
  12889. * Constructs a new lighting context node.
  12890. *
  12891. * @param {LightsNode} lightsNode - The lights node.
  12892. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12893. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12894. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12895. */
  12896. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12897. super( lightsNode );
  12898. /**
  12899. * The current lighting model.
  12900. *
  12901. * @type {?LightingModel}
  12902. * @default null
  12903. */
  12904. this.lightingModel = lightingModel;
  12905. /**
  12906. * A backdrop node.
  12907. *
  12908. * @type {?Node<vec3>}
  12909. * @default null
  12910. */
  12911. this.backdropNode = backdropNode;
  12912. /**
  12913. * A backdrop alpha node.
  12914. *
  12915. * @type {?Node<float>}
  12916. * @default null
  12917. */
  12918. this.backdropAlphaNode = backdropAlphaNode;
  12919. this._value = null;
  12920. }
  12921. /**
  12922. * Returns a lighting context object.
  12923. *
  12924. * @return {{
  12925. * radiance: Node<vec3>,
  12926. * irradiance: Node<vec3>,
  12927. * iblIrradiance: Node<vec3>,
  12928. * ambientOcclusion: Node<float>,
  12929. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12930. * backdrop: Node<vec3>,
  12931. * backdropAlpha: Node<float>
  12932. * }} The lighting context object.
  12933. */
  12934. getContext() {
  12935. const { backdropNode, backdropAlphaNode } = this;
  12936. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12937. directSpecular = vec3().toVar( 'directSpecular' ),
  12938. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12939. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12940. const reflectedLight = {
  12941. directDiffuse,
  12942. directSpecular,
  12943. indirectDiffuse,
  12944. indirectSpecular
  12945. };
  12946. const context = {
  12947. radiance: vec3().toVar( 'radiance' ),
  12948. irradiance: vec3().toVar( 'irradiance' ),
  12949. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12950. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12951. reflectedLight,
  12952. backdrop: backdropNode,
  12953. backdropAlpha: backdropAlphaNode
  12954. };
  12955. return context;
  12956. }
  12957. setup( builder ) {
  12958. this.value = this._value || ( this._value = this.getContext() );
  12959. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12960. return super.setup( builder );
  12961. }
  12962. }
  12963. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12964. /**
  12965. * A generic class that can be used by nodes which contribute
  12966. * irradiance to the scene. E.g. a light map node can be used
  12967. * as input for this module. Used in {@link NodeMaterial}.
  12968. *
  12969. * @augments LightingNode
  12970. */
  12971. class IrradianceNode extends LightingNode {
  12972. static get type() {
  12973. return 'IrradianceNode';
  12974. }
  12975. /**
  12976. * Constructs a new irradiance node.
  12977. *
  12978. * @param {Node<vec3>} node - A node contributing irradiance.
  12979. */
  12980. constructor( node ) {
  12981. super();
  12982. /**
  12983. * A node contributing irradiance.
  12984. *
  12985. * @type {Node<vec3>}
  12986. */
  12987. this.node = node;
  12988. }
  12989. setup( builder ) {
  12990. builder.context.irradiance.addAssign( this.node );
  12991. }
  12992. }
  12993. const _size$5 = /*@__PURE__*/ new Vector2();
  12994. /**
  12995. * A special type of texture node which represents the data of the current viewport
  12996. * as a texture. The module extracts data from the current bound framebuffer with
  12997. * a copy operation so no extra render pass is required to produce the texture data
  12998. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12999. * variety of effects like refractive or transmissive materials.
  13000. *
  13001. * @augments TextureNode
  13002. */
  13003. class ViewportTextureNode extends TextureNode {
  13004. static get type() {
  13005. return 'ViewportTextureNode';
  13006. }
  13007. /**
  13008. * Constructs a new viewport texture node.
  13009. *
  13010. * @param {Node} [uvNode=screenUV] - The uv node.
  13011. * @param {?Node} [levelNode=null] - The level node.
  13012. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13013. */
  13014. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13015. let defaultFramebuffer = null;
  13016. if ( framebufferTexture === null ) {
  13017. defaultFramebuffer = new FramebufferTexture();
  13018. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13019. framebufferTexture = defaultFramebuffer;
  13020. } else {
  13021. defaultFramebuffer = framebufferTexture;
  13022. }
  13023. super( framebufferTexture, uvNode, levelNode );
  13024. /**
  13025. * Whether to generate mipmaps or not.
  13026. *
  13027. * @type {boolean}
  13028. * @default false
  13029. */
  13030. this.generateMipmaps = false;
  13031. /**
  13032. * The reference framebuffer texture. This is used to store the framebuffer texture
  13033. * for the current render target. If the render target changes, a new framebuffer texture
  13034. * is created automatically.
  13035. *
  13036. * @type {FramebufferTexture}
  13037. * @default null
  13038. */
  13039. this.defaultFramebuffer = defaultFramebuffer;
  13040. /**
  13041. * This flag can be used for type testing.
  13042. *
  13043. * @type {boolean}
  13044. * @readonly
  13045. * @default true
  13046. */
  13047. this.isOutputTextureNode = true;
  13048. /**
  13049. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13050. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13051. *
  13052. * @type {string}
  13053. * @default 'frame'
  13054. */
  13055. this.updateBeforeType = NodeUpdateType.FRAME;
  13056. /**
  13057. * The framebuffer texture for the current renderer context.
  13058. *
  13059. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13060. * @private
  13061. */
  13062. this._cacheTextures = new WeakMap();
  13063. }
  13064. /**
  13065. * This methods returns a texture for the given render target reference.
  13066. *
  13067. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13068. * for different render contexts.
  13069. *
  13070. * @param {?RenderTarget} [reference=null] - The render target reference.
  13071. * @return {Texture} The framebuffer texture.
  13072. */
  13073. getTextureForReference( reference = null ) {
  13074. let defaultFramebuffer;
  13075. let cacheTextures;
  13076. if ( this.referenceNode ) {
  13077. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13078. cacheTextures = this.referenceNode._cacheTextures;
  13079. } else {
  13080. defaultFramebuffer = this.defaultFramebuffer;
  13081. cacheTextures = this._cacheTextures;
  13082. }
  13083. if ( reference === null ) {
  13084. return defaultFramebuffer;
  13085. }
  13086. if ( cacheTextures.has( reference ) === false ) {
  13087. const framebufferTexture = defaultFramebuffer.clone();
  13088. cacheTextures.set( reference, framebufferTexture );
  13089. }
  13090. return cacheTextures.get( reference );
  13091. }
  13092. updateReference( frame ) {
  13093. const renderTarget = frame.renderer.getRenderTarget();
  13094. this.value = this.getTextureForReference( renderTarget );
  13095. return this.value;
  13096. }
  13097. updateBefore( frame ) {
  13098. const renderer = frame.renderer;
  13099. const renderTarget = renderer.getRenderTarget();
  13100. if ( renderTarget === null ) {
  13101. renderer.getDrawingBufferSize( _size$5 );
  13102. } else {
  13103. _size$5.set( renderTarget.width, renderTarget.height );
  13104. }
  13105. //
  13106. const framebufferTexture = this.getTextureForReference( renderTarget );
  13107. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13108. framebufferTexture.image.width = _size$5.width;
  13109. framebufferTexture.image.height = _size$5.height;
  13110. framebufferTexture.needsUpdate = true;
  13111. }
  13112. //
  13113. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13114. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13115. renderer.copyFramebufferToTexture( framebufferTexture );
  13116. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13117. }
  13118. clone() {
  13119. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13120. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13121. return viewportTextureNode;
  13122. }
  13123. }
  13124. /**
  13125. * TSL function for creating a viewport texture node.
  13126. *
  13127. * @tsl
  13128. * @function
  13129. * @param {?Node} [uvNode=screenUV] - The uv node.
  13130. * @param {?Node} [levelNode=null] - The level node.
  13131. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13132. * @returns {ViewportTextureNode}
  13133. */
  13134. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13135. /**
  13136. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13137. *
  13138. * @tsl
  13139. * @function
  13140. * @param {?Node} [uvNode=screenUV] - The uv node.
  13141. * @param {?Node} [levelNode=null] - The level node.
  13142. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13143. * @returns {ViewportTextureNode}
  13144. */
  13145. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13146. let _sharedDepthbuffer = null;
  13147. /**
  13148. * Represents the depth of the current viewport as a texture. This module
  13149. * can be used in combination with viewport texture to achieve effects
  13150. * that require depth evaluation.
  13151. *
  13152. * @augments ViewportTextureNode
  13153. */
  13154. class ViewportDepthTextureNode extends ViewportTextureNode {
  13155. static get type() {
  13156. return 'ViewportDepthTextureNode';
  13157. }
  13158. /**
  13159. * Constructs a new viewport depth texture node.
  13160. *
  13161. * @param {Node} [uvNode=screenUV] - The uv node.
  13162. * @param {?Node} [levelNode=null] - The level node.
  13163. */
  13164. constructor( uvNode = screenUV, levelNode = null ) {
  13165. if ( _sharedDepthbuffer === null ) {
  13166. _sharedDepthbuffer = new DepthTexture();
  13167. }
  13168. super( uvNode, levelNode, _sharedDepthbuffer );
  13169. }
  13170. /**
  13171. * Overwritten so the method always returns the unique shared
  13172. * depth texture.
  13173. *
  13174. * @return {DepthTexture} The shared depth texture.
  13175. */
  13176. getTextureForReference() {
  13177. return _sharedDepthbuffer;
  13178. }
  13179. }
  13180. /**
  13181. * TSL function for a viewport depth texture node.
  13182. *
  13183. * @tsl
  13184. * @function
  13185. * @param {?Node} [uvNode=screenUV] - The uv node.
  13186. * @param {?Node} [levelNode=null] - The level node.
  13187. * @returns {ViewportDepthTextureNode}
  13188. */
  13189. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13190. /**
  13191. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13192. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13193. * fragment or for depth evaluation purposes.
  13194. *
  13195. * @augments Node
  13196. */
  13197. class ViewportDepthNode extends Node {
  13198. static get type() {
  13199. return 'ViewportDepthNode';
  13200. }
  13201. /**
  13202. * Constructs a new viewport depth node.
  13203. *
  13204. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13205. * @param {?Node} [valueNode=null] - The value node.
  13206. */
  13207. constructor( scope, valueNode = null ) {
  13208. super( 'float' );
  13209. /**
  13210. * The node behaves differently depending on which scope is selected.
  13211. *
  13212. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13213. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13214. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13215. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13216. *
  13217. * @type {('depth'|'depthBase'|'linearDepth')}
  13218. */
  13219. this.scope = scope;
  13220. /**
  13221. * Can be used to define a custom depth value.
  13222. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13223. *
  13224. * @type {?Node}
  13225. * @default null
  13226. */
  13227. this.valueNode = valueNode;
  13228. /**
  13229. * This flag can be used for type testing.
  13230. *
  13231. * @type {boolean}
  13232. * @readonly
  13233. * @default true
  13234. */
  13235. this.isViewportDepthNode = true;
  13236. }
  13237. generate( builder ) {
  13238. const { scope } = this;
  13239. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13240. return builder.getFragDepth();
  13241. }
  13242. return super.generate( builder );
  13243. }
  13244. setup( { camera } ) {
  13245. const { scope } = this;
  13246. const value = this.valueNode;
  13247. let node = null;
  13248. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13249. if ( value !== null ) {
  13250. node = depthBase().assign( value );
  13251. }
  13252. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13253. if ( camera.isPerspectiveCamera ) {
  13254. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13255. } else {
  13256. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13257. }
  13258. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13259. if ( value !== null ) {
  13260. if ( camera.isPerspectiveCamera ) {
  13261. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13262. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13263. } else {
  13264. node = value;
  13265. }
  13266. } else {
  13267. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13268. }
  13269. }
  13270. return node;
  13271. }
  13272. }
  13273. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13274. ViewportDepthNode.DEPTH = 'depth';
  13275. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13276. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13277. /**
  13278. * TSL function for converting a viewZ value to an orthographic depth value.
  13279. *
  13280. * @tsl
  13281. * @function
  13282. * @param {Node<float>} viewZ - The viewZ node.
  13283. * @param {Node<float>} near - The camera's near value.
  13284. * @param {Node<float>} far - The camera's far value.
  13285. * @returns {Node<float>}
  13286. */
  13287. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13288. /**
  13289. * TSL function for converting an orthographic depth value to a viewZ value.
  13290. *
  13291. * @tsl
  13292. * @function
  13293. * @param {Node<float>} depth - The orthographic depth.
  13294. * @param {Node<float>} near - The camera's near value.
  13295. * @param {Node<float>} far - The camera's far value.
  13296. * @returns {Node<float>}
  13297. */
  13298. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13299. /**
  13300. * TSL function for converting a viewZ value to a perspective depth value.
  13301. *
  13302. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13303. *
  13304. * @tsl
  13305. * @function
  13306. * @param {Node<float>} viewZ - The viewZ node.
  13307. * @param {Node<float>} near - The camera's near value.
  13308. * @param {Node<float>} far - The camera's far value.
  13309. * @returns {Node<float>}
  13310. */
  13311. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13312. /**
  13313. * TSL function for converting a perspective depth value to a viewZ value.
  13314. *
  13315. * @tsl
  13316. * @function
  13317. * @param {Node<float>} depth - The perspective depth.
  13318. * @param {Node<float>} near - The camera's near value.
  13319. * @param {Node<float>} far - The camera's far value.
  13320. * @returns {Node<float>}
  13321. */
  13322. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13323. /**
  13324. * TSL function for converting a viewZ value to a logarithmic depth value.
  13325. *
  13326. * @tsl
  13327. * @function
  13328. * @param {Node<float>} viewZ - The viewZ node.
  13329. * @param {Node<float>} near - The camera's near value.
  13330. * @param {Node<float>} far - The camera's far value.
  13331. * @returns {Node<float>}
  13332. */
  13333. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13334. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13335. // The final logarithmic depth formula used here is adapted from one described in an
  13336. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13337. // which was an improvement upon an earlier formula one described in an
  13338. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13339. // Ulrich's formula is the following:
  13340. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13341. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13342. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13343. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13344. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13345. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13346. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13347. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13348. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13349. // Outerra eventually made another improvement to their original "C-constant" variant,
  13350. // but it still does not incorporate the camera near plane (for this version,
  13351. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13352. // Here we make 4 changes to Ulrich's formula:
  13353. // 1. Clamp the camera near plane so we don't divide by 0.
  13354. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13355. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13356. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13357. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13358. // so we do the same here, hence the 'viewZ.negate()' call.
  13359. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13360. near = near.max( 1e-6 ).toVar();
  13361. const numerator = log2( viewZ.negate().div( near ) );
  13362. const denominator = log2( far.div( near ) );
  13363. return numerator.div( denominator );
  13364. };
  13365. /**
  13366. * TSL function for converting a logarithmic depth value to a viewZ value.
  13367. *
  13368. * @tsl
  13369. * @function
  13370. * @param {Node<float>} depth - The logarithmic depth.
  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 logarithmicDepthToViewZ = ( depth, near, far ) => {
  13376. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13377. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13378. // a negative viewZ).
  13379. const exponent = depth.mul( log( far.div( near ) ) );
  13380. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13381. };
  13382. /**
  13383. * TSL function for defining a value for the current fragment's depth.
  13384. *
  13385. * @tsl
  13386. * @function
  13387. * @param {Node<float>} value - The depth value to set.
  13388. * @returns {ViewportDepthNode<float>}
  13389. */
  13390. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13391. /**
  13392. * TSL object that represents the depth value for the current fragment.
  13393. *
  13394. * @tsl
  13395. * @type {ViewportDepthNode}
  13396. */
  13397. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13398. /**
  13399. * TSL function for converting a perspective depth value to linear depth.
  13400. *
  13401. * @tsl
  13402. * @function
  13403. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13404. * @returns {ViewportDepthNode<float>}
  13405. */
  13406. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13407. /**
  13408. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13409. *
  13410. * @tsl
  13411. * @type {ViewportDepthNode}
  13412. */
  13413. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13414. depth.assign = ( value ) => depthBase( value );
  13415. /**
  13416. * This node is used in {@link NodeMaterial} to setup the clipping
  13417. * which can happen hardware-accelerated (if supported) and optionally
  13418. * use alpha-to-coverage for anti-aliasing clipped edges.
  13419. *
  13420. * @augments Node
  13421. */
  13422. class ClippingNode extends Node {
  13423. static get type() {
  13424. return 'ClippingNode';
  13425. }
  13426. /**
  13427. * Constructs a new clipping node.
  13428. *
  13429. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13430. * the selected scope influences the behavior of the node and what type of code is generated.
  13431. */
  13432. constructor( scope = ClippingNode.DEFAULT ) {
  13433. super();
  13434. /**
  13435. * The node's scope. Similar to other nodes, the selected scope influences
  13436. * the behavior of the node and what type of code is generated.
  13437. *
  13438. * @type {('default'|'hardware'|'alphaToCoverage')}
  13439. */
  13440. this.scope = scope;
  13441. }
  13442. /**
  13443. * Setups the node depending on the selected scope.
  13444. *
  13445. * @param {NodeBuilder} builder - The current node builder.
  13446. * @return {Node} The result node.
  13447. */
  13448. setup( builder ) {
  13449. super.setup( builder );
  13450. const clippingContext = builder.clippingContext;
  13451. const { intersectionPlanes, unionPlanes } = clippingContext;
  13452. this.hardwareClipping = builder.material.hardwareClipping;
  13453. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13454. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13455. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13456. return this.setupHardwareClipping( unionPlanes, builder );
  13457. } else {
  13458. return this.setupDefault( intersectionPlanes, unionPlanes );
  13459. }
  13460. }
  13461. /**
  13462. * Setups alpha to coverage.
  13463. *
  13464. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13465. * @param {Array<Vector4>} unionPlanes - The union planes.
  13466. * @return {Node} The result node.
  13467. */
  13468. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13469. return Fn( () => {
  13470. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13471. const distanceGradient = float().toVar( 'distanceToGradient' );
  13472. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13473. const numUnionPlanes = unionPlanes.length;
  13474. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13475. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13476. Loop( numUnionPlanes, ( { i } ) => {
  13477. const plane = clippingPlanes.element( i );
  13478. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13479. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13480. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13481. } );
  13482. }
  13483. const numIntersectionPlanes = intersectionPlanes.length;
  13484. if ( numIntersectionPlanes > 0 ) {
  13485. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13486. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13487. Loop( numIntersectionPlanes, ( { i } ) => {
  13488. const plane = clippingPlanes.element( i );
  13489. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13490. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13491. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13492. } );
  13493. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13494. }
  13495. diffuseColor.a.mulAssign( clipOpacity );
  13496. diffuseColor.a.equal( 0.0 ).discard();
  13497. } )();
  13498. }
  13499. /**
  13500. * Setups the default clipping.
  13501. *
  13502. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13503. * @param {Array<Vector4>} unionPlanes - The union planes.
  13504. * @return {Node} The result node.
  13505. */
  13506. setupDefault( intersectionPlanes, unionPlanes ) {
  13507. return Fn( () => {
  13508. const numUnionPlanes = unionPlanes.length;
  13509. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13510. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13511. Loop( numUnionPlanes, ( { i } ) => {
  13512. const plane = clippingPlanes.element( i );
  13513. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13514. } );
  13515. }
  13516. const numIntersectionPlanes = intersectionPlanes.length;
  13517. if ( numIntersectionPlanes > 0 ) {
  13518. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13519. const clipped = bool( true ).toVar( 'clipped' );
  13520. Loop( numIntersectionPlanes, ( { i } ) => {
  13521. const plane = clippingPlanes.element( i );
  13522. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13523. } );
  13524. clipped.discard();
  13525. }
  13526. } )();
  13527. }
  13528. /**
  13529. * Setups hardware clipping.
  13530. *
  13531. * @param {Array<Vector4>} unionPlanes - The union planes.
  13532. * @param {NodeBuilder} builder - The current node builder.
  13533. * @return {Node} The result node.
  13534. */
  13535. setupHardwareClipping( unionPlanes, builder ) {
  13536. const numUnionPlanes = unionPlanes.length;
  13537. builder.enableHardwareClipping( numUnionPlanes );
  13538. return Fn( () => {
  13539. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13540. const hw_clip_distances = builtin( builder.getClipDistance() );
  13541. Loop( numUnionPlanes, ( { i } ) => {
  13542. const plane = clippingPlanes.element( i );
  13543. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13544. hw_clip_distances.element( i ).assign( distance );
  13545. } );
  13546. } )();
  13547. }
  13548. }
  13549. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13550. ClippingNode.DEFAULT = 'default';
  13551. ClippingNode.HARDWARE = 'hardware';
  13552. /**
  13553. * TSL function for setting up the default clipping logic.
  13554. *
  13555. * @tsl
  13556. * @function
  13557. * @returns {ClippingNode}
  13558. */
  13559. const clipping = () => nodeObject( new ClippingNode() );
  13560. /**
  13561. * TSL function for setting up alpha to coverage.
  13562. *
  13563. * @tsl
  13564. * @function
  13565. * @returns {ClippingNode}
  13566. */
  13567. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13568. /**
  13569. * TSL function for setting up hardware-based clipping.
  13570. *
  13571. * @tsl
  13572. * @function
  13573. * @returns {ClippingNode}
  13574. */
  13575. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13576. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13577. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13578. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13579. 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 ) ) ) ) ) );
  13580. } );
  13581. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13582. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13583. } );
  13584. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13585. // Find the discretized derivatives of our coordinates
  13586. const maxDeriv = max$1(
  13587. length( dFdx( position.xyz ) ),
  13588. length( dFdy( position.xyz ) )
  13589. );
  13590. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13591. // Find two nearest log-discretized noise scales
  13592. const pixScales = vec2(
  13593. exp2( floor( log2( pixScale ) ) ),
  13594. exp2( ceil( log2( pixScale ) ) )
  13595. );
  13596. // Compute alpha thresholds at our two noise scales
  13597. const alpha = vec2(
  13598. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13599. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13600. );
  13601. // Factor to interpolate lerp with
  13602. const lerpFactor = fract( log2( pixScale ) );
  13603. // Interpolate alpha threshold from noise at two scales
  13604. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13605. // Pass into CDF to compute uniformly distrib threshold
  13606. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13607. const cases = vec3(
  13608. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13609. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13610. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13611. // Find our final, uniformly distributed alpha threshold (ατ)
  13612. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13613. // Avoids ατ == 0. Could also do ατ =1-ατ
  13614. return clamp( threshold, 1.0e-6, 1.0 );
  13615. } ).setLayout( {
  13616. name: 'getAlphaHashThreshold',
  13617. type: 'float',
  13618. inputs: [
  13619. { name: 'position', type: 'vec3' }
  13620. ]
  13621. } );
  13622. /**
  13623. * An attribute node for representing vertex colors.
  13624. *
  13625. * @augments AttributeNode
  13626. */
  13627. class VertexColorNode extends AttributeNode {
  13628. static get type() {
  13629. return 'VertexColorNode';
  13630. }
  13631. /**
  13632. * Constructs a new vertex color node.
  13633. *
  13634. * @param {number} index - The attribute index.
  13635. */
  13636. constructor( index ) {
  13637. super( null, 'vec4' );
  13638. /**
  13639. * This flag can be used for type testing.
  13640. *
  13641. * @type {boolean}
  13642. * @readonly
  13643. * @default true
  13644. */
  13645. this.isVertexColorNode = true;
  13646. /**
  13647. * The attribute index to enable more than one sets of vertex colors.
  13648. *
  13649. * @type {number}
  13650. * @default 0
  13651. */
  13652. this.index = index;
  13653. }
  13654. /**
  13655. * Overwrites the default implementation by honoring the attribute index.
  13656. *
  13657. * @param {NodeBuilder} builder - The current node builder.
  13658. * @return {string} The attribute name.
  13659. */
  13660. getAttributeName( /*builder*/ ) {
  13661. const index = this.index;
  13662. return 'color' + ( index > 0 ? index : '' );
  13663. }
  13664. generate( builder ) {
  13665. const attributeName = this.getAttributeName( builder );
  13666. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13667. let result;
  13668. if ( geometryAttribute === true ) {
  13669. result = super.generate( builder );
  13670. } else {
  13671. // Vertex color fallback should be white
  13672. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13673. }
  13674. return result;
  13675. }
  13676. serialize( data ) {
  13677. super.serialize( data );
  13678. data.index = this.index;
  13679. }
  13680. deserialize( data ) {
  13681. super.deserialize( data );
  13682. this.index = data.index;
  13683. }
  13684. }
  13685. /**
  13686. * TSL function for creating a reference node.
  13687. *
  13688. * @tsl
  13689. * @function
  13690. * @param {number} [index=0] - The attribute index.
  13691. * @returns {VertexColorNode}
  13692. */
  13693. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13694. /**
  13695. * Represents a "Color Burn" blend mode.
  13696. *
  13697. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13698. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13699. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13700. *
  13701. * @tsl
  13702. * @function
  13703. * @param {Node<vec3>} base - The base color.
  13704. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13705. * @return {Node<vec3>} The result.
  13706. */
  13707. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13708. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13709. } ).setLayout( {
  13710. name: 'blendBurn',
  13711. type: 'vec3',
  13712. inputs: [
  13713. { name: 'base', type: 'vec3' },
  13714. { name: 'blend', type: 'vec3' }
  13715. ]
  13716. } );
  13717. /**
  13718. * Represents a "Color Dodge" blend mode.
  13719. *
  13720. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13721. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13722. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13723. *
  13724. * @tsl
  13725. * @function
  13726. * @param {Node<vec3>} base - The base color.
  13727. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13728. * @return {Node<vec3>} The result.
  13729. */
  13730. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13731. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13732. } ).setLayout( {
  13733. name: 'blendDodge',
  13734. type: 'vec3',
  13735. inputs: [
  13736. { name: 'base', type: 'vec3' },
  13737. { name: 'blend', type: 'vec3' }
  13738. ]
  13739. } );
  13740. /**
  13741. * Represents a "Screen" blend mode.
  13742. *
  13743. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13744. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13745. * effects.
  13746. *
  13747. * @tsl
  13748. * @function
  13749. * @param {Node<vec3>} base - The base color.
  13750. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13751. * @return {Node<vec3>} The result.
  13752. */
  13753. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13754. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13755. } ).setLayout( {
  13756. name: 'blendScreen',
  13757. type: 'vec3',
  13758. inputs: [
  13759. { name: 'base', type: 'vec3' },
  13760. { name: 'blend', type: 'vec3' }
  13761. ]
  13762. } );
  13763. /**
  13764. * Represents a "Overlay" blend mode.
  13765. *
  13766. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13767. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13768. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13769. *
  13770. * @tsl
  13771. * @function
  13772. * @param {Node<vec3>} base - The base color.
  13773. * @param {Node<vec3>} blend - The blend color
  13774. * @return {Node<vec3>} The result.
  13775. */
  13776. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13777. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13778. } ).setLayout( {
  13779. name: 'blendOverlay',
  13780. type: 'vec3',
  13781. inputs: [
  13782. { name: 'base', type: 'vec3' },
  13783. { name: 'blend', type: 'vec3' }
  13784. ]
  13785. } );
  13786. /**
  13787. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13788. * It assumes both input colors have non-premultiplied alpha.
  13789. *
  13790. * @tsl
  13791. * @function
  13792. * @param {Node<vec4>} base - The base color.
  13793. * @param {Node<vec4>} blend - The blend color
  13794. * @return {Node<vec4>} The result.
  13795. */
  13796. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13797. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13798. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13799. } ).setLayout( {
  13800. name: 'blendColor',
  13801. type: 'vec4',
  13802. inputs: [
  13803. { name: 'base', type: 'vec4' },
  13804. { name: 'blend', type: 'vec4' }
  13805. ]
  13806. } );
  13807. /**
  13808. * Premultiplies the RGB channels of a color by its alpha channel.
  13809. *
  13810. * This function is useful for converting a non-premultiplied alpha color
  13811. * into a premultiplied alpha format, where the RGB values are scaled
  13812. * by the alpha value. Premultiplied alpha is often used in graphics
  13813. * rendering for certain operations, such as compositing and image processing.
  13814. *
  13815. * @tsl
  13816. * @function
  13817. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13818. * @return {Node<vec4>} The color with premultiplied alpha.
  13819. */
  13820. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13821. return vec4( color.rgb.mul( color.a ), color.a );
  13822. }, { color: 'vec4', return: 'vec4' } );
  13823. /**
  13824. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13825. *
  13826. * This function is useful for converting a premultiplied alpha color
  13827. * back into a non-premultiplied alpha format, where the RGB values are
  13828. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13829. * rendering for certain operations, such as compositing and image processing.
  13830. *
  13831. * @tsl
  13832. * @function
  13833. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13834. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13835. */
  13836. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13837. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13838. return vec4( color.rgb.div( color.a ), color.a );
  13839. }, { color: 'vec4', return: 'vec4' } );
  13840. // Deprecated
  13841. /**
  13842. * @tsl
  13843. * @function
  13844. * @deprecated since r171. Use {@link blendBurn} instead.
  13845. *
  13846. * @param {...any} params
  13847. * @returns {Function}
  13848. */
  13849. const burn = ( ...params ) => { // @deprecated, r171
  13850. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13851. return blendBurn( params );
  13852. };
  13853. /**
  13854. * @tsl
  13855. * @function
  13856. * @deprecated since r171. Use {@link blendDodge} instead.
  13857. *
  13858. * @param {...any} params
  13859. * @returns {Function}
  13860. */
  13861. const dodge = ( ...params ) => { // @deprecated, r171
  13862. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13863. return blendDodge( params );
  13864. };
  13865. /**
  13866. * @tsl
  13867. * @function
  13868. * @deprecated since r171. Use {@link blendScreen} instead.
  13869. *
  13870. * @param {...any} params
  13871. * @returns {Function}
  13872. */
  13873. const screen = ( ...params ) => { // @deprecated, r171
  13874. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13875. return blendScreen( params );
  13876. };
  13877. /**
  13878. * @tsl
  13879. * @function
  13880. * @deprecated since r171. Use {@link blendOverlay} instead.
  13881. *
  13882. * @param {...any} params
  13883. * @returns {Function}
  13884. */
  13885. const overlay = ( ...params ) => { // @deprecated, r171
  13886. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13887. return blendOverlay( params );
  13888. };
  13889. /**
  13890. * Base class for all node materials.
  13891. *
  13892. * @augments Material
  13893. */
  13894. class NodeMaterial extends Material {
  13895. static get type() {
  13896. return 'NodeMaterial';
  13897. }
  13898. /**
  13899. * Represents the type of the node material.
  13900. *
  13901. * @type {string}
  13902. */
  13903. get type() {
  13904. return this.constructor.type;
  13905. }
  13906. set type( _value ) { /* */ }
  13907. /**
  13908. * Constructs a new node material.
  13909. */
  13910. constructor() {
  13911. super();
  13912. /**
  13913. * This flag can be used for type testing.
  13914. *
  13915. * @type {boolean}
  13916. * @readonly
  13917. * @default true
  13918. */
  13919. this.isNodeMaterial = true;
  13920. /**
  13921. * Whether this material is affected by fog or not.
  13922. *
  13923. * @type {boolean}
  13924. * @default true
  13925. */
  13926. this.fog = true;
  13927. /**
  13928. * Whether this material is affected by lights or not.
  13929. *
  13930. * @type {boolean}
  13931. * @default false
  13932. */
  13933. this.lights = false;
  13934. /**
  13935. * Whether this material uses hardware clipping or not.
  13936. * This property is managed by the engine and should not be
  13937. * modified by apps.
  13938. *
  13939. * @type {boolean}
  13940. * @default false
  13941. */
  13942. this.hardwareClipping = false;
  13943. /**
  13944. * Node materials which set their `lights` property to `true`
  13945. * are affected by all lights of the scene. Sometimes selective
  13946. * lighting is wanted which means only _some_ lights in the scene
  13947. * affect a material. This can be achieved by creating an instance
  13948. * of {@link LightsNode} with a list of selective
  13949. * lights and assign the node to this property.
  13950. *
  13951. * ```js
  13952. * const customLightsNode = lights( [ light1, light2 ] );
  13953. * material.lightsNode = customLightsNode;
  13954. * ```
  13955. *
  13956. * @type {?LightsNode}
  13957. * @default null
  13958. */
  13959. this.lightsNode = null;
  13960. /**
  13961. * The environment of node materials can be defined by an environment
  13962. * map assigned to the `envMap` property or by `Scene.environment`
  13963. * if the node material is a PBR material. This node property allows to overwrite
  13964. * the default behavior and define the environment with a custom node.
  13965. *
  13966. * ```js
  13967. * material.envNode = pmremTexture( renderTarget.texture );
  13968. * ```
  13969. *
  13970. * @type {?Node<vec3>}
  13971. * @default null
  13972. */
  13973. this.envNode = null;
  13974. /**
  13975. * The lighting of node materials might be influenced by ambient occlusion.
  13976. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13977. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13978. * the default and define the ambient occlusion with a custom node instead.
  13979. *
  13980. * If you don't want to overwrite the diffuse color but modify the existing
  13981. * values instead, use {@link materialAO}.
  13982. *
  13983. * @type {?Node<float>}
  13984. * @default null
  13985. */
  13986. this.aoNode = null;
  13987. /**
  13988. * The diffuse color of node materials is by default inferred from the
  13989. * `color` and `map` properties. This node property allows to overwrite the default
  13990. * and define the diffuse color with a node instead.
  13991. *
  13992. * ```js
  13993. * material.colorNode = color( 0xff0000 ); // define red color
  13994. * ```
  13995. *
  13996. * If you don't want to overwrite the diffuse color but modify the existing
  13997. * values instead, use {@link materialColor}.
  13998. *
  13999. * ```js
  14000. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14001. * ```
  14002. *
  14003. * @type {?Node<vec3>}
  14004. * @default null
  14005. */
  14006. this.colorNode = null;
  14007. /**
  14008. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14009. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14010. * and define the normals with a node instead.
  14011. *
  14012. * If you don't want to overwrite the normals but modify the existing values instead,
  14013. * use {@link materialNormal}.
  14014. *
  14015. * @type {?Node<vec3>}
  14016. * @default null
  14017. */
  14018. this.normalNode = null;
  14019. /**
  14020. * The opacity of node materials is by default inferred from the `opacity`
  14021. * and `alphaMap` properties. This node property allows to overwrite the default
  14022. * and define the opacity with a node instead.
  14023. *
  14024. * If you don't want to overwrite the normals but modify the existing
  14025. * value instead, use {@link materialOpacity}.
  14026. *
  14027. * @type {?Node<float>}
  14028. * @default null
  14029. */
  14030. this.opacityNode = null;
  14031. /**
  14032. * This node can be used to implement a variety of filter-like effects. The idea is
  14033. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14034. * to create an arbitrary effect and then assign the node composition to this property.
  14035. * Everything behind the object using this material will now be affected by a filter.
  14036. *
  14037. * ```js
  14038. * const material = new NodeMaterial()
  14039. * material.transparent = true;
  14040. *
  14041. * // everything behind the object will be monochromatic
  14042. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14043. * ```
  14044. *
  14045. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14046. *
  14047. * @type {?Node<vec3>}
  14048. * @default null
  14049. */
  14050. this.backdropNode = null;
  14051. /**
  14052. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14053. *
  14054. * @type {?Node<float>}
  14055. * @default null
  14056. */
  14057. this.backdropAlphaNode = null;
  14058. /**
  14059. * The alpha test of node materials is by default inferred from the `alphaTest`
  14060. * property. This node property allows to overwrite the default and define the
  14061. * alpha test with a node instead.
  14062. *
  14063. * If you don't want to overwrite the alpha test but modify the existing
  14064. * value instead, use {@link materialAlphaTest}.
  14065. *
  14066. * @type {?Node<float>}
  14067. * @default null
  14068. */
  14069. this.alphaTestNode = null;
  14070. /**
  14071. * Discards the fragment if the mask value is `false`.
  14072. *
  14073. * @type {?Node<bool>}
  14074. * @default null
  14075. */
  14076. this.maskNode = null;
  14077. /**
  14078. * The local vertex positions are computed based on multiple factors like the
  14079. * attribute data, morphing or skinning. This node property allows to overwrite
  14080. * the default and define local vertex positions with nodes instead.
  14081. *
  14082. * If you don't want to overwrite the vertex positions but modify the existing
  14083. * values instead, use {@link positionLocal}.
  14084. *
  14085. *```js
  14086. * material.positionNode = positionLocal.add( displace );
  14087. * ```
  14088. *
  14089. * @type {?Node<vec3>}
  14090. * @default null
  14091. */
  14092. this.positionNode = null;
  14093. /**
  14094. * This node property is intended for logic which modifies geometry data once or per animation step.
  14095. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14096. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14097. * can be implemented.
  14098. *
  14099. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14100. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14101. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14102. * eventually assigned to `geometryNode`.
  14103. *
  14104. * @type {?Function}
  14105. * @default null
  14106. */
  14107. this.geometryNode = null;
  14108. /**
  14109. * Allows to overwrite depth values in the fragment shader.
  14110. *
  14111. * @type {?Node<float>}
  14112. * @default null
  14113. */
  14114. this.depthNode = null;
  14115. /**
  14116. * Allows to overwrite the position used for shadow map rendering which
  14117. * is by default {@link positionWorld}, the vertex position
  14118. * in world space.
  14119. *
  14120. * @type {?Node<float>}
  14121. * @default null
  14122. */
  14123. this.receivedShadowPositionNode = null;
  14124. /**
  14125. * Allows to overwrite the geometry position used for shadow map projection which
  14126. * is by default {@link positionLocal}, the vertex position in local space.
  14127. *
  14128. * @type {?Node<float>}
  14129. * @default null
  14130. */
  14131. this.castShadowPositionNode = null;
  14132. /**
  14133. * This node can be used to influence how an object using this node material
  14134. * receive shadows.
  14135. *
  14136. * ```js
  14137. * const totalShadows = float( 1 ).toVar();
  14138. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14139. * totalShadows.mulAssign( shadow );
  14140. * //return float( 1 ); // bypass received shadows
  14141. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14142. * } );
  14143. *
  14144. * @type {?(Function|FunctionNode<vec4>)}
  14145. * @default null
  14146. */
  14147. this.receivedShadowNode = null;
  14148. /**
  14149. * This node can be used to influence how an object using this node material
  14150. * casts shadows. To apply a color to shadows, you can simply do:
  14151. *
  14152. * ```js
  14153. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14154. * ```
  14155. *
  14156. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14157. * is also common to use the property with `Fn` function so checks are performed
  14158. * per fragment.
  14159. *
  14160. * ```js
  14161. * materialCustomShadow.castShadowNode = Fn( () => {
  14162. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14163. * return materialColor;
  14164. * } )();
  14165. * ```
  14166. *
  14167. * @type {?Node<vec4>}
  14168. * @default null
  14169. */
  14170. this.castShadowNode = null;
  14171. /**
  14172. * This node can be used to define the final output of the material.
  14173. *
  14174. * TODO: Explain the differences to `fragmentNode`.
  14175. *
  14176. * @type {?Node<vec4>}
  14177. * @default null
  14178. */
  14179. this.outputNode = null;
  14180. /**
  14181. * MRT configuration is done on renderer or pass level. This node allows to
  14182. * overwrite what values are written into MRT targets on material level. This
  14183. * can be useful for implementing selective FX features that should only affect
  14184. * specific objects.
  14185. *
  14186. * @type {?MRTNode}
  14187. * @default null
  14188. */
  14189. this.mrtNode = null;
  14190. /**
  14191. * This node property can be used if you need complete freedom in implementing
  14192. * the fragment shader. Assigning a node will replace the built-in material
  14193. * logic used in the fragment stage.
  14194. *
  14195. * @type {?Node<vec4>}
  14196. * @default null
  14197. */
  14198. this.fragmentNode = null;
  14199. /**
  14200. * This node property can be used if you need complete freedom in implementing
  14201. * the vertex shader. Assigning a node will replace the built-in material logic
  14202. * used in the vertex stage.
  14203. *
  14204. * @type {?Node<vec4>}
  14205. * @default null
  14206. */
  14207. this.vertexNode = null;
  14208. // Deprecated properties
  14209. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14210. get: () => {
  14211. return this.receivedShadowPositionNode;
  14212. },
  14213. set: ( value ) => {
  14214. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14215. this.receivedShadowPositionNode = value;
  14216. }
  14217. } );
  14218. }
  14219. /**
  14220. * Allows to define a custom cache key that influence the material key computation
  14221. * for render objects.
  14222. *
  14223. * @return {string} The custom cache key.
  14224. */
  14225. customProgramCacheKey() {
  14226. return this.type + getCacheKey$1( this );
  14227. }
  14228. /**
  14229. * Builds this material with the given node builder.
  14230. *
  14231. * @param {NodeBuilder} builder - The current node builder.
  14232. */
  14233. build( builder ) {
  14234. this.setup( builder );
  14235. }
  14236. /**
  14237. * Setups a node material observer with the given builder.
  14238. *
  14239. * @param {NodeBuilder} builder - The current node builder.
  14240. * @return {NodeMaterialObserver} The node material observer.
  14241. */
  14242. setupObserver( builder ) {
  14243. return new NodeMaterialObserver( builder );
  14244. }
  14245. /**
  14246. * Setups the vertex and fragment stage of this node material.
  14247. *
  14248. * @param {NodeBuilder} builder - The current node builder.
  14249. */
  14250. setup( builder ) {
  14251. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14252. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14253. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14254. const renderer = builder.renderer;
  14255. const renderTarget = renderer.getRenderTarget();
  14256. // < VERTEX STAGE >
  14257. builder.addStack();
  14258. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14259. const vertexNode = this.vertexNode || mvp;
  14260. builder.stack.outputNode = vertexNode;
  14261. this.setupHardwareClipping( builder );
  14262. if ( this.geometryNode !== null ) {
  14263. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14264. }
  14265. builder.addFlow( 'vertex', builder.removeStack() );
  14266. // < FRAGMENT STAGE >
  14267. builder.addStack();
  14268. let resultNode;
  14269. const clippingNode = this.setupClipping( builder );
  14270. if ( this.depthWrite === true || this.depthTest === true ) {
  14271. // only write depth if depth buffer is configured
  14272. if ( renderTarget !== null ) {
  14273. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14274. } else {
  14275. if ( renderer.depth === true ) this.setupDepth( builder );
  14276. }
  14277. }
  14278. if ( this.fragmentNode === null ) {
  14279. this.setupDiffuseColor( builder );
  14280. this.setupVariants( builder );
  14281. const outgoingLightNode = this.setupLighting( builder );
  14282. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  14283. // force unsigned floats - useful for RenderTargets
  14284. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14285. resultNode = this.setupOutput( builder, basicOutput );
  14286. // OUTPUT NODE
  14287. output.assign( resultNode );
  14288. //
  14289. const isCustomOutput = this.outputNode !== null;
  14290. if ( isCustomOutput ) resultNode = this.outputNode;
  14291. // MRT
  14292. if ( renderTarget !== null ) {
  14293. const mrt = renderer.getMRT();
  14294. const materialMRT = this.mrtNode;
  14295. if ( mrt !== null ) {
  14296. if ( isCustomOutput ) output.assign( resultNode );
  14297. resultNode = mrt;
  14298. if ( materialMRT !== null ) {
  14299. resultNode = mrt.merge( materialMRT );
  14300. }
  14301. } else if ( materialMRT !== null ) {
  14302. resultNode = materialMRT;
  14303. }
  14304. }
  14305. } else {
  14306. let fragmentNode = this.fragmentNode;
  14307. if ( fragmentNode.isOutputStructNode !== true ) {
  14308. fragmentNode = vec4( fragmentNode );
  14309. }
  14310. resultNode = this.setupOutput( builder, fragmentNode );
  14311. }
  14312. builder.stack.outputNode = resultNode;
  14313. builder.addFlow( 'fragment', builder.removeStack() );
  14314. // < OBSERVER >
  14315. builder.observer = this.setupObserver( builder );
  14316. }
  14317. /**
  14318. * Setups the clipping node.
  14319. *
  14320. * @param {NodeBuilder} builder - The current node builder.
  14321. * @return {ClippingNode} The clipping node.
  14322. */
  14323. setupClipping( builder ) {
  14324. if ( builder.clippingContext === null ) return null;
  14325. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14326. let result = null;
  14327. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14328. const samples = builder.renderer.currentSamples;
  14329. if ( this.alphaToCoverage && samples > 1 ) {
  14330. // to be added to flow when the color/alpha value has been determined
  14331. result = clippingAlpha();
  14332. } else {
  14333. builder.stack.add( clipping() );
  14334. }
  14335. }
  14336. return result;
  14337. }
  14338. /**
  14339. * Setups the hardware clipping if available on the current device.
  14340. *
  14341. * @param {NodeBuilder} builder - The current node builder.
  14342. */
  14343. setupHardwareClipping( builder ) {
  14344. this.hardwareClipping = false;
  14345. if ( builder.clippingContext === null ) return;
  14346. const candidateCount = builder.clippingContext.unionPlanes.length;
  14347. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14348. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14349. builder.stack.add( hardwareClipping() );
  14350. this.hardwareClipping = true;
  14351. }
  14352. return;
  14353. }
  14354. /**
  14355. * Setups the depth of this material.
  14356. *
  14357. * @param {NodeBuilder} builder - The current node builder.
  14358. */
  14359. setupDepth( builder ) {
  14360. const { renderer, camera } = builder;
  14361. // Depth
  14362. let depthNode = this.depthNode;
  14363. if ( depthNode === null ) {
  14364. const mrt = renderer.getMRT();
  14365. if ( mrt && mrt.has( 'depth' ) ) {
  14366. depthNode = mrt.get( 'depth' );
  14367. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14368. if ( camera.isPerspectiveCamera ) {
  14369. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14370. } else {
  14371. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14372. }
  14373. }
  14374. }
  14375. if ( depthNode !== null ) {
  14376. depth.assign( depthNode ).toStack();
  14377. }
  14378. }
  14379. /**
  14380. * Setups the position node in view space. This method exists
  14381. * so derived node materials can modify the implementation e.g. sprite materials.
  14382. *
  14383. * @param {NodeBuilder} builder - The current node builder.
  14384. * @return {Node<vec3>} The position in view space.
  14385. */
  14386. setupPositionView( /*builder*/ ) {
  14387. return modelViewMatrix.mul( positionLocal ).xyz;
  14388. }
  14389. /**
  14390. * Setups the position in clip space.
  14391. *
  14392. * @param {NodeBuilder} builder - The current node builder.
  14393. * @return {Node<vec4>} The position in view space.
  14394. */
  14395. setupModelViewProjection( /*builder*/ ) {
  14396. return cameraProjectionMatrix.mul( positionView );
  14397. }
  14398. /**
  14399. * Setups the logic for the vertex stage.
  14400. *
  14401. * @param {NodeBuilder} builder - The current node builder.
  14402. * @return {Node<vec4>} The position in clip space.
  14403. */
  14404. setupVertex( builder ) {
  14405. builder.addStack();
  14406. this.setupPosition( builder );
  14407. builder.context.vertex = builder.removeStack();
  14408. return modelViewProjection;
  14409. }
  14410. /**
  14411. * Setups the computation of the position in local space.
  14412. *
  14413. * @param {NodeBuilder} builder - The current node builder.
  14414. * @return {Node<vec3>} The position in local space.
  14415. */
  14416. setupPosition( builder ) {
  14417. const { object, geometry } = builder;
  14418. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14419. morphReference( object ).toStack();
  14420. }
  14421. if ( object.isSkinnedMesh === true ) {
  14422. skinning( object ).toStack();
  14423. }
  14424. if ( this.displacementMap ) {
  14425. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14426. const displacementScale = materialReference( 'displacementScale', 'float' );
  14427. const displacementBias = materialReference( 'displacementBias', 'float' );
  14428. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14429. }
  14430. if ( object.isBatchedMesh ) {
  14431. batch( object ).toStack();
  14432. }
  14433. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14434. instancedMesh( object ).toStack();
  14435. }
  14436. if ( this.positionNode !== null ) {
  14437. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14438. }
  14439. return positionLocal;
  14440. }
  14441. /**
  14442. * Setups the computation of the material's diffuse color.
  14443. *
  14444. * @param {NodeBuilder} builder - The current node builder.
  14445. * @param {BufferGeometry} geometry - The geometry.
  14446. */
  14447. setupDiffuseColor( { object, geometry } ) {
  14448. // MASK
  14449. if ( this.maskNode !== null ) {
  14450. // Discard if the mask is `false`
  14451. bool( this.maskNode ).not().discard();
  14452. }
  14453. // COLOR
  14454. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14455. // VERTEX COLORS
  14456. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14457. colorNode = colorNode.mul( vertexColor() );
  14458. }
  14459. // INSTANCED COLORS
  14460. if ( object.instanceColor ) {
  14461. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14462. colorNode = instanceColor.mul( colorNode );
  14463. }
  14464. if ( object.isBatchedMesh && object._colorsTexture ) {
  14465. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14466. colorNode = batchColor.mul( colorNode );
  14467. }
  14468. // DIFFUSE COLOR
  14469. diffuseColor.assign( colorNode );
  14470. // OPACITY
  14471. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14472. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14473. // ALPHA TEST
  14474. let alphaTestNode = null;
  14475. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14476. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14477. if ( this.alphaToCoverage === true ) {
  14478. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14479. diffuseColor.a.lessThanEqual( 0 ).discard();
  14480. } else {
  14481. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14482. }
  14483. }
  14484. // ALPHA HASH
  14485. if ( this.alphaHash === true ) {
  14486. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14487. }
  14488. // OPAQUE
  14489. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14490. if ( isOpaque ) {
  14491. diffuseColor.a.assign( 1.0 );
  14492. }
  14493. }
  14494. /**
  14495. * Abstract interface method that can be implemented by derived materials
  14496. * to setup material-specific node variables.
  14497. *
  14498. * @abstract
  14499. * @param {NodeBuilder} builder - The current node builder.
  14500. */
  14501. setupVariants( /*builder*/ ) {
  14502. // Interface function.
  14503. }
  14504. /**
  14505. * Setups the outgoing light node variable
  14506. *
  14507. * @return {Node<vec3>} The outgoing light node.
  14508. */
  14509. setupOutgoingLight() {
  14510. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14511. }
  14512. /**
  14513. * Setups the normal node from the material.
  14514. *
  14515. * @return {Node<vec3>} The normal node.
  14516. */
  14517. setupNormal() {
  14518. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14519. }
  14520. /**
  14521. * Setups the environment node from the material.
  14522. *
  14523. * @param {NodeBuilder} builder - The current node builder.
  14524. * @return {Node<vec4>} The environment node.
  14525. */
  14526. setupEnvironment( /*builder*/ ) {
  14527. let node = null;
  14528. if ( this.envNode ) {
  14529. node = this.envNode;
  14530. } else if ( this.envMap ) {
  14531. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14532. }
  14533. return node;
  14534. }
  14535. /**
  14536. * Setups the light map node from the material.
  14537. *
  14538. * @param {NodeBuilder} builder - The current node builder.
  14539. * @return {Node<vec3>} The light map node.
  14540. */
  14541. setupLightMap( builder ) {
  14542. let node = null;
  14543. if ( builder.material.lightMap ) {
  14544. node = new IrradianceNode( materialLightMap );
  14545. }
  14546. return node;
  14547. }
  14548. /**
  14549. * Setups the lights node based on the scene, environment and material.
  14550. *
  14551. * @param {NodeBuilder} builder - The current node builder.
  14552. * @return {LightsNode} The lights node.
  14553. */
  14554. setupLights( builder ) {
  14555. const materialLightsNode = [];
  14556. //
  14557. const envNode = this.setupEnvironment( builder );
  14558. if ( envNode && envNode.isLightingNode ) {
  14559. materialLightsNode.push( envNode );
  14560. }
  14561. const lightMapNode = this.setupLightMap( builder );
  14562. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14563. materialLightsNode.push( lightMapNode );
  14564. }
  14565. if ( this.aoNode !== null || builder.material.aoMap ) {
  14566. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14567. materialLightsNode.push( new AONode( aoNode ) );
  14568. }
  14569. let lightsN = this.lightsNode || builder.lightsNode;
  14570. if ( materialLightsNode.length > 0 ) {
  14571. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14572. }
  14573. return lightsN;
  14574. }
  14575. /**
  14576. * This method should be implemented by most derived materials
  14577. * since it defines the material's lighting model.
  14578. *
  14579. * @abstract
  14580. * @param {NodeBuilder} builder - The current node builder.
  14581. * @return {LightingModel} The lighting model.
  14582. */
  14583. setupLightingModel( /*builder*/ ) {
  14584. // Interface function.
  14585. }
  14586. /**
  14587. * Setups the outgoing light node.
  14588. *
  14589. * @param {NodeBuilder} builder - The current node builder.
  14590. * @return {Node<vec3>} The outgoing light node.
  14591. */
  14592. setupLighting( builder ) {
  14593. const { material } = builder;
  14594. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14595. // OUTGOING LIGHT
  14596. const lights = this.lights === true || this.lightsNode !== null;
  14597. const lightsNode = lights ? this.setupLights( builder ) : null;
  14598. let outgoingLightNode = this.setupOutgoingLight( builder );
  14599. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14600. const lightingModel = this.setupLightingModel( builder ) || null;
  14601. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14602. } else if ( backdropNode !== null ) {
  14603. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14604. }
  14605. // EMISSIVE
  14606. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14607. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14608. outgoingLightNode = outgoingLightNode.add( emissive );
  14609. }
  14610. return outgoingLightNode;
  14611. }
  14612. /**
  14613. * Setup the fog.
  14614. *
  14615. * @param {NodeBuilder} builder - The current node builder.
  14616. * @param {Node<vec4>} outputNode - The existing output node.
  14617. * @return {Node<vec4>} The output node.
  14618. */
  14619. setupFog( builder, outputNode ) {
  14620. const fogNode = builder.fogNode;
  14621. if ( fogNode ) {
  14622. output.assign( outputNode );
  14623. outputNode = vec4( fogNode.toVar() );
  14624. }
  14625. return outputNode;
  14626. }
  14627. /**
  14628. * Setups premultiplied alpha.
  14629. *
  14630. * @param {NodeBuilder} builder - The current node builder.
  14631. * @param {Node<vec4>} outputNode - The existing output node.
  14632. * @return {Node<vec4>} The output node.
  14633. */
  14634. setupPremultipliedAlpha( builder, outputNode ) {
  14635. return premultiplyAlpha( outputNode );
  14636. }
  14637. /**
  14638. * Setups the output node.
  14639. *
  14640. * @param {NodeBuilder} builder - The current node builder.
  14641. * @param {Node<vec4>} outputNode - The existing output node.
  14642. * @return {Node<vec4>} The output node.
  14643. */
  14644. setupOutput( builder, outputNode ) {
  14645. // FOG
  14646. if ( this.fog === true ) {
  14647. outputNode = this.setupFog( builder, outputNode );
  14648. }
  14649. // PREMULTIPLIED ALPHA
  14650. if ( this.premultipliedAlpha === true ) {
  14651. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14652. }
  14653. return outputNode;
  14654. }
  14655. /**
  14656. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14657. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14658. * defining all material properties of the classic type in the node type.
  14659. *
  14660. * @param {Material} material - The material to copy properties with their values to this node material.
  14661. */
  14662. setDefaultValues( material ) {
  14663. // This approach is to reuse the native refreshUniforms*
  14664. // and turn available the use of features like transmission and environment in core
  14665. for ( const property in material ) {
  14666. const value = material[ property ];
  14667. if ( this[ property ] === undefined ) {
  14668. this[ property ] = value;
  14669. if ( value && value.clone ) this[ property ] = value.clone();
  14670. }
  14671. }
  14672. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14673. for ( const key in descriptors ) {
  14674. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14675. descriptors[ key ].get !== undefined ) {
  14676. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14677. }
  14678. }
  14679. }
  14680. /**
  14681. * Serializes this material to JSON.
  14682. *
  14683. * @param {?(Object|string)} meta - The meta information for serialization.
  14684. * @return {Object} The serialized node.
  14685. */
  14686. toJSON( meta ) {
  14687. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14688. if ( isRoot ) {
  14689. meta = {
  14690. textures: {},
  14691. images: {},
  14692. nodes: {}
  14693. };
  14694. }
  14695. const data = Material.prototype.toJSON.call( this, meta );
  14696. const nodeChildren = getNodeChildren( this );
  14697. data.inputNodes = {};
  14698. for ( const { property, childNode } of nodeChildren ) {
  14699. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14700. }
  14701. // TODO: Copied from Object3D.toJSON
  14702. function extractFromCache( cache ) {
  14703. const values = [];
  14704. for ( const key in cache ) {
  14705. const data = cache[ key ];
  14706. delete data.metadata;
  14707. values.push( data );
  14708. }
  14709. return values;
  14710. }
  14711. if ( isRoot ) {
  14712. const textures = extractFromCache( meta.textures );
  14713. const images = extractFromCache( meta.images );
  14714. const nodes = extractFromCache( meta.nodes );
  14715. if ( textures.length > 0 ) data.textures = textures;
  14716. if ( images.length > 0 ) data.images = images;
  14717. if ( nodes.length > 0 ) data.nodes = nodes;
  14718. }
  14719. return data;
  14720. }
  14721. /**
  14722. * Copies the properties of the given node material to this instance.
  14723. *
  14724. * @param {NodeMaterial} source - The material to copy.
  14725. * @return {NodeMaterial} A reference to this node material.
  14726. */
  14727. copy( source ) {
  14728. this.lightsNode = source.lightsNode;
  14729. this.envNode = source.envNode;
  14730. this.colorNode = source.colorNode;
  14731. this.normalNode = source.normalNode;
  14732. this.opacityNode = source.opacityNode;
  14733. this.backdropNode = source.backdropNode;
  14734. this.backdropAlphaNode = source.backdropAlphaNode;
  14735. this.alphaTestNode = source.alphaTestNode;
  14736. this.maskNode = source.maskNode;
  14737. this.positionNode = source.positionNode;
  14738. this.geometryNode = source.geometryNode;
  14739. this.depthNode = source.depthNode;
  14740. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14741. this.castShadowPositionNode = source.castShadowPositionNode;
  14742. this.receivedShadowNode = source.receivedShadowNode;
  14743. this.castShadowNode = source.castShadowNode;
  14744. this.outputNode = source.outputNode;
  14745. this.mrtNode = source.mrtNode;
  14746. this.fragmentNode = source.fragmentNode;
  14747. this.vertexNode = source.vertexNode;
  14748. return super.copy( source );
  14749. }
  14750. }
  14751. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14752. /**
  14753. * Node material version of {@link LineBasicMaterial}.
  14754. *
  14755. * @augments NodeMaterial
  14756. */
  14757. class LineBasicNodeMaterial extends NodeMaterial {
  14758. static get type() {
  14759. return 'LineBasicNodeMaterial';
  14760. }
  14761. /**
  14762. * Constructs a new line basic node material.
  14763. *
  14764. * @param {Object} [parameters] - The configuration parameter.
  14765. */
  14766. constructor( parameters ) {
  14767. super();
  14768. /**
  14769. * This flag can be used for type testing.
  14770. *
  14771. * @type {boolean}
  14772. * @readonly
  14773. * @default true
  14774. */
  14775. this.isLineBasicNodeMaterial = true;
  14776. this.setDefaultValues( _defaultValues$d );
  14777. this.setValues( parameters );
  14778. }
  14779. }
  14780. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14781. /**
  14782. * Node material version of {@link LineDashedMaterial}.
  14783. *
  14784. * @augments NodeMaterial
  14785. */
  14786. class LineDashedNodeMaterial extends NodeMaterial {
  14787. static get type() {
  14788. return 'LineDashedNodeMaterial';
  14789. }
  14790. /**
  14791. * Constructs a new line dashed node material.
  14792. *
  14793. * @param {Object} [parameters] - The configuration parameter.
  14794. */
  14795. constructor( parameters ) {
  14796. super();
  14797. /**
  14798. * This flag can be used for type testing.
  14799. *
  14800. * @type {boolean}
  14801. * @readonly
  14802. * @default true
  14803. */
  14804. this.isLineDashedNodeMaterial = true;
  14805. this.setDefaultValues( _defaultValues$c );
  14806. /**
  14807. * The dash offset.
  14808. *
  14809. * @type {number}
  14810. * @default 0
  14811. */
  14812. this.dashOffset = 0;
  14813. /**
  14814. * The offset of dash materials is by default inferred from the `dashOffset`
  14815. * property. This node property allows to overwrite the default
  14816. * and define the offset with a node instead.
  14817. *
  14818. * If you don't want to overwrite the offset but modify the existing
  14819. * value instead, use {@link materialLineDashOffset}.
  14820. *
  14821. * @type {?Node<float>}
  14822. * @default null
  14823. */
  14824. this.offsetNode = null;
  14825. /**
  14826. * The scale of dash materials is by default inferred from the `scale`
  14827. * property. This node property allows to overwrite the default
  14828. * and define the scale with a node instead.
  14829. *
  14830. * If you don't want to overwrite the scale but modify the existing
  14831. * value instead, use {@link materialLineScale}.
  14832. *
  14833. * @type {?Node<float>}
  14834. * @default null
  14835. */
  14836. this.dashScaleNode = null;
  14837. /**
  14838. * The dash size of dash materials is by default inferred from the `dashSize`
  14839. * property. This node property allows to overwrite the default
  14840. * and define the dash size with a node instead.
  14841. *
  14842. * If you don't want to overwrite the dash size but modify the existing
  14843. * value instead, use {@link materialLineDashSize}.
  14844. *
  14845. * @type {?Node<float>}
  14846. * @default null
  14847. */
  14848. this.dashSizeNode = null;
  14849. /**
  14850. * The gap size of dash materials is by default inferred from the `gapSize`
  14851. * property. This node property allows to overwrite the default
  14852. * and define the gap size with a node instead.
  14853. *
  14854. * If you don't want to overwrite the gap size but modify the existing
  14855. * value instead, use {@link materialLineGapSize}.
  14856. *
  14857. * @type {?Node<float>}
  14858. * @default null
  14859. */
  14860. this.gapSizeNode = null;
  14861. this.setValues( parameters );
  14862. }
  14863. /**
  14864. * Setups the dash specific node variables.
  14865. *
  14866. * @param {NodeBuilder} builder - The current node builder.
  14867. */
  14868. setupVariants( /* builder */ ) {
  14869. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14870. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14871. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14872. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14873. dashSize.assign( dashSizeNode );
  14874. gapSize.assign( gapSizeNode );
  14875. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14876. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14877. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14878. }
  14879. }
  14880. let _sharedFramebuffer = null;
  14881. /**
  14882. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14883. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14884. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14885. *
  14886. * @augments ViewportTextureNode
  14887. */
  14888. class ViewportSharedTextureNode extends ViewportTextureNode {
  14889. static get type() {
  14890. return 'ViewportSharedTextureNode';
  14891. }
  14892. /**
  14893. * Constructs a new viewport shared texture node.
  14894. *
  14895. * @param {Node} [uvNode=screenUV] - The uv node.
  14896. * @param {?Node} [levelNode=null] - The level node.
  14897. */
  14898. constructor( uvNode = screenUV, levelNode = null ) {
  14899. if ( _sharedFramebuffer === null ) {
  14900. _sharedFramebuffer = new FramebufferTexture();
  14901. }
  14902. super( uvNode, levelNode, _sharedFramebuffer );
  14903. }
  14904. /**
  14905. * Overwritten so the method always returns the unique shared
  14906. * framebuffer texture.
  14907. *
  14908. * @return {FramebufferTexture} The shared framebuffer texture.
  14909. */
  14910. getTextureForReference() {
  14911. return _sharedFramebuffer;
  14912. }
  14913. updateReference() {
  14914. return this;
  14915. }
  14916. }
  14917. /**
  14918. * TSL function for creating a shared viewport texture node.
  14919. *
  14920. * @tsl
  14921. * @function
  14922. * @param {?Node} [uvNode=screenUV] - The uv node.
  14923. * @param {?Node} [levelNode=null] - The level node.
  14924. * @returns {ViewportSharedTextureNode}
  14925. */
  14926. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14927. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14928. /**
  14929. * This node material can be used to render lines with a size larger than one
  14930. * by representing them as instanced meshes.
  14931. *
  14932. * @augments NodeMaterial
  14933. */
  14934. class Line2NodeMaterial extends NodeMaterial {
  14935. static get type() {
  14936. return 'Line2NodeMaterial';
  14937. }
  14938. /**
  14939. * Constructs a new node material for wide line rendering.
  14940. *
  14941. * @param {Object} [parameters={}] - The configuration parameter.
  14942. */
  14943. constructor( parameters = {} ) {
  14944. super();
  14945. /**
  14946. * This flag can be used for type testing.
  14947. *
  14948. * @type {boolean}
  14949. * @readonly
  14950. * @default true
  14951. */
  14952. this.isLine2NodeMaterial = true;
  14953. this.setDefaultValues( _defaultValues$b );
  14954. /**
  14955. * Whether vertex colors should be used or not.
  14956. *
  14957. * @type {boolean}
  14958. * @default false
  14959. */
  14960. this.useColor = parameters.vertexColors;
  14961. /**
  14962. * The dash offset.
  14963. *
  14964. * @type {number}
  14965. * @default 0
  14966. */
  14967. this.dashOffset = 0;
  14968. /**
  14969. * Defines the lines color.
  14970. *
  14971. * @type {?Node<vec3>}
  14972. * @default null
  14973. */
  14974. this.lineColorNode = null;
  14975. /**
  14976. * Defines the offset.
  14977. *
  14978. * @type {?Node<float>}
  14979. * @default null
  14980. */
  14981. this.offsetNode = null;
  14982. /**
  14983. * Defines the dash scale.
  14984. *
  14985. * @type {?Node<float>}
  14986. * @default null
  14987. */
  14988. this.dashScaleNode = null;
  14989. /**
  14990. * Defines the dash size.
  14991. *
  14992. * @type {?Node<float>}
  14993. * @default null
  14994. */
  14995. this.dashSizeNode = null;
  14996. /**
  14997. * Defines the gap size.
  14998. *
  14999. * @type {?Node<float>}
  15000. * @default null
  15001. */
  15002. this.gapSizeNode = null;
  15003. /**
  15004. * Blending is set to `NoBlending` since transparency
  15005. * is not supported, yet.
  15006. *
  15007. * @type {number}
  15008. * @default 0
  15009. */
  15010. this.blending = NoBlending;
  15011. this._useDash = parameters.dashed;
  15012. this._useAlphaToCoverage = true;
  15013. this._useWorldUnits = false;
  15014. this.setValues( parameters );
  15015. }
  15016. /**
  15017. * Setups the vertex and fragment stage of this node material.
  15018. *
  15019. * @param {NodeBuilder} builder - The current node builder.
  15020. */
  15021. setup( builder ) {
  15022. const { renderer } = builder;
  15023. const useAlphaToCoverage = this._useAlphaToCoverage;
  15024. const useColor = this.useColor;
  15025. const useDash = this._useDash;
  15026. const useWorldUnits = this._useWorldUnits;
  15027. const trimSegment = Fn( ( { start, end } ) => {
  15028. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15029. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15030. const nearEstimate = b.mul( -0.5 ).div( a );
  15031. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15032. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15033. } ).setLayout( {
  15034. name: 'trimSegment',
  15035. type: 'vec4',
  15036. inputs: [
  15037. { name: 'start', type: 'vec4' },
  15038. { name: 'end', type: 'vec4' }
  15039. ]
  15040. } );
  15041. this.vertexNode = Fn( () => {
  15042. const instanceStart = attribute( 'instanceStart' );
  15043. const instanceEnd = attribute( 'instanceEnd' );
  15044. // camera space
  15045. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15046. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15047. if ( useDash ) {
  15048. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15049. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15050. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15051. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15052. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15053. lineDistance = lineDistance.add( offsetNode );
  15054. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15055. }
  15056. if ( useWorldUnits ) {
  15057. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15058. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15059. }
  15060. const aspect = viewport.z.div( viewport.w );
  15061. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15062. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15063. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15064. // perhaps there is a more elegant solution -- WestLangley
  15065. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15066. If( perspective, () => {
  15067. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15068. end.assign( trimSegment( { start: start, end: end } ) );
  15069. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15070. start.assign( trimSegment( { start: end, end: start } ) );
  15071. } );
  15072. } );
  15073. // clip space
  15074. const clipStart = cameraProjectionMatrix.mul( start );
  15075. const clipEnd = cameraProjectionMatrix.mul( end );
  15076. // ndc space
  15077. const ndcStart = clipStart.xyz.div( clipStart.w );
  15078. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15079. // direction
  15080. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15081. // account for clip-space aspect ratio
  15082. dir.x.assign( dir.x.mul( aspect ) );
  15083. dir.assign( dir.normalize() );
  15084. const clip = vec4().toVar();
  15085. if ( useWorldUnits ) {
  15086. // get the offset direction as perpendicular to the view vector
  15087. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15088. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15089. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15090. const worldFwd = worldDir.cross( worldUp );
  15091. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15092. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15093. // height offset
  15094. const hw = materialLineWidth.mul( 0.5 );
  15095. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15096. // don't extend the line if we're rendering dashes because we
  15097. // won't be rendering the endcaps
  15098. if ( ! useDash ) {
  15099. // cap extension
  15100. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15101. // add width to the box
  15102. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15103. // endcaps
  15104. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15105. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15106. } );
  15107. }
  15108. // project the worldpos
  15109. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15110. // shift the depth of the projected points so the line
  15111. // segments overlap neatly
  15112. const clipPose = vec3().toVar();
  15113. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15114. clip.z.assign( clipPose.z.mul( clip.w ) );
  15115. } else {
  15116. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15117. // undo aspect ratio adjustment
  15118. dir.x.assign( dir.x.div( aspect ) );
  15119. offset.x.assign( offset.x.div( aspect ) );
  15120. // sign flip
  15121. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15122. // endcaps
  15123. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15124. offset.assign( offset.sub( dir ) );
  15125. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15126. offset.assign( offset.add( dir ) );
  15127. } );
  15128. // adjust for linewidth
  15129. offset.assign( offset.mul( materialLineWidth ) );
  15130. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15131. offset.assign( offset.div( viewport.w ) );
  15132. // select end
  15133. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15134. // back to clip space
  15135. offset.assign( offset.mul( clip.w ) );
  15136. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15137. }
  15138. return clip;
  15139. } )();
  15140. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15141. const p13 = p1.sub( p3 );
  15142. const p43 = p4.sub( p3 );
  15143. const p21 = p2.sub( p1 );
  15144. const d1343 = p13.dot( p43 );
  15145. const d4321 = p43.dot( p21 );
  15146. const d1321 = p13.dot( p21 );
  15147. const d4343 = p43.dot( p43 );
  15148. const d2121 = p21.dot( p21 );
  15149. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15150. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15151. const mua = numer.div( denom ).clamp();
  15152. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15153. return vec2( mua, mub );
  15154. } );
  15155. this.colorNode = Fn( () => {
  15156. const vUv = uv$1();
  15157. if ( useDash ) {
  15158. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15159. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15160. dashSize.assign( dashSizeNode );
  15161. gapSize.assign( gapSizeNode );
  15162. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15163. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15164. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15165. }
  15166. const alpha = float( 1 ).toVar( 'alpha' );
  15167. if ( useWorldUnits ) {
  15168. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15169. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15170. // Find the closest points on the view ray and the line segment
  15171. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15172. const lineDir = worldEnd.sub( worldStart );
  15173. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15174. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15175. const p2 = rayEnd.mul( params.y );
  15176. const delta = p1.sub( p2 );
  15177. const len = delta.length();
  15178. const norm = len.div( materialLineWidth );
  15179. if ( ! useDash ) {
  15180. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15181. const dnorm = norm.fwidth();
  15182. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15183. } else {
  15184. norm.greaterThan( 0.5 ).discard();
  15185. }
  15186. }
  15187. } else {
  15188. // round endcaps
  15189. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15190. const a = vUv.x;
  15191. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15192. const len2 = a.mul( a ).add( b.mul( b ) );
  15193. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15194. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15195. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15196. } );
  15197. } else {
  15198. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15199. const a = vUv.x;
  15200. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15201. const len2 = a.mul( a ).add( b.mul( b ) );
  15202. len2.greaterThan( 1.0 ).discard();
  15203. } );
  15204. }
  15205. }
  15206. let lineColorNode;
  15207. if ( this.lineColorNode ) {
  15208. lineColorNode = this.lineColorNode;
  15209. } else {
  15210. if ( useColor ) {
  15211. const instanceColorStart = attribute( 'instanceColorStart' );
  15212. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15213. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15214. lineColorNode = instanceColor.mul( materialColor );
  15215. } else {
  15216. lineColorNode = materialColor;
  15217. }
  15218. }
  15219. return vec4( lineColorNode, alpha );
  15220. } )();
  15221. if ( this.transparent ) {
  15222. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15223. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15224. }
  15225. super.setup( builder );
  15226. }
  15227. /**
  15228. * Whether the lines should sized in world units or not.
  15229. * When set to `false` the unit is pixel.
  15230. *
  15231. * @type {boolean}
  15232. * @default false
  15233. */
  15234. get worldUnits() {
  15235. return this._useWorldUnits;
  15236. }
  15237. set worldUnits( value ) {
  15238. if ( this._useWorldUnits !== value ) {
  15239. this._useWorldUnits = value;
  15240. this.needsUpdate = true;
  15241. }
  15242. }
  15243. /**
  15244. * Whether the lines should be dashed or not.
  15245. *
  15246. * @type {boolean}
  15247. * @default false
  15248. */
  15249. get dashed() {
  15250. return this._useDash;
  15251. }
  15252. set dashed( value ) {
  15253. if ( this._useDash !== value ) {
  15254. this._useDash = value;
  15255. this.needsUpdate = true;
  15256. }
  15257. }
  15258. /**
  15259. * Whether alpha to coverage should be used or not.
  15260. *
  15261. * @type {boolean}
  15262. * @default true
  15263. */
  15264. get alphaToCoverage() {
  15265. return this._useAlphaToCoverage;
  15266. }
  15267. set alphaToCoverage( value ) {
  15268. if ( this._useAlphaToCoverage !== value ) {
  15269. this._useAlphaToCoverage = value;
  15270. this.needsUpdate = true;
  15271. }
  15272. }
  15273. }
  15274. /**
  15275. * Packs a direction vector into a color value.
  15276. *
  15277. * @tsl
  15278. * @function
  15279. * @param {Node<vec3>} node - The direction to pack.
  15280. * @return {Node<vec3>} The color.
  15281. */
  15282. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  15283. /**
  15284. * Unpacks a color value into a direction vector.
  15285. *
  15286. * @tsl
  15287. * @function
  15288. * @param {Node<vec3>} node - The color to unpack.
  15289. * @return {Node<vec3>} The direction.
  15290. */
  15291. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  15292. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15293. /**
  15294. * Node material version of {@link MeshNormalMaterial}.
  15295. *
  15296. * @augments NodeMaterial
  15297. */
  15298. class MeshNormalNodeMaterial extends NodeMaterial {
  15299. static get type() {
  15300. return 'MeshNormalNodeMaterial';
  15301. }
  15302. /**
  15303. * Constructs a new mesh normal node material.
  15304. *
  15305. * @param {Object} [parameters] - The configuration parameter.
  15306. */
  15307. constructor( parameters ) {
  15308. super();
  15309. /**
  15310. * This flag can be used for type testing.
  15311. *
  15312. * @type {boolean}
  15313. * @readonly
  15314. * @default true
  15315. */
  15316. this.isMeshNormalNodeMaterial = true;
  15317. this.setDefaultValues( _defaultValues$a );
  15318. this.setValues( parameters );
  15319. }
  15320. /**
  15321. * Overwrites the default implementation by computing the diffuse color
  15322. * based on the normal data.
  15323. */
  15324. setupDiffuseColor() {
  15325. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15326. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15327. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15328. }
  15329. }
  15330. /**
  15331. * TSL function for creating an equirect uv node.
  15332. *
  15333. * Can be used to compute texture coordinates for projecting an
  15334. * equirectangular texture onto a mesh for using it as the scene's
  15335. * background.
  15336. *
  15337. * ```js
  15338. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15339. * ```
  15340. *
  15341. * @tsl
  15342. * @function
  15343. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15344. * @returns {Node<vec2>}
  15345. */
  15346. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15347. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15348. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15349. return vec2( u, v );
  15350. } );
  15351. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15352. /**
  15353. * This class represents a cube render target. It is a special version
  15354. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15355. *
  15356. * @augments WebGLCubeRenderTarget
  15357. */
  15358. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15359. /**
  15360. * Constructs a new cube render target.
  15361. *
  15362. * @param {number} [size=1] - The size of the render target.
  15363. * @param {RenderTarget~Options} [options] - The configuration object.
  15364. */
  15365. constructor( size = 1, options = {} ) {
  15366. super( size, options );
  15367. /**
  15368. * This flag can be used for type testing.
  15369. *
  15370. * @type {boolean}
  15371. * @readonly
  15372. * @default true
  15373. */
  15374. this.isCubeRenderTarget = true;
  15375. }
  15376. /**
  15377. * Converts the given equirectangular texture to a cube map.
  15378. *
  15379. * @param {Renderer} renderer - The renderer.
  15380. * @param {Texture} texture - The equirectangular texture.
  15381. * @return {CubeRenderTarget} A reference to this cube render target.
  15382. */
  15383. fromEquirectangularTexture( renderer, texture$1 ) {
  15384. const currentMinFilter = texture$1.minFilter;
  15385. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15386. texture$1.generateMipmaps = true;
  15387. this.texture.type = texture$1.type;
  15388. this.texture.colorSpace = texture$1.colorSpace;
  15389. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15390. this.texture.minFilter = texture$1.minFilter;
  15391. this.texture.magFilter = texture$1.magFilter;
  15392. const geometry = new BoxGeometry( 5, 5, 5 );
  15393. const uvNode = equirectUV( positionWorldDirection );
  15394. const material = new NodeMaterial();
  15395. material.colorNode = texture( texture$1, uvNode, 0 );
  15396. material.side = BackSide;
  15397. material.blending = NoBlending;
  15398. const mesh = new Mesh( geometry, material );
  15399. const scene = new Scene();
  15400. scene.add( mesh );
  15401. // Avoid blurred poles
  15402. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15403. const camera = new CubeCamera( 1, 10, this );
  15404. const currentMRT = renderer.getMRT();
  15405. renderer.setMRT( null );
  15406. camera.update( renderer, scene );
  15407. renderer.setMRT( currentMRT );
  15408. texture$1.minFilter = currentMinFilter;
  15409. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15410. mesh.geometry.dispose();
  15411. mesh.material.dispose();
  15412. return this;
  15413. }
  15414. }
  15415. const _cache$1 = new WeakMap();
  15416. /**
  15417. * This node can be used to automatically convert environment maps in the
  15418. * equirectangular format into the cube map format.
  15419. *
  15420. * @augments TempNode
  15421. */
  15422. class CubeMapNode extends TempNode {
  15423. static get type() {
  15424. return 'CubeMapNode';
  15425. }
  15426. /**
  15427. * Constructs a new cube map node.
  15428. *
  15429. * @param {Node} envNode - The node representing the environment map.
  15430. */
  15431. constructor( envNode ) {
  15432. super( 'vec3' );
  15433. /**
  15434. * The node representing the environment map.
  15435. *
  15436. * @type {Node}
  15437. */
  15438. this.envNode = envNode;
  15439. /**
  15440. * A reference to the internal cube texture.
  15441. *
  15442. * @private
  15443. * @type {?CubeTexture}
  15444. * @default null
  15445. */
  15446. this._cubeTexture = null;
  15447. /**
  15448. * A reference to the internal cube texture node.
  15449. *
  15450. * @private
  15451. * @type {CubeTextureNode}
  15452. */
  15453. this._cubeTextureNode = cubeTexture( null );
  15454. const defaultTexture = new CubeTexture();
  15455. defaultTexture.isRenderTargetTexture = true;
  15456. /**
  15457. * A default cube texture that acts as a placeholder.
  15458. * It is used when the conversion from equirectangular to cube
  15459. * map has not finished yet for a given texture.
  15460. *
  15461. * @private
  15462. * @type {CubeTexture}
  15463. */
  15464. this._defaultTexture = defaultTexture;
  15465. /**
  15466. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15467. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15468. *
  15469. * @type {string}
  15470. * @default 'render'
  15471. */
  15472. this.updateBeforeType = NodeUpdateType.RENDER;
  15473. }
  15474. updateBefore( frame ) {
  15475. const { renderer, material } = frame;
  15476. const envNode = this.envNode;
  15477. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15478. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15479. if ( texture && texture.isTexture ) {
  15480. const mapping = texture.mapping;
  15481. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15482. // check for converted cubemap map
  15483. if ( _cache$1.has( texture ) ) {
  15484. const cubeMap = _cache$1.get( texture );
  15485. mapTextureMapping( cubeMap, texture.mapping );
  15486. this._cubeTexture = cubeMap;
  15487. } else {
  15488. // create cube map from equirectangular map
  15489. const image = texture.image;
  15490. if ( isEquirectangularMapReady$1( image ) ) {
  15491. const renderTarget = new CubeRenderTarget( image.height );
  15492. renderTarget.fromEquirectangularTexture( renderer, texture );
  15493. mapTextureMapping( renderTarget.texture, texture.mapping );
  15494. this._cubeTexture = renderTarget.texture;
  15495. _cache$1.set( texture, renderTarget.texture );
  15496. texture.addEventListener( 'dispose', onTextureDispose );
  15497. } else {
  15498. // default cube texture as fallback when equirectangular texture is not yet loaded
  15499. this._cubeTexture = this._defaultTexture;
  15500. }
  15501. }
  15502. //
  15503. this._cubeTextureNode.value = this._cubeTexture;
  15504. } else {
  15505. // envNode already refers to a cube map
  15506. this._cubeTextureNode = this.envNode;
  15507. }
  15508. }
  15509. }
  15510. }
  15511. setup( builder ) {
  15512. this.updateBefore( builder );
  15513. return this._cubeTextureNode;
  15514. }
  15515. }
  15516. /**
  15517. * Returns true if the given equirectangular image has been fully loaded
  15518. * and is ready for further processing.
  15519. *
  15520. * @private
  15521. * @param {Image} image - The equirectangular image to check.
  15522. * @return {boolean} Whether the image is ready or not.
  15523. */
  15524. function isEquirectangularMapReady$1( image ) {
  15525. if ( image === null || image === undefined ) return false;
  15526. return image.height > 0;
  15527. }
  15528. /**
  15529. * This function is executed when `dispose()` is called on the equirectangular
  15530. * texture. In this case, the generated cube map with its render target
  15531. * is deleted as well.
  15532. *
  15533. * @private
  15534. * @param {Object} event - The event object.
  15535. */
  15536. function onTextureDispose( event ) {
  15537. const texture = event.target;
  15538. texture.removeEventListener( 'dispose', onTextureDispose );
  15539. const renderTarget = _cache$1.get( texture );
  15540. if ( renderTarget !== undefined ) {
  15541. _cache$1.delete( texture );
  15542. renderTarget.dispose();
  15543. }
  15544. }
  15545. /**
  15546. * This function makes sure the generated cube map uses the correct
  15547. * texture mapping that corresponds to the equirectangular original.
  15548. *
  15549. * @private
  15550. * @param {Texture} texture - The cube texture.
  15551. * @param {number} mapping - The original texture mapping.
  15552. */
  15553. function mapTextureMapping( texture, mapping ) {
  15554. if ( mapping === EquirectangularReflectionMapping ) {
  15555. texture.mapping = CubeReflectionMapping;
  15556. } else if ( mapping === EquirectangularRefractionMapping ) {
  15557. texture.mapping = CubeRefractionMapping;
  15558. }
  15559. }
  15560. /**
  15561. * TSL function for creating a cube map node.
  15562. *
  15563. * @tsl
  15564. * @function
  15565. * @param {Node} envNode - The node representing the environment map.
  15566. * @returns {CubeMapNode}
  15567. */
  15568. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15569. /**
  15570. * Represents a basic model for Image-based lighting (IBL). The environment
  15571. * is defined via environment maps in the equirectangular or cube map format.
  15572. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15573. * or {@link MeshPhongNodeMaterial}.
  15574. *
  15575. * @augments LightingNode
  15576. */
  15577. class BasicEnvironmentNode extends LightingNode {
  15578. static get type() {
  15579. return 'BasicEnvironmentNode';
  15580. }
  15581. /**
  15582. * Constructs a new basic environment node.
  15583. *
  15584. * @param {Node} [envNode=null] - A node representing the environment.
  15585. */
  15586. constructor( envNode = null ) {
  15587. super();
  15588. /**
  15589. * A node representing the environment.
  15590. *
  15591. * @type {Node}
  15592. * @default null
  15593. */
  15594. this.envNode = envNode;
  15595. }
  15596. setup( builder ) {
  15597. // environment property is used in the finish() method of BasicLightingModel
  15598. builder.context.environment = cubeMapNode( this.envNode );
  15599. }
  15600. }
  15601. /**
  15602. * A specific version of {@link IrradianceNode} that is only relevant
  15603. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15604. * requires a special scaling factor for the light map.
  15605. *
  15606. * @augments LightingNode
  15607. */
  15608. class BasicLightMapNode extends LightingNode {
  15609. static get type() {
  15610. return 'BasicLightMapNode';
  15611. }
  15612. /**
  15613. * Constructs a new basic light map node.
  15614. *
  15615. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15616. */
  15617. constructor( lightMapNode = null ) {
  15618. super();
  15619. /**
  15620. * The light map node.
  15621. *
  15622. * @type {?Node<vec3>}
  15623. */
  15624. this.lightMapNode = lightMapNode;
  15625. }
  15626. setup( builder ) {
  15627. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15628. const RECIPROCAL_PI = float( 1 / Math.PI );
  15629. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15630. }
  15631. }
  15632. /**
  15633. * Abstract class for implementing lighting models. The module defines
  15634. * multiple methods that concrete lighting models can implement. These
  15635. * methods are executed at different points during the light evaluation
  15636. * process.
  15637. */
  15638. class LightingModel {
  15639. /**
  15640. * This method is intended for setting up lighting model and context data
  15641. * which are later used in the evaluation process.
  15642. *
  15643. * @abstract
  15644. * @param {NodeBuilder} builder - The current node builder.
  15645. */
  15646. start( builder ) {
  15647. // lights ( direct )
  15648. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15649. // indirect
  15650. this.indirect( builder );
  15651. }
  15652. /**
  15653. * This method is intended for executing final tasks like final updates
  15654. * to the outgoing light.
  15655. *
  15656. * @abstract
  15657. * @param {NodeBuilder} builder - The current node builder.
  15658. */
  15659. finish( /*builder*/ ) { }
  15660. /**
  15661. * This method is intended for implementing the direct light term and
  15662. * executed during the build process of directional, point and spot light nodes.
  15663. *
  15664. * @abstract
  15665. * @param {Object} lightData - The light data.
  15666. * @param {NodeBuilder} builder - The current node builder.
  15667. */
  15668. direct( /*lightData, builder*/ ) { }
  15669. /**
  15670. * This method is intended for implementing the direct light term for
  15671. * rect area light nodes.
  15672. *
  15673. * @abstract
  15674. * @param {Object} lightData - The light data.
  15675. * @param {NodeBuilder} builder - The current node builder.
  15676. */
  15677. directRectArea( /*lightData, builder*/ ) {}
  15678. /**
  15679. * This method is intended for implementing the indirect light term.
  15680. *
  15681. * @abstract
  15682. * @param {NodeBuilder} builder - The current node builder.
  15683. */
  15684. indirect( /*builder*/ ) { }
  15685. /**
  15686. * This method is intended for implementing the ambient occlusion term.
  15687. * Unlike other methods, this method must be called manually by the lighting
  15688. * model in its indirect term.
  15689. *
  15690. * @abstract
  15691. * @param {NodeBuilder} builder - The current node builder.
  15692. */
  15693. ambientOcclusion( /*input, stack, builder*/ ) { }
  15694. }
  15695. /**
  15696. * Represents the lighting model for unlit materials. The only light contribution
  15697. * is baked indirect lighting modulated with ambient occlusion and the material's
  15698. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15699. *
  15700. * @augments LightingModel
  15701. */
  15702. class BasicLightingModel extends LightingModel {
  15703. /**
  15704. * Constructs a new basic lighting model.
  15705. */
  15706. constructor() {
  15707. super();
  15708. }
  15709. /**
  15710. * Implements the baked indirect lighting with its modulation.
  15711. *
  15712. * @param {NodeBuilder} builder - The current node builder.
  15713. */
  15714. indirect( { context } ) {
  15715. const ambientOcclusion = context.ambientOcclusion;
  15716. const reflectedLight = context.reflectedLight;
  15717. const irradianceLightMap = context.irradianceLightMap;
  15718. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15719. // accumulation (baked indirect lighting only)
  15720. if ( irradianceLightMap ) {
  15721. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15722. } else {
  15723. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15724. }
  15725. // modulation
  15726. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15727. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15728. }
  15729. /**
  15730. * Implements the environment mapping.
  15731. *
  15732. * @param {NodeBuilder} builder - The current node builder.
  15733. */
  15734. finish( builder ) {
  15735. const { material, context } = builder;
  15736. const outgoingLight = context.outgoingLight;
  15737. const envNode = builder.context.environment;
  15738. if ( envNode ) {
  15739. switch ( material.combine ) {
  15740. case MultiplyOperation:
  15741. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15742. break;
  15743. case MixOperation:
  15744. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15745. break;
  15746. case AddOperation:
  15747. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15748. break;
  15749. default:
  15750. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15751. break;
  15752. }
  15753. }
  15754. }
  15755. }
  15756. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15757. /**
  15758. * Node material version of {@link MeshBasicMaterial}.
  15759. *
  15760. * @augments NodeMaterial
  15761. */
  15762. class MeshBasicNodeMaterial extends NodeMaterial {
  15763. static get type() {
  15764. return 'MeshBasicNodeMaterial';
  15765. }
  15766. /**
  15767. * Constructs a new mesh basic node material.
  15768. *
  15769. * @param {Object} [parameters] - The configuration parameter.
  15770. */
  15771. constructor( parameters ) {
  15772. super();
  15773. /**
  15774. * This flag can be used for type testing.
  15775. *
  15776. * @type {boolean}
  15777. * @readonly
  15778. * @default true
  15779. */
  15780. this.isMeshBasicNodeMaterial = true;
  15781. /**
  15782. * Although the basic material is by definition unlit, we set
  15783. * this property to `true` since we use a lighting model to compute
  15784. * the outgoing light of the fragment shader.
  15785. *
  15786. * @type {boolean}
  15787. * @default true
  15788. */
  15789. this.lights = true;
  15790. this.setDefaultValues( _defaultValues$9 );
  15791. this.setValues( parameters );
  15792. }
  15793. /**
  15794. * Basic materials are not affected by normal and bump maps so we
  15795. * return by default {@link normalViewGeometry}.
  15796. *
  15797. * @return {Node<vec3>} The normal node.
  15798. */
  15799. setupNormal() {
  15800. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15801. }
  15802. /**
  15803. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15804. * to implement the default environment mapping.
  15805. *
  15806. * @param {NodeBuilder} builder - The current node builder.
  15807. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15808. */
  15809. setupEnvironment( builder ) {
  15810. const envNode = super.setupEnvironment( builder );
  15811. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15812. }
  15813. /**
  15814. * This method must be overwritten since light maps are evaluated
  15815. * with a special scaling factor for basic materials.
  15816. *
  15817. * @param {NodeBuilder} builder - The current node builder.
  15818. * @return {?BasicLightMapNode<vec3>} The light map node.
  15819. */
  15820. setupLightMap( builder ) {
  15821. let node = null;
  15822. if ( builder.material.lightMap ) {
  15823. node = new BasicLightMapNode( materialLightMap );
  15824. }
  15825. return node;
  15826. }
  15827. /**
  15828. * The material overwrites this method because `lights` is set to `true` but
  15829. * we still want to return the diffuse color as the outgoing light.
  15830. *
  15831. * @return {Node<vec3>} The outgoing light node.
  15832. */
  15833. setupOutgoingLight() {
  15834. return diffuseColor.rgb;
  15835. }
  15836. /**
  15837. * Setups the lighting model.
  15838. *
  15839. * @return {BasicLightingModel} The lighting model.
  15840. */
  15841. setupLightingModel() {
  15842. return new BasicLightingModel();
  15843. }
  15844. }
  15845. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15846. // Original approximation by Christophe Schlick '94
  15847. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15848. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15849. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15850. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15851. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15852. } ); // validated
  15853. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15854. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15855. } ); // validated
  15856. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15857. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15858. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15859. } );
  15860. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15861. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15862. const dotNH = normalView.dot( halfDir ).clamp();
  15863. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15864. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15865. const G = G_BlinnPhong_Implicit();
  15866. const D = D_BlinnPhong( { dotNH } );
  15867. return F.mul( G ).mul( D );
  15868. } );
  15869. /**
  15870. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15871. *
  15872. * @augments BasicLightingModel
  15873. */
  15874. class PhongLightingModel extends BasicLightingModel {
  15875. /**
  15876. * Constructs a new phong lighting model.
  15877. *
  15878. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15879. */
  15880. constructor( specular = true ) {
  15881. super();
  15882. /**
  15883. * Whether specular is supported or not. Set this to `false` if you are
  15884. * looking for a Lambert-like material meaning a material for non-shiny
  15885. * surfaces, without specular highlights.
  15886. *
  15887. * @type {boolean}
  15888. * @default true
  15889. */
  15890. this.specular = specular;
  15891. }
  15892. /**
  15893. * Implements the direct lighting. The specular portion is optional an can be controlled
  15894. * with the {@link PhongLightingModel#specular} flag.
  15895. *
  15896. * @param {Object} lightData - The light data.
  15897. */
  15898. direct( { lightDirection, lightColor, reflectedLight } ) {
  15899. const dotNL = normalView.dot( lightDirection ).clamp();
  15900. const irradiance = dotNL.mul( lightColor );
  15901. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15902. if ( this.specular === true ) {
  15903. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15904. }
  15905. }
  15906. /**
  15907. * Implements the indirect lighting.
  15908. *
  15909. * @param {NodeBuilder} builder - The current node builder.
  15910. */
  15911. indirect( builder ) {
  15912. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15913. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15914. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15915. }
  15916. }
  15917. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15918. /**
  15919. * Node material version of {@link MeshLambertMaterial}.
  15920. *
  15921. * @augments NodeMaterial
  15922. */
  15923. class MeshLambertNodeMaterial extends NodeMaterial {
  15924. static get type() {
  15925. return 'MeshLambertNodeMaterial';
  15926. }
  15927. /**
  15928. * Constructs a new mesh lambert node material.
  15929. *
  15930. * @param {Object} [parameters] - The configuration parameter.
  15931. */
  15932. constructor( parameters ) {
  15933. super();
  15934. /**
  15935. * This flag can be used for type testing.
  15936. *
  15937. * @type {boolean}
  15938. * @readonly
  15939. * @default true
  15940. */
  15941. this.isMeshLambertNodeMaterial = true;
  15942. /**
  15943. * Set to `true` because lambert materials react on lights.
  15944. *
  15945. * @type {boolean}
  15946. * @default true
  15947. */
  15948. this.lights = true;
  15949. this.setDefaultValues( _defaultValues$8 );
  15950. this.setValues( parameters );
  15951. }
  15952. /**
  15953. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15954. * to implement the default environment mapping.
  15955. *
  15956. * @param {NodeBuilder} builder - The current node builder.
  15957. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15958. */
  15959. setupEnvironment( builder ) {
  15960. const envNode = super.setupEnvironment( builder );
  15961. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15962. }
  15963. /**
  15964. * Setups the lighting model.
  15965. *
  15966. * @return {PhongLightingModel} The lighting model.
  15967. */
  15968. setupLightingModel( /*builder*/ ) {
  15969. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15970. }
  15971. }
  15972. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15973. /**
  15974. * Node material version of {@link MeshPhongMaterial}.
  15975. *
  15976. * @augments NodeMaterial
  15977. */
  15978. class MeshPhongNodeMaterial extends NodeMaterial {
  15979. static get type() {
  15980. return 'MeshPhongNodeMaterial';
  15981. }
  15982. /**
  15983. * Constructs a new mesh lambert node material.
  15984. *
  15985. * @param {Object} [parameters] - The configuration parameter.
  15986. */
  15987. constructor( parameters ) {
  15988. super();
  15989. /**
  15990. * This flag can be used for type testing.
  15991. *
  15992. * @type {boolean}
  15993. * @readonly
  15994. * @default true
  15995. */
  15996. this.isMeshPhongNodeMaterial = true;
  15997. /**
  15998. * Set to `true` because phong materials react on lights.
  15999. *
  16000. * @type {boolean}
  16001. * @default true
  16002. */
  16003. this.lights = true;
  16004. /**
  16005. * The shininess of phong materials is by default inferred from the `shininess`
  16006. * property. This node property allows to overwrite the default
  16007. * and define the shininess with a node instead.
  16008. *
  16009. * If you don't want to overwrite the shininess but modify the existing
  16010. * value instead, use {@link materialShininess}.
  16011. *
  16012. * @type {?Node<float>}
  16013. * @default null
  16014. */
  16015. this.shininessNode = null;
  16016. /**
  16017. * The specular color of phong materials is by default inferred from the
  16018. * `specular` property. This node property allows to overwrite the default
  16019. * and define the specular color with a node instead.
  16020. *
  16021. * If you don't want to overwrite the specular color but modify the existing
  16022. * value instead, use {@link materialSpecular}.
  16023. *
  16024. * @type {?Node<vec3>}
  16025. * @default null
  16026. */
  16027. this.specularNode = null;
  16028. this.setDefaultValues( _defaultValues$7 );
  16029. this.setValues( parameters );
  16030. }
  16031. /**
  16032. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16033. * to implement the default environment mapping.
  16034. *
  16035. * @param {NodeBuilder} builder - The current node builder.
  16036. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16037. */
  16038. setupEnvironment( builder ) {
  16039. const envNode = super.setupEnvironment( builder );
  16040. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16041. }
  16042. /**
  16043. * Setups the lighting model.
  16044. *
  16045. * @return {PhongLightingModel} The lighting model.
  16046. */
  16047. setupLightingModel( /*builder*/ ) {
  16048. return new PhongLightingModel();
  16049. }
  16050. /**
  16051. * Setups the phong specific node variables.
  16052. *
  16053. * @param {NodeBuilder} builder - The current node builder.
  16054. */
  16055. setupVariants( /*builder*/ ) {
  16056. // SHININESS
  16057. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16058. shininess.assign( shininessNode );
  16059. // SPECULAR COLOR
  16060. const specularNode = this.specularNode || materialSpecular;
  16061. specularColor.assign( specularNode );
  16062. }
  16063. copy( source ) {
  16064. this.shininessNode = source.shininessNode;
  16065. this.specularNode = source.specularNode;
  16066. return super.copy( source );
  16067. }
  16068. }
  16069. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16070. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16071. return float( 0 );
  16072. }
  16073. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16074. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16075. return geometryRoughness;
  16076. } );
  16077. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16078. const { roughness } = inputs;
  16079. const geometryRoughness = getGeometryRoughness();
  16080. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16081. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16082. roughnessFactor = roughnessFactor.min( 1.0 );
  16083. return roughnessFactor;
  16084. } );
  16085. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16086. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16087. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16088. const a2 = alpha.pow2();
  16089. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16090. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16091. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16092. } ).setLayout( {
  16093. name: 'V_GGX_SmithCorrelated',
  16094. type: 'float',
  16095. inputs: [
  16096. { name: 'alpha', type: 'float' },
  16097. { name: 'dotNL', type: 'float' },
  16098. { name: 'dotNV', type: 'float' }
  16099. ]
  16100. } ); // validated
  16101. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16102. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16103. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16104. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16105. const v = div( 0.5, gv.add( gl ) );
  16106. return v.saturate();
  16107. } ).setLayout( {
  16108. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16109. type: 'float',
  16110. inputs: [
  16111. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16112. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16113. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16114. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16115. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16116. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16117. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16118. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16119. ]
  16120. } );
  16121. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16122. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16123. // alpha is "roughness squared" in Disney’s reparameterization
  16124. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16125. const a2 = alpha.pow2();
  16126. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16127. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16128. } ).setLayout( {
  16129. name: 'D_GGX',
  16130. type: 'float',
  16131. inputs: [
  16132. { name: 'alpha', type: 'float' },
  16133. { name: 'dotNH', type: 'float' }
  16134. ]
  16135. } ); // validated
  16136. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16137. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16138. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16139. const a2 = alphaT.mul( alphaB );
  16140. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16141. const v2 = v.dot( v );
  16142. const w2 = a2.div( v2 );
  16143. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16144. } ).setLayout( {
  16145. name: 'D_GGX_Anisotropic',
  16146. type: 'float',
  16147. inputs: [
  16148. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16149. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16150. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16151. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16152. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16153. ]
  16154. } );
  16155. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16156. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16157. const alpha = roughness.pow2(); // UE4's roughness
  16158. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16159. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16160. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16161. const dotNH = normalView$1.dot( halfDir ).clamp();
  16162. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16163. let F = F_Schlick( { f0, f90, dotVH } );
  16164. let V, D;
  16165. if ( defined( USE_IRIDESCENCE ) ) {
  16166. F = iridescence.mix( F, f );
  16167. }
  16168. if ( defined( USE_ANISOTROPY ) ) {
  16169. const dotTL = anisotropyT.dot( lightDirection );
  16170. const dotTV = anisotropyT.dot( positionViewDirection );
  16171. const dotTH = anisotropyT.dot( halfDir );
  16172. const dotBL = anisotropyB.dot( lightDirection );
  16173. const dotBV = anisotropyB.dot( positionViewDirection );
  16174. const dotBH = anisotropyB.dot( halfDir );
  16175. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16176. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16177. } else {
  16178. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16179. D = D_GGX( { alpha, dotNH } );
  16180. }
  16181. return F.mul( V ).mul( D );
  16182. } ); // validated
  16183. // Analytical approximation of the DFG LUT, one half of the
  16184. // split-sum approximation used in indirect specular lighting.
  16185. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  16186. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  16187. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16188. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  16189. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  16190. const r = roughness.mul( c0 ).add( c1 );
  16191. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  16192. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  16193. return fab;
  16194. } ).setLayout( {
  16195. name: 'DFGApprox',
  16196. type: 'vec2',
  16197. inputs: [
  16198. { name: 'roughness', type: 'float' },
  16199. { name: 'dotNV', type: 'vec3' }
  16200. ]
  16201. } );
  16202. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16203. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16204. const fab = DFGApprox( { dotNV, roughness } );
  16205. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16206. } );
  16207. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16208. const x = dotVH.oneMinus().saturate();
  16209. const x2 = x.mul( x );
  16210. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16211. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16212. } ).setLayout( {
  16213. name: 'Schlick_to_F0',
  16214. type: 'vec3',
  16215. inputs: [
  16216. { name: 'f', type: 'vec3' },
  16217. { name: 'f90', type: 'float' },
  16218. { name: 'dotVH', type: 'float' }
  16219. ]
  16220. } );
  16221. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16222. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16223. const alpha = roughness.pow2();
  16224. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16225. const invAlpha = float( 1.0 ).div( alpha );
  16226. const cos2h = dotNH.pow2();
  16227. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16228. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16229. } ).setLayout( {
  16230. name: 'D_Charlie',
  16231. type: 'float',
  16232. inputs: [
  16233. { name: 'roughness', type: 'float' },
  16234. { name: 'dotNH', type: 'float' }
  16235. ]
  16236. } );
  16237. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16238. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16239. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16240. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16241. } ).setLayout( {
  16242. name: 'V_Neubelt',
  16243. type: 'float',
  16244. inputs: [
  16245. { name: 'dotNV', type: 'float' },
  16246. { name: 'dotNL', type: 'float' }
  16247. ]
  16248. } );
  16249. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16250. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16251. const dotNL = normalView.dot( lightDirection ).clamp();
  16252. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16253. const dotNH = normalView.dot( halfDir ).clamp();
  16254. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16255. const V = V_Neubelt( { dotNV, dotNL } );
  16256. return sheen.mul( D ).mul( V );
  16257. } );
  16258. // Rect Area Light
  16259. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16260. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16261. // code: https://github.com/selfshadow/ltc_code/
  16262. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16263. const LUT_SIZE = 64.0;
  16264. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16265. const LUT_BIAS = 0.5 / LUT_SIZE;
  16266. const dotNV = N.dot( V ).saturate();
  16267. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16268. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16269. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16270. return uv;
  16271. } ).setLayout( {
  16272. name: 'LTC_Uv',
  16273. type: 'vec2',
  16274. inputs: [
  16275. { name: 'N', type: 'vec3' },
  16276. { name: 'V', type: 'vec3' },
  16277. { name: 'roughness', type: 'float' }
  16278. ]
  16279. } );
  16280. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16281. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16282. // An approximation of the form factor of a horizon-clipped rectangle.
  16283. const l = f.length();
  16284. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16285. } ).setLayout( {
  16286. name: 'LTC_ClippedSphereFormFactor',
  16287. type: 'float',
  16288. inputs: [
  16289. { name: 'f', type: 'vec3' }
  16290. ]
  16291. } );
  16292. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16293. const x = v1.dot( v2 );
  16294. const y = x.abs().toVar();
  16295. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16296. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16297. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16298. const v = a.div( b );
  16299. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16300. return v1.cross( v2 ).mul( theta_sintheta );
  16301. } ).setLayout( {
  16302. name: 'LTC_EdgeVectorFormFactor',
  16303. type: 'vec3',
  16304. inputs: [
  16305. { name: 'v1', type: 'vec3' },
  16306. { name: 'v2', type: 'vec3' }
  16307. ]
  16308. } );
  16309. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16310. // bail if point is on back side of plane of light
  16311. // assumes ccw winding order of light vertices
  16312. const v1 = p1.sub( p0 ).toVar();
  16313. const v2 = p3.sub( p0 ).toVar();
  16314. const lightNormal = v1.cross( v2 );
  16315. const result = vec3().toVar();
  16316. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16317. // construct orthonormal basis around N
  16318. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16319. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16320. // compute transform
  16321. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16322. // transform rect
  16323. // & project rect onto sphere
  16324. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16325. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16326. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16327. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16328. // calculate vector form factor
  16329. const vectorFormFactor = vec3( 0 ).toVar();
  16330. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16331. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16332. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16333. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16334. // adjust for horizon clipping
  16335. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16336. } );
  16337. return result;
  16338. } ).setLayout( {
  16339. name: 'LTC_Evaluate',
  16340. type: 'vec3',
  16341. inputs: [
  16342. { name: 'N', type: 'vec3' },
  16343. { name: 'V', type: 'vec3' },
  16344. { name: 'P', type: 'vec3' },
  16345. { name: 'mInv', type: 'mat3' },
  16346. { name: 'p0', type: 'vec3' },
  16347. { name: 'p1', type: 'vec3' },
  16348. { name: 'p2', type: 'vec3' },
  16349. { name: 'p3', type: 'vec3' }
  16350. ]
  16351. } );
  16352. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16353. // bail if point is on back side of plane of light
  16354. // assumes ccw winding order of light vertices
  16355. const v1 = p1.sub( p0 ).toVar();
  16356. const v2 = p3.sub( p0 ).toVar();
  16357. const lightNormal = v1.cross( v2 );
  16358. const result = vec3().toVar();
  16359. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16360. // transform rect
  16361. // & project rect onto sphere
  16362. const coords0 = p0.sub( P ).normalize().toVar();
  16363. const coords1 = p1.sub( P ).normalize().toVar();
  16364. const coords2 = p2.sub( P ).normalize().toVar();
  16365. const coords3 = p3.sub( P ).normalize().toVar();
  16366. // calculate vector form factor
  16367. const vectorFormFactor = vec3( 0 ).toVar();
  16368. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16369. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16370. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16371. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16372. // adjust for horizon clipping
  16373. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16374. } );
  16375. return result;
  16376. } ).setLayout( {
  16377. name: 'LTC_Evaluate',
  16378. type: 'vec3',
  16379. inputs: [
  16380. { name: 'P', type: 'vec3' },
  16381. { name: 'p0', type: 'vec3' },
  16382. { name: 'p1', type: 'vec3' },
  16383. { name: 'p2', type: 'vec3' },
  16384. { name: 'p3', type: 'vec3' }
  16385. ]
  16386. } );
  16387. // Mipped Bicubic Texture Filtering by N8
  16388. // https://www.shadertoy.com/view/Dl2SDW
  16389. const bC = 1.0 / 6.0;
  16390. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16391. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16392. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16393. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16394. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16395. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16396. // h0 and h1 are the two offset functions
  16397. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16398. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16399. const bicubic = ( textureNode, texelSize, lod ) => {
  16400. const uv = textureNode.uvNode;
  16401. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16402. const iuv = floor( uvScaled );
  16403. const fuv = fract( uvScaled );
  16404. const g0x = g0( fuv.x );
  16405. const g1x = g1( fuv.x );
  16406. const h0x = h0( fuv.x );
  16407. const h1x = h1( fuv.x );
  16408. const h0y = h0( fuv.y );
  16409. const h1y = h1( fuv.y );
  16410. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16411. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16412. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16413. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16414. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16415. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16416. return a.add( b );
  16417. };
  16418. /**
  16419. * Applies mipped bicubic texture filtering to the given texture node.
  16420. *
  16421. * @tsl
  16422. * @function
  16423. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16424. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16425. * @return {Node} The filtered texture sample.
  16426. */
  16427. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16428. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16429. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16430. const fLodSizeInv = div( 1.0, fLodSize );
  16431. const cLodSizeInv = div( 1.0, cLodSize );
  16432. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16433. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16434. return fract( lodNode ).mix( fSample, cSample );
  16435. } );
  16436. /**
  16437. * Applies mipped bicubic texture filtering to the given texture node.
  16438. *
  16439. * @tsl
  16440. * @function
  16441. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16442. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16443. * @return {Node} The filtered texture sample.
  16444. */
  16445. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16446. const lod = strength.mul( maxMipLevel( textureNode ) );
  16447. return textureBicubicLevel( textureNode, lod );
  16448. } );
  16449. //
  16450. // Transmission
  16451. //
  16452. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16453. // Direction of refracted light.
  16454. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16455. // Compute rotation-independent scaling of the model matrix.
  16456. const modelScale = vec3(
  16457. length( modelMatrix[ 0 ].xyz ),
  16458. length( modelMatrix[ 1 ].xyz ),
  16459. length( modelMatrix[ 2 ].xyz )
  16460. );
  16461. // The thickness is specified in local space.
  16462. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16463. } ).setLayout( {
  16464. name: 'getVolumeTransmissionRay',
  16465. type: 'vec3',
  16466. inputs: [
  16467. { name: 'n', type: 'vec3' },
  16468. { name: 'v', type: 'vec3' },
  16469. { name: 'thickness', type: 'float' },
  16470. { name: 'ior', type: 'float' },
  16471. { name: 'modelMatrix', type: 'mat4' }
  16472. ]
  16473. } );
  16474. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16475. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16476. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16477. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16478. } ).setLayout( {
  16479. name: 'applyIorToRoughness',
  16480. type: 'float',
  16481. inputs: [
  16482. { name: 'roughness', type: 'float' },
  16483. { name: 'ior', type: 'float' }
  16484. ]
  16485. } );
  16486. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16487. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16488. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16489. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16490. const transmissionSample = vTexture.sample( fragCoord );
  16491. //const transmissionSample = viewportMipTexture( fragCoord );
  16492. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16493. return textureBicubicLevel( transmissionSample, lod );
  16494. } );
  16495. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16496. If( attenuationDistance.notEqual( 0 ), () => {
  16497. // Compute light attenuation using Beer's law.
  16498. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16499. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16500. return transmittance;
  16501. } );
  16502. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16503. return vec3( 1.0 );
  16504. } ).setLayout( {
  16505. name: 'volumeAttenuation',
  16506. type: 'vec3',
  16507. inputs: [
  16508. { name: 'transmissionDistance', type: 'float' },
  16509. { name: 'attenuationColor', type: 'vec3' },
  16510. { name: 'attenuationDistance', type: 'float' }
  16511. ]
  16512. } );
  16513. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16514. let transmittedLight, transmittance;
  16515. if ( dispersion ) {
  16516. transmittedLight = vec4().toVar();
  16517. transmittance = vec3().toVar();
  16518. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16519. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16520. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16521. const ior = iors.element( i );
  16522. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16523. const refractedRayExit = position.add( transmissionRay );
  16524. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16525. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16526. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16527. refractionCoords.addAssign( 1.0 );
  16528. refractionCoords.divAssign( 2.0 );
  16529. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16530. // Sample framebuffer to get pixel the refracted ray hits.
  16531. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16532. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16533. transmittedLight.a.addAssign( transmissionSample.a );
  16534. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16535. } );
  16536. transmittedLight.a.divAssign( 3.0 );
  16537. } else {
  16538. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16539. const refractedRayExit = position.add( transmissionRay );
  16540. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16541. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16542. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16543. refractionCoords.addAssign( 1.0 );
  16544. refractionCoords.divAssign( 2.0 );
  16545. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16546. // Sample framebuffer to get pixel the refracted ray hits.
  16547. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16548. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16549. }
  16550. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16551. const dotNV = n.dot( v ).clamp();
  16552. // Get the specular component.
  16553. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16554. dotNV,
  16555. specularColor,
  16556. specularF90,
  16557. roughness
  16558. } ) );
  16559. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16560. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16561. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16562. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16563. } );
  16564. //
  16565. // Iridescence
  16566. //
  16567. // XYZ to linear-sRGB color space
  16568. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16569. 3.2404542, -0.969266, 0.0556434,
  16570. -1.5371385, 1.8760108, -0.2040259,
  16571. -0.4985314, 0.0415560, 1.0572252
  16572. );
  16573. // Assume air interface for top
  16574. // Note: We don't handle the case fresnel0 == 1
  16575. const Fresnel0ToIor = ( fresnel0 ) => {
  16576. const sqrtF0 = fresnel0.sqrt();
  16577. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16578. };
  16579. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16580. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16581. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16582. };
  16583. // Fresnel equations for dielectric/dielectric interfaces.
  16584. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16585. // Evaluation XYZ sensitivity curves in Fourier space
  16586. const evalSensitivity = ( OPD, shift ) => {
  16587. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16588. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16589. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16590. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16591. 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() );
  16592. 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() );
  16593. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16594. const rgb = XYZ_TO_REC709.mul( xyz );
  16595. return rgb;
  16596. };
  16597. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16598. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16599. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16600. // Evaluate the cosTheta on the base layer (Snell law)
  16601. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16602. // Handle TIR:
  16603. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16604. If( cosTheta2Sq.lessThan( 0 ), () => {
  16605. return vec3( 1.0 );
  16606. } );
  16607. const cosTheta2 = cosTheta2Sq.sqrt();
  16608. // First interface
  16609. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16610. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16611. //const R21 = R12;
  16612. const T121 = R12.oneMinus();
  16613. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16614. const phi21 = float( Math.PI ).sub( phi12 );
  16615. // Second interface
  16616. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16617. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16618. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16619. const phi23 = vec3(
  16620. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16621. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16622. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16623. );
  16624. // Phase shift
  16625. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16626. const phi = vec3( phi21 ).add( phi23 );
  16627. // Compound terms
  16628. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16629. const r123 = R123.sqrt();
  16630. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16631. // Reflectance term for m = 0 (DC term amplitude)
  16632. const C0 = R12.add( Rs );
  16633. const I = C0.toVar();
  16634. // Reflectance term for m > 0 (pairs of diracs)
  16635. const Cm = Rs.sub( T121 ).toVar();
  16636. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16637. Cm.mulAssign( r123 );
  16638. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16639. I.addAssign( Cm.mul( Sm ) );
  16640. } );
  16641. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16642. return I.max( vec3( 0.0 ) );
  16643. } ).setLayout( {
  16644. name: 'evalIridescence',
  16645. type: 'vec3',
  16646. inputs: [
  16647. { name: 'outsideIOR', type: 'float' },
  16648. { name: 'eta2', type: 'float' },
  16649. { name: 'cosTheta1', type: 'float' },
  16650. { name: 'thinFilmThickness', type: 'float' },
  16651. { name: 'baseF0', type: 'vec3' }
  16652. ]
  16653. } );
  16654. //
  16655. // Sheen
  16656. //
  16657. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16658. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16659. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16660. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16661. const dotNV = normal.dot( viewDir ).saturate();
  16662. const r2 = roughness.pow2();
  16663. const a = select(
  16664. roughness.lessThan( 0.25 ),
  16665. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16666. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16667. );
  16668. const b = select(
  16669. roughness.lessThan( 0.25 ),
  16670. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16671. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16672. );
  16673. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16674. return DG.mul( 1.0 / Math.PI ).saturate();
  16675. } );
  16676. const clearcoatF0 = vec3( 0.04 );
  16677. const clearcoatF90 = float( 1 );
  16678. /**
  16679. * Represents the lighting model for a PBR material.
  16680. *
  16681. * @augments LightingModel
  16682. */
  16683. class PhysicalLightingModel extends LightingModel {
  16684. /**
  16685. * Constructs a new physical lighting model.
  16686. *
  16687. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16688. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16689. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16690. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16691. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16692. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16693. */
  16694. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16695. super();
  16696. /**
  16697. * Whether clearcoat is supported or not.
  16698. *
  16699. * @type {boolean}
  16700. * @default false
  16701. */
  16702. this.clearcoat = clearcoat;
  16703. /**
  16704. * Whether sheen is supported or not.
  16705. *
  16706. * @type {boolean}
  16707. * @default false
  16708. */
  16709. this.sheen = sheen;
  16710. /**
  16711. * Whether iridescence is supported or not.
  16712. *
  16713. * @type {boolean}
  16714. * @default false
  16715. */
  16716. this.iridescence = iridescence;
  16717. /**
  16718. * Whether anisotropy is supported or not.
  16719. *
  16720. * @type {boolean}
  16721. * @default false
  16722. */
  16723. this.anisotropy = anisotropy;
  16724. /**
  16725. * Whether transmission is supported or not.
  16726. *
  16727. * @type {boolean}
  16728. * @default false
  16729. */
  16730. this.transmission = transmission;
  16731. /**
  16732. * Whether dispersion is supported or not.
  16733. *
  16734. * @type {boolean}
  16735. * @default false
  16736. */
  16737. this.dispersion = dispersion;
  16738. /**
  16739. * The clear coat radiance.
  16740. *
  16741. * @type {?Node}
  16742. * @default null
  16743. */
  16744. this.clearcoatRadiance = null;
  16745. /**
  16746. * The clear coat specular direct.
  16747. *
  16748. * @type {?Node}
  16749. * @default null
  16750. */
  16751. this.clearcoatSpecularDirect = null;
  16752. /**
  16753. * The clear coat specular indirect.
  16754. *
  16755. * @type {?Node}
  16756. * @default null
  16757. */
  16758. this.clearcoatSpecularIndirect = null;
  16759. /**
  16760. * The sheen specular direct.
  16761. *
  16762. * @type {?Node}
  16763. * @default null
  16764. */
  16765. this.sheenSpecularDirect = null;
  16766. /**
  16767. * The sheen specular indirect.
  16768. *
  16769. * @type {?Node}
  16770. * @default null
  16771. */
  16772. this.sheenSpecularIndirect = null;
  16773. /**
  16774. * The iridescence Fresnel.
  16775. *
  16776. * @type {?Node}
  16777. * @default null
  16778. */
  16779. this.iridescenceFresnel = null;
  16780. /**
  16781. * The iridescence F0.
  16782. *
  16783. * @type {?Node}
  16784. * @default null
  16785. */
  16786. this.iridescenceF0 = null;
  16787. }
  16788. /**
  16789. * Depending on what features are requested, the method prepares certain node variables
  16790. * which are later used for lighting computations.
  16791. *
  16792. * @param {NodeBuilder} builder - The current node builder.
  16793. */
  16794. start( builder ) {
  16795. if ( this.clearcoat === true ) {
  16796. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16797. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16798. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16799. }
  16800. if ( this.sheen === true ) {
  16801. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16802. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16803. }
  16804. if ( this.iridescence === true ) {
  16805. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16806. this.iridescenceFresnel = evalIridescence( {
  16807. outsideIOR: float( 1.0 ),
  16808. eta2: iridescenceIOR,
  16809. cosTheta1: dotNVi,
  16810. thinFilmThickness: iridescenceThickness,
  16811. baseF0: specularColor
  16812. } );
  16813. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16814. }
  16815. if ( this.transmission === true ) {
  16816. const position = positionWorld;
  16817. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16818. const n = normalWorld;
  16819. const context = builder.context;
  16820. context.backdrop = getIBLVolumeRefraction(
  16821. n,
  16822. v,
  16823. roughness,
  16824. diffuseColor,
  16825. specularColor,
  16826. specularF90, // specularF90
  16827. position, // positionWorld
  16828. modelWorldMatrix, // modelMatrix
  16829. cameraViewMatrix, // viewMatrix
  16830. cameraProjectionMatrix, // projMatrix
  16831. ior,
  16832. thickness,
  16833. attenuationColor,
  16834. attenuationDistance,
  16835. this.dispersion ? dispersion : null
  16836. );
  16837. context.backdropAlpha = transmission;
  16838. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16839. }
  16840. super.start( builder );
  16841. }
  16842. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16843. // Approximates multi-scattering in order to preserve energy.
  16844. // http://www.jcgt.org/published/0008/01/03/
  16845. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16846. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16847. const fab = DFGApprox( { roughness, dotNV } );
  16848. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16849. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16850. const Ess = fab.x.add( fab.y );
  16851. const Ems = Ess.oneMinus();
  16852. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16853. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16854. singleScatter.addAssign( FssEss );
  16855. multiScatter.addAssign( Fms.mul( Ems ) );
  16856. }
  16857. /**
  16858. * Implements the direct light.
  16859. *
  16860. * @param {Object} lightData - The light data.
  16861. * @param {NodeBuilder} builder - The current node builder.
  16862. */
  16863. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16864. const dotNL = normalView.dot( lightDirection ).clamp();
  16865. const irradiance = dotNL.mul( lightColor );
  16866. if ( this.sheen === true ) {
  16867. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16868. }
  16869. if ( this.clearcoat === true ) {
  16870. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16871. const ccIrradiance = dotNLcc.mul( lightColor );
  16872. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16873. }
  16874. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16875. 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 } ) ) );
  16876. }
  16877. /**
  16878. * This method is intended for implementing the direct light term for
  16879. * rect area light nodes.
  16880. *
  16881. * @param {Object} input - The input data.
  16882. * @param {NodeBuilder} builder - The current node builder.
  16883. */
  16884. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16885. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16886. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16887. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16888. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16889. const N = normalView;
  16890. const V = positionViewDirection;
  16891. const P = positionView.toVar();
  16892. const uv = LTC_Uv( { N, V, roughness } );
  16893. const t1 = ltc_1.sample( uv ).toVar();
  16894. const t2 = ltc_2.sample( uv ).toVar();
  16895. const mInv = mat3(
  16896. vec3( t1.x, 0, t1.y ),
  16897. vec3( 0, 1, 0 ),
  16898. vec3( t1.z, 0, t1.w )
  16899. ).toVar();
  16900. // LTC Fresnel Approximation by Stephen Hill
  16901. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16902. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16903. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16904. 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 } ) ) );
  16905. }
  16906. /**
  16907. * Implements the indirect lighting.
  16908. *
  16909. * @param {NodeBuilder} builder - The current node builder.
  16910. */
  16911. indirect( builder ) {
  16912. this.indirectDiffuse( builder );
  16913. this.indirectSpecular( builder );
  16914. this.ambientOcclusion( builder );
  16915. }
  16916. /**
  16917. * Implements the indirect diffuse term.
  16918. *
  16919. * @param {NodeBuilder} builder - The current node builder.
  16920. */
  16921. indirectDiffuse( builder ) {
  16922. const { irradiance, reflectedLight } = builder.context;
  16923. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16924. }
  16925. /**
  16926. * Implements the indirect specular term.
  16927. *
  16928. * @param {NodeBuilder} builder - The current node builder.
  16929. */
  16930. indirectSpecular( builder ) {
  16931. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16932. if ( this.sheen === true ) {
  16933. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16934. sheen,
  16935. IBLSheenBRDF( {
  16936. normal: normalView,
  16937. viewDir: positionViewDirection,
  16938. roughness: sheenRoughness
  16939. } )
  16940. ) );
  16941. }
  16942. if ( this.clearcoat === true ) {
  16943. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16944. const clearcoatEnv = EnvironmentBRDF( {
  16945. dotNV: dotNVcc,
  16946. specularColor: clearcoatF0,
  16947. specularF90: clearcoatF90,
  16948. roughness: clearcoatRoughness
  16949. } );
  16950. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16951. }
  16952. // Both indirect specular and indirect diffuse light accumulate here
  16953. const singleScattering = vec3().toVar( 'singleScattering' );
  16954. const multiScattering = vec3().toVar( 'multiScattering' );
  16955. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16956. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16957. const totalScattering = singleScattering.add( multiScattering );
  16958. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16959. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16960. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16961. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16962. }
  16963. /**
  16964. * Implements the ambient occlusion term.
  16965. *
  16966. * @param {NodeBuilder} builder - The current node builder.
  16967. */
  16968. ambientOcclusion( builder ) {
  16969. const { ambientOcclusion, reflectedLight } = builder.context;
  16970. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16971. const aoNV = dotNV.add( ambientOcclusion );
  16972. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16973. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16974. if ( this.clearcoat === true ) {
  16975. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16976. }
  16977. if ( this.sheen === true ) {
  16978. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16979. }
  16980. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16981. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16982. }
  16983. /**
  16984. * Used for final lighting accumulations depending on the requested features.
  16985. *
  16986. * @param {NodeBuilder} builder - The current node builder.
  16987. */
  16988. finish( { context } ) {
  16989. const { outgoingLight } = context;
  16990. if ( this.clearcoat === true ) {
  16991. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16992. const Fcc = F_Schlick( {
  16993. dotVH: dotNVcc,
  16994. f0: clearcoatF0,
  16995. f90: clearcoatF90
  16996. } );
  16997. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16998. outgoingLight.assign( clearcoatLight );
  16999. }
  17000. if ( this.sheen === true ) {
  17001. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  17002. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  17003. outgoingLight.assign( sheenLight );
  17004. }
  17005. }
  17006. }
  17007. // These defines must match with PMREMGenerator
  17008. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17009. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17010. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17011. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17012. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17013. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17014. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17015. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17016. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17017. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17018. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17019. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17020. // These shader functions convert between the UV coordinates of a single face of
  17021. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17022. // sampling a textureCube (not generally normalized ).
  17023. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17024. const absDirection = vec3( abs( direction ) ).toVar();
  17025. const face = float( -1 ).toVar();
  17026. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17027. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17028. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17029. } ).Else( () => {
  17030. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17031. } );
  17032. } ).Else( () => {
  17033. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17034. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17035. } ).Else( () => {
  17036. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17037. } );
  17038. } );
  17039. return face;
  17040. } ).setLayout( {
  17041. name: 'getFace',
  17042. type: 'float',
  17043. inputs: [
  17044. { name: 'direction', type: 'vec3' }
  17045. ]
  17046. } );
  17047. // RH coordinate system; PMREM face-indexing convention
  17048. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17049. const uv = vec2().toVar();
  17050. If( face.equal( 0.0 ), () => {
  17051. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17052. } ).ElseIf( face.equal( 1.0 ), () => {
  17053. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17054. } ).ElseIf( face.equal( 2.0 ), () => {
  17055. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17056. } ).ElseIf( face.equal( 3.0 ), () => {
  17057. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17058. } ).ElseIf( face.equal( 4.0 ), () => {
  17059. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17060. } ).Else( () => {
  17061. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17062. } );
  17063. return mul( 0.5, uv.add( 1.0 ) );
  17064. } ).setLayout( {
  17065. name: 'getUV',
  17066. type: 'vec2',
  17067. inputs: [
  17068. { name: 'direction', type: 'vec3' },
  17069. { name: 'face', type: 'float' }
  17070. ]
  17071. } );
  17072. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17073. const mip = float( 0.0 ).toVar();
  17074. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17075. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17076. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17077. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17078. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17079. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17080. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17081. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17082. } ).Else( () => {
  17083. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17084. } );
  17085. return mip;
  17086. } ).setLayout( {
  17087. name: 'roughnessToMip',
  17088. type: 'float',
  17089. inputs: [
  17090. { name: 'roughness', type: 'float' }
  17091. ]
  17092. } );
  17093. // RH coordinate system; PMREM face-indexing convention
  17094. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17095. const uv = uv_immutable.toVar();
  17096. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17097. const direction = vec3( uv, 1.0 ).toVar();
  17098. If( face.equal( 0.0 ), () => {
  17099. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17100. } ).ElseIf( face.equal( 1.0 ), () => {
  17101. direction.assign( direction.xzy );
  17102. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17103. } ).ElseIf( face.equal( 2.0 ), () => {
  17104. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17105. } ).ElseIf( face.equal( 3.0 ), () => {
  17106. direction.assign( direction.zyx );
  17107. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17108. } ).ElseIf( face.equal( 4.0 ), () => {
  17109. direction.assign( direction.xzy );
  17110. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17111. } ).ElseIf( face.equal( 5.0 ), () => {
  17112. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17113. } );
  17114. return direction;
  17115. } ).setLayout( {
  17116. name: 'getDirection',
  17117. type: 'vec3',
  17118. inputs: [
  17119. { name: 'uv', type: 'vec2' },
  17120. { name: 'face', type: 'float' }
  17121. ]
  17122. } );
  17123. //
  17124. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17125. const roughness = float( roughness_immutable );
  17126. const sampleDir = vec3( sampleDir_immutable );
  17127. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17128. const mipF = fract( mip );
  17129. const mipInt = floor( mip );
  17130. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17131. If( mipF.notEqual( 0.0 ), () => {
  17132. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17133. color0.assign( mix( color0, color1, mipF ) );
  17134. } );
  17135. return color0;
  17136. } );
  17137. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17138. const mipInt = float( mipInt_immutable ).toVar();
  17139. const direction = vec3( direction_immutable );
  17140. const face = float( getFace( direction ) ).toVar();
  17141. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17142. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17143. const faceSize = float( exp2( mipInt ) ).toVar();
  17144. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17145. If( face.greaterThan( 2.0 ), () => {
  17146. uv.y.addAssign( faceSize );
  17147. face.subAssign( 3.0 );
  17148. } );
  17149. uv.x.addAssign( face.mul( faceSize ) );
  17150. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17151. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17152. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17153. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17154. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17155. } );
  17156. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17157. const cosTheta = cos( theta );
  17158. // Rodrigues' axis-angle rotation
  17159. const sampleDirection = outputDirection.mul( cosTheta )
  17160. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17161. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17162. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17163. } );
  17164. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17165. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17166. If( axis.equal( vec3( 0.0 ) ), () => {
  17167. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17168. } );
  17169. axis.assign( normalize( axis ) );
  17170. const gl_FragColor = vec3().toVar();
  17171. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17172. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17173. If( i.greaterThanEqual( samples ), () => {
  17174. Break();
  17175. } );
  17176. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17177. 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 } ) ) );
  17178. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17179. } );
  17180. return vec4( gl_FragColor, 1 );
  17181. } );
  17182. const LOD_MIN = 4;
  17183. // The standard deviations (radians) associated with the extra mips. These are
  17184. // chosen to approximate a Trowbridge-Reitz distribution function times the
  17185. // geometric shadowing function. These sigma values squared must match the
  17186. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  17187. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17188. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17189. // samples and exit early, but not recompile the shader.
  17190. const MAX_SAMPLES = 20;
  17191. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17192. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17193. const _clearColor$2 = /*@__PURE__*/ new Color();
  17194. let _oldTarget = null;
  17195. let _oldActiveCubeFace = 0;
  17196. let _oldActiveMipmapLevel = 0;
  17197. // Golden Ratio
  17198. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  17199. const INV_PHI = 1 / PHI;
  17200. // Vertices of a dodecahedron (except the opposites, which represent the
  17201. // same axis), used as axis directions evenly spread on a sphere.
  17202. const _axisDirections = [
  17203. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  17204. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  17205. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  17206. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  17207. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  17208. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  17209. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  17210. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  17211. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  17212. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  17213. ];
  17214. const _origin = /*@__PURE__*/ new Vector3();
  17215. // maps blur materials to their uniforms dictionary
  17216. const _uniformsMap = new WeakMap();
  17217. // WebGPU Face indices
  17218. const _faceLib = [
  17219. 3, 1, 5,
  17220. 0, 4, 2
  17221. ];
  17222. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17223. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17224. /**
  17225. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17226. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17227. * blur to be quickly accessed based on material roughness. It is packed into a
  17228. * special CubeUV format that allows us to perform custom interpolation so that
  17229. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17230. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17231. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17232. * higher roughness levels. In this way we maintain resolution to smoothly
  17233. * interpolate diffuse lighting while limiting sampling computation.
  17234. *
  17235. * Paper: Fast, Accurate Image-Based Lighting:
  17236. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  17237. */
  17238. class PMREMGenerator {
  17239. /**
  17240. * Constructs a new PMREM generator.
  17241. *
  17242. * @param {Renderer} renderer - The renderer.
  17243. */
  17244. constructor( renderer ) {
  17245. this._renderer = renderer;
  17246. this._pingPongRenderTarget = null;
  17247. this._lodMax = 0;
  17248. this._cubeSize = 0;
  17249. this._lodPlanes = [];
  17250. this._sizeLods = [];
  17251. this._sigmas = [];
  17252. this._lodMeshes = [];
  17253. this._blurMaterial = null;
  17254. this._cubemapMaterial = null;
  17255. this._equirectMaterial = null;
  17256. this._backgroundBox = null;
  17257. }
  17258. get _hasInitialized() {
  17259. return this._renderer.hasInitialized();
  17260. }
  17261. /**
  17262. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17263. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17264. * in radians to be applied to the scene before PMREM generation. Optional near
  17265. * and far planes ensure the scene is rendered in its entirety.
  17266. *
  17267. * @param {Scene} scene - The scene to be captured.
  17268. * @param {number} [sigma=0] - The blur radius in radians.
  17269. * @param {number} [near=0.1] - The near plane distance.
  17270. * @param {number} [far=100] - The far plane distance.
  17271. * @param {Object} [options={}] - The configuration options.
  17272. * @param {number} [options.size=256] - The texture size of the PMREM.
  17273. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17274. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17275. * @return {RenderTarget} The resulting PMREM.
  17276. * @see {@link PMREMGenerator#fromSceneAsync}
  17277. */
  17278. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17279. const {
  17280. size = 256,
  17281. position = _origin,
  17282. renderTarget = null,
  17283. } = options;
  17284. this._setSize( size );
  17285. if ( this._hasInitialized === false ) {
  17286. warn( 'PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  17287. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17288. options.renderTarget = cubeUVRenderTarget;
  17289. this.fromSceneAsync( scene, sigma, near, far, options );
  17290. return cubeUVRenderTarget;
  17291. }
  17292. _oldTarget = this._renderer.getRenderTarget();
  17293. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17294. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17295. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17296. cubeUVRenderTarget.depthBuffer = true;
  17297. this._init( cubeUVRenderTarget );
  17298. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17299. if ( sigma > 0 ) {
  17300. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17301. }
  17302. this._applyPMREM( cubeUVRenderTarget );
  17303. this._cleanup( cubeUVRenderTarget );
  17304. return cubeUVRenderTarget;
  17305. }
  17306. /**
  17307. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17308. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17309. * in radians to be applied to the scene before PMREM generation. Optional near
  17310. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17311. * is placed at the origin).
  17312. *
  17313. * @param {Scene} scene - The scene to be captured.
  17314. * @param {number} [sigma=0] - The blur radius in radians.
  17315. * @param {number} [near=0.1] - The near plane distance.
  17316. * @param {number} [far=100] - The far plane distance.
  17317. * @param {Object} [options={}] - The configuration options.
  17318. * @param {number} [options.size=256] - The texture size of the PMREM.
  17319. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17320. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17321. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17322. * @see {@link PMREMGenerator#fromScene}
  17323. */
  17324. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17325. if ( this._hasInitialized === false ) await this._renderer.init();
  17326. return this.fromScene( scene, sigma, near, far, options );
  17327. }
  17328. /**
  17329. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17330. * or HDR. The ideal input image size is 1k (1024 x 512),
  17331. * as this matches best with the 256 x 256 cubemap output.
  17332. *
  17333. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17334. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17335. * @return {RenderTarget} The resulting PMREM.
  17336. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17337. */
  17338. fromEquirectangular( equirectangular, renderTarget = null ) {
  17339. if ( this._hasInitialized === false ) {
  17340. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  17341. this._setSizeFromTexture( equirectangular );
  17342. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17343. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17344. return cubeUVRenderTarget;
  17345. }
  17346. return this._fromTexture( equirectangular, renderTarget );
  17347. }
  17348. /**
  17349. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17350. * or HDR. The ideal input image size is 1k (1024 x 512),
  17351. * as this matches best with the 256 x 256 cubemap output.
  17352. *
  17353. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17354. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17355. * @return {Promise<RenderTarget>} The resulting PMREM.
  17356. * @see {@link PMREMGenerator#fromEquirectangular}
  17357. */
  17358. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17359. if ( this._hasInitialized === false ) await this._renderer.init();
  17360. return this._fromTexture( equirectangular, renderTarget );
  17361. }
  17362. /**
  17363. * Generates a PMREM from an cubemap texture, which can be either LDR
  17364. * or HDR. The ideal input cube size is 256 x 256,
  17365. * as this matches best with the 256 x 256 cubemap output.
  17366. *
  17367. * @param {Texture} cubemap - The cubemap texture to be converted.
  17368. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17369. * @return {RenderTarget} The resulting PMREM.
  17370. * @see {@link PMREMGenerator#fromCubemapAsync}
  17371. */
  17372. fromCubemap( cubemap, renderTarget = null ) {
  17373. if ( this._hasInitialized === false ) {
  17374. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17375. this._setSizeFromTexture( cubemap );
  17376. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17377. this.fromCubemapAsync( cubemap, renderTarget );
  17378. return cubeUVRenderTarget;
  17379. }
  17380. return this._fromTexture( cubemap, renderTarget );
  17381. }
  17382. /**
  17383. * Generates a PMREM from an cubemap texture, which can be either LDR
  17384. * or HDR. The ideal input cube size is 256 x 256,
  17385. * with the 256 x 256 cubemap output.
  17386. *
  17387. * @param {Texture} cubemap - The cubemap texture to be converted.
  17388. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17389. * @return {Promise<RenderTarget>} The resulting PMREM.
  17390. * @see {@link PMREMGenerator#fromCubemap}
  17391. */
  17392. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17393. if ( this._hasInitialized === false ) await this._renderer.init();
  17394. return this._fromTexture( cubemap, renderTarget );
  17395. }
  17396. /**
  17397. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17398. * your texture's network fetch for increased concurrency.
  17399. *
  17400. * @returns {Promise}
  17401. */
  17402. async compileCubemapShader() {
  17403. if ( this._cubemapMaterial === null ) {
  17404. this._cubemapMaterial = _getCubemapMaterial();
  17405. await this._compileMaterial( this._cubemapMaterial );
  17406. }
  17407. }
  17408. /**
  17409. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17410. * your texture's network fetch for increased concurrency.
  17411. *
  17412. * @returns {Promise}
  17413. */
  17414. async compileEquirectangularShader() {
  17415. if ( this._equirectMaterial === null ) {
  17416. this._equirectMaterial = _getEquirectMaterial();
  17417. await this._compileMaterial( this._equirectMaterial );
  17418. }
  17419. }
  17420. /**
  17421. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17422. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17423. * one of them will cause any others to also become unusable.
  17424. */
  17425. dispose() {
  17426. this._dispose();
  17427. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17428. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17429. if ( this._backgroundBox !== null ) {
  17430. this._backgroundBox.geometry.dispose();
  17431. this._backgroundBox.material.dispose();
  17432. }
  17433. }
  17434. // private interface
  17435. _setSizeFromTexture( texture ) {
  17436. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17437. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17438. } else { // Equirectangular
  17439. this._setSize( texture.image.width / 4 );
  17440. }
  17441. }
  17442. _setSize( cubeSize ) {
  17443. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17444. this._cubeSize = Math.pow( 2, this._lodMax );
  17445. }
  17446. _dispose() {
  17447. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17448. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17449. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17450. this._lodPlanes[ i ].dispose();
  17451. }
  17452. }
  17453. _cleanup( outputTarget ) {
  17454. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17455. outputTarget.scissorTest = false;
  17456. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17457. }
  17458. _fromTexture( texture, renderTarget ) {
  17459. this._setSizeFromTexture( texture );
  17460. _oldTarget = this._renderer.getRenderTarget();
  17461. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17462. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17463. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17464. this._init( cubeUVRenderTarget );
  17465. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17466. this._applyPMREM( cubeUVRenderTarget );
  17467. this._cleanup( cubeUVRenderTarget );
  17468. return cubeUVRenderTarget;
  17469. }
  17470. _allocateTarget() {
  17471. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17472. const height = 4 * this._cubeSize;
  17473. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17474. return cubeUVRenderTarget;
  17475. }
  17476. _init( renderTarget ) {
  17477. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17478. if ( this._pingPongRenderTarget !== null ) {
  17479. this._dispose();
  17480. }
  17481. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17482. const { _lodMax } = this;
  17483. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17484. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17485. }
  17486. }
  17487. async _compileMaterial( material ) {
  17488. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17489. await this._renderer.compile( tmpMesh, _flatCamera );
  17490. }
  17491. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17492. const cubeCamera = _cubeCamera;
  17493. cubeCamera.near = near;
  17494. cubeCamera.far = far;
  17495. // px, py, pz, nx, ny, nz
  17496. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17497. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17498. const renderer = this._renderer;
  17499. const originalAutoClear = renderer.autoClear;
  17500. renderer.getClearColor( _clearColor$2 );
  17501. renderer.autoClear = false;
  17502. let backgroundBox = this._backgroundBox;
  17503. if ( backgroundBox === null ) {
  17504. const backgroundMaterial = new MeshBasicMaterial( {
  17505. name: 'PMREM.Background',
  17506. side: BackSide,
  17507. depthWrite: false,
  17508. depthTest: false
  17509. } );
  17510. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17511. }
  17512. let useSolidColor = false;
  17513. const background = scene.background;
  17514. if ( background ) {
  17515. if ( background.isColor ) {
  17516. backgroundBox.material.color.copy( background );
  17517. scene.background = null;
  17518. useSolidColor = true;
  17519. }
  17520. } else {
  17521. backgroundBox.material.color.copy( _clearColor$2 );
  17522. useSolidColor = true;
  17523. }
  17524. renderer.setRenderTarget( cubeUVRenderTarget );
  17525. renderer.clear();
  17526. if ( useSolidColor ) {
  17527. renderer.render( backgroundBox, cubeCamera );
  17528. }
  17529. for ( let i = 0; i < 6; i ++ ) {
  17530. const col = i % 3;
  17531. if ( col === 0 ) {
  17532. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17533. cubeCamera.position.set( position.x, position.y, position.z );
  17534. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17535. } else if ( col === 1 ) {
  17536. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17537. cubeCamera.position.set( position.x, position.y, position.z );
  17538. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17539. } else {
  17540. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17541. cubeCamera.position.set( position.x, position.y, position.z );
  17542. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17543. }
  17544. const size = this._cubeSize;
  17545. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17546. renderer.render( scene, cubeCamera );
  17547. }
  17548. renderer.autoClear = originalAutoClear;
  17549. scene.background = background;
  17550. }
  17551. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17552. const renderer = this._renderer;
  17553. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17554. if ( isCubeTexture ) {
  17555. if ( this._cubemapMaterial === null ) {
  17556. this._cubemapMaterial = _getCubemapMaterial( texture );
  17557. }
  17558. } else {
  17559. if ( this._equirectMaterial === null ) {
  17560. this._equirectMaterial = _getEquirectMaterial( texture );
  17561. }
  17562. }
  17563. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17564. material.fragmentNode.value = texture;
  17565. const mesh = this._lodMeshes[ 0 ];
  17566. mesh.material = material;
  17567. const size = this._cubeSize;
  17568. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17569. renderer.setRenderTarget( cubeUVRenderTarget );
  17570. renderer.render( mesh, _flatCamera );
  17571. }
  17572. _applyPMREM( cubeUVRenderTarget ) {
  17573. const renderer = this._renderer;
  17574. const autoClear = renderer.autoClear;
  17575. renderer.autoClear = false;
  17576. const n = this._lodPlanes.length;
  17577. for ( let i = 1; i < n; i ++ ) {
  17578. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17579. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17580. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17581. }
  17582. renderer.autoClear = autoClear;
  17583. }
  17584. /**
  17585. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17586. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17587. * the blur latitudinally (around the poles), and then longitudinally (towards
  17588. * the poles) to approximate the orthogonally-separable blur. It is least
  17589. * accurate at the poles, but still does a decent job.
  17590. *
  17591. * @private
  17592. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17593. * @param {number} lodIn - The input level-of-detail.
  17594. * @param {number} lodOut - The output level-of-detail.
  17595. * @param {number} sigma - The blur radius in radians.
  17596. * @param {Vector3} [poleAxis] - The pole axis.
  17597. */
  17598. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17599. const pingPongRenderTarget = this._pingPongRenderTarget;
  17600. this._halfBlur(
  17601. cubeUVRenderTarget,
  17602. pingPongRenderTarget,
  17603. lodIn,
  17604. lodOut,
  17605. sigma,
  17606. 'latitudinal',
  17607. poleAxis );
  17608. this._halfBlur(
  17609. pingPongRenderTarget,
  17610. cubeUVRenderTarget,
  17611. lodOut,
  17612. lodOut,
  17613. sigma,
  17614. 'longitudinal',
  17615. poleAxis );
  17616. }
  17617. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17618. const renderer = this._renderer;
  17619. const blurMaterial = this._blurMaterial;
  17620. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17621. error( 'blur direction must be either latitudinal or longitudinal!' );
  17622. }
  17623. // Number of standard deviations at which to cut off the discrete approximation.
  17624. const STANDARD_DEVIATIONS = 3;
  17625. const blurMesh = this._lodMeshes[ lodOut ];
  17626. blurMesh.material = blurMaterial;
  17627. const blurUniforms = _uniformsMap.get( blurMaterial );
  17628. const pixels = this._sizeLods[ lodIn ] - 1;
  17629. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17630. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17631. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17632. if ( samples > MAX_SAMPLES ) {
  17633. warn( `sigmaRadians, ${
  17634. sigmaRadians}, is too large and will clip, as it requested ${
  17635. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17636. }
  17637. const weights = [];
  17638. let sum = 0;
  17639. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17640. const x = i / sigmaPixels;
  17641. const weight = Math.exp( - x * x / 2 );
  17642. weights.push( weight );
  17643. if ( i === 0 ) {
  17644. sum += weight;
  17645. } else if ( i < samples ) {
  17646. sum += 2 * weight;
  17647. }
  17648. }
  17649. for ( let i = 0; i < weights.length; i ++ ) {
  17650. weights[ i ] = weights[ i ] / sum;
  17651. }
  17652. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17653. blurUniforms.envMap.value = targetIn.texture;
  17654. blurUniforms.samples.value = samples;
  17655. blurUniforms.weights.array = weights;
  17656. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17657. if ( poleAxis ) {
  17658. blurUniforms.poleAxis.value = poleAxis;
  17659. }
  17660. const { _lodMax } = this;
  17661. blurUniforms.dTheta.value = radiansPerPixel;
  17662. blurUniforms.mipInt.value = _lodMax - lodIn;
  17663. const outputSize = this._sizeLods[ lodOut ];
  17664. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17665. const y = 4 * ( this._cubeSize - outputSize );
  17666. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17667. renderer.setRenderTarget( targetOut );
  17668. renderer.render( blurMesh, _flatCamera );
  17669. }
  17670. }
  17671. function _createPlanes( lodMax ) {
  17672. const lodPlanes = [];
  17673. const sizeLods = [];
  17674. const sigmas = [];
  17675. const lodMeshes = [];
  17676. let lod = lodMax;
  17677. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17678. for ( let i = 0; i < totalLods; i ++ ) {
  17679. const sizeLod = Math.pow( 2, lod );
  17680. sizeLods.push( sizeLod );
  17681. let sigma = 1.0 / sizeLod;
  17682. if ( i > lodMax - LOD_MIN ) {
  17683. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17684. } else if ( i === 0 ) {
  17685. sigma = 0;
  17686. }
  17687. sigmas.push( sigma );
  17688. const texelSize = 1.0 / ( sizeLod - 2 );
  17689. const min = - texelSize;
  17690. const max = 1 + texelSize;
  17691. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17692. const cubeFaces = 6;
  17693. const vertices = 6;
  17694. const positionSize = 3;
  17695. const uvSize = 2;
  17696. const faceIndexSize = 1;
  17697. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17698. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17699. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17700. for ( let face = 0; face < cubeFaces; face ++ ) {
  17701. const x = ( face % 3 ) * 2 / 3 - 1;
  17702. const y = face > 2 ? 0 : -1;
  17703. const coordinates = [
  17704. x, y, 0,
  17705. x + 2 / 3, y, 0,
  17706. x + 2 / 3, y + 1, 0,
  17707. x, y, 0,
  17708. x + 2 / 3, y + 1, 0,
  17709. x, y + 1, 0
  17710. ];
  17711. const faceIdx = _faceLib[ face ];
  17712. position.set( coordinates, positionSize * vertices * faceIdx );
  17713. uv.set( uv1, uvSize * vertices * faceIdx );
  17714. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17715. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17716. }
  17717. const planes = new BufferGeometry();
  17718. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17719. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17720. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17721. lodPlanes.push( planes );
  17722. lodMeshes.push( new Mesh( planes, null ) );
  17723. if ( lod > LOD_MIN ) {
  17724. lod --;
  17725. }
  17726. }
  17727. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17728. }
  17729. function _createRenderTarget( width, height ) {
  17730. const params = {
  17731. magFilter: LinearFilter,
  17732. minFilter: LinearFilter,
  17733. generateMipmaps: false,
  17734. type: HalfFloatType,
  17735. format: RGBAFormat,
  17736. colorSpace: LinearSRGBColorSpace,
  17737. //depthBuffer: false
  17738. };
  17739. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17740. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17741. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17742. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17743. cubeUVRenderTarget.scissorTest = true;
  17744. return cubeUVRenderTarget;
  17745. }
  17746. function _setViewport( target, x, y, width, height ) {
  17747. target.viewport.set( x, y, width, height );
  17748. target.scissor.set( x, y, width, height );
  17749. }
  17750. function _getMaterial( type ) {
  17751. const material = new NodeMaterial();
  17752. material.depthTest = false;
  17753. material.depthWrite = false;
  17754. material.blending = NoBlending;
  17755. material.name = `PMREM_${ type }`;
  17756. return material;
  17757. }
  17758. function _getBlurShader( lodMax, width, height ) {
  17759. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17760. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17761. const dTheta = uniform( 0 );
  17762. const n = float( MAX_SAMPLES );
  17763. const latitudinal = uniform( 0 ); // false, bool
  17764. const samples = uniform( 1 ); // int
  17765. const envMap = texture( null );
  17766. const mipInt = uniform( 0 ); // int
  17767. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17768. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17769. const CUBEUV_MAX_MIP = float( lodMax );
  17770. const materialUniforms = {
  17771. n,
  17772. latitudinal,
  17773. weights,
  17774. poleAxis,
  17775. outputDirection: _outputDirection,
  17776. dTheta,
  17777. samples,
  17778. envMap,
  17779. mipInt,
  17780. CUBEUV_TEXEL_WIDTH,
  17781. CUBEUV_TEXEL_HEIGHT,
  17782. CUBEUV_MAX_MIP
  17783. };
  17784. const material = _getMaterial( 'blur' );
  17785. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17786. _uniformsMap.set( material, materialUniforms );
  17787. return material;
  17788. }
  17789. function _getCubemapMaterial( envTexture ) {
  17790. const material = _getMaterial( 'cubemap' );
  17791. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17792. return material;
  17793. }
  17794. function _getEquirectMaterial( envTexture ) {
  17795. const material = _getMaterial( 'equirect' );
  17796. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17797. return material;
  17798. }
  17799. const _cache = new WeakMap();
  17800. /**
  17801. * Generates the cubeUV size based on the given image height.
  17802. *
  17803. * @private
  17804. * @param {number} imageHeight - The image height.
  17805. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17806. */
  17807. function _generateCubeUVSize( imageHeight ) {
  17808. const maxMip = Math.log2( imageHeight ) - 2;
  17809. const texelHeight = 1.0 / imageHeight;
  17810. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17811. return { texelWidth, texelHeight, maxMip };
  17812. }
  17813. /**
  17814. * Generates a PMREM from the given texture.
  17815. *
  17816. * @private
  17817. * @param {Texture} texture - The texture to create the PMREM for.
  17818. * @param {Renderer} renderer - The renderer.
  17819. * @param {PMREMGenerator} generator - The PMREM generator.
  17820. * @return {?Texture} The PMREM.
  17821. */
  17822. function _getPMREMFromTexture( texture, renderer, generator ) {
  17823. const cache = _getCache( renderer );
  17824. let cacheTexture = cache.get( texture );
  17825. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17826. if ( pmremVersion !== texture.pmremVersion ) {
  17827. const image = texture.image;
  17828. if ( texture.isCubeTexture ) {
  17829. if ( isCubeMapReady( image ) ) {
  17830. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17831. } else {
  17832. return null;
  17833. }
  17834. } else {
  17835. if ( isEquirectangularMapReady( image ) ) {
  17836. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17837. } else {
  17838. return null;
  17839. }
  17840. }
  17841. cacheTexture.pmremVersion = texture.pmremVersion;
  17842. cache.set( texture, cacheTexture );
  17843. }
  17844. return cacheTexture.texture;
  17845. }
  17846. /**
  17847. * Returns a cache that stores generated PMREMs for the respective textures.
  17848. * A cache must be maintained per renderer since PMREMs are render target textures
  17849. * which can't be shared across render contexts.
  17850. *
  17851. * @private
  17852. * @param {Renderer} renderer - The renderer.
  17853. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17854. */
  17855. function _getCache( renderer ) {
  17856. let rendererCache = _cache.get( renderer );
  17857. if ( rendererCache === undefined ) {
  17858. rendererCache = new WeakMap();
  17859. _cache.set( renderer, rendererCache );
  17860. }
  17861. return rendererCache;
  17862. }
  17863. /**
  17864. * This node represents a PMREM which is a special type of preprocessed
  17865. * environment map intended for PBR materials.
  17866. *
  17867. * ```js
  17868. * const material = new MeshStandardNodeMaterial();
  17869. * material.envNode = pmremTexture( envMap );
  17870. * ```
  17871. *
  17872. * @augments TempNode
  17873. */
  17874. class PMREMNode extends TempNode {
  17875. static get type() {
  17876. return 'PMREMNode';
  17877. }
  17878. /**
  17879. * Constructs a new function overloading node.
  17880. *
  17881. * @param {Texture} value - The input texture.
  17882. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17883. * @param {Node<float>} [levelNode=null] - The level node.
  17884. */
  17885. constructor( value, uvNode = null, levelNode = null ) {
  17886. super( 'vec3' );
  17887. /**
  17888. * Reference to the input texture.
  17889. *
  17890. * @private
  17891. * @type {Texture}
  17892. */
  17893. this._value = value;
  17894. /**
  17895. * Reference to the generated PMREM.
  17896. *
  17897. * @private
  17898. * @type {Texture | null}
  17899. * @default null
  17900. */
  17901. this._pmrem = null;
  17902. /**
  17903. * The uv node.
  17904. *
  17905. * @type {Node<vec2>}
  17906. */
  17907. this.uvNode = uvNode;
  17908. /**
  17909. * The level node.
  17910. *
  17911. * @type {Node<float>}
  17912. */
  17913. this.levelNode = levelNode;
  17914. /**
  17915. * Reference to a PMREM generator.
  17916. *
  17917. * @private
  17918. * @type {?PMREMGenerator}
  17919. * @default null
  17920. */
  17921. this._generator = null;
  17922. const defaultTexture = new Texture();
  17923. defaultTexture.isRenderTargetTexture = true;
  17924. /**
  17925. * The texture node holding the generated PMREM.
  17926. *
  17927. * @private
  17928. * @type {TextureNode}
  17929. */
  17930. this._texture = texture( defaultTexture );
  17931. /**
  17932. * A uniform representing the PMREM's width.
  17933. *
  17934. * @private
  17935. * @type {UniformNode<float>}
  17936. */
  17937. this._width = uniform( 0 );
  17938. /**
  17939. * A uniform representing the PMREM's height.
  17940. *
  17941. * @private
  17942. * @type {UniformNode<float>}
  17943. */
  17944. this._height = uniform( 0 );
  17945. /**
  17946. * A uniform representing the PMREM's max Mip.
  17947. *
  17948. * @private
  17949. * @type {UniformNode<float>}
  17950. */
  17951. this._maxMip = uniform( 0 );
  17952. /**
  17953. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17954. *
  17955. * @type {string}
  17956. * @default 'render'
  17957. */
  17958. this.updateBeforeType = NodeUpdateType.RENDER;
  17959. }
  17960. set value( value ) {
  17961. this._value = value;
  17962. this._pmrem = null;
  17963. }
  17964. /**
  17965. * The node's texture value.
  17966. *
  17967. * @type {Texture}
  17968. */
  17969. get value() {
  17970. return this._value;
  17971. }
  17972. /**
  17973. * Uses the given PMREM texture to update internal values.
  17974. *
  17975. * @param {Texture} texture - The PMREM texture.
  17976. */
  17977. updateFromTexture( texture ) {
  17978. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17979. this._texture.value = texture;
  17980. this._width.value = cubeUVSize.texelWidth;
  17981. this._height.value = cubeUVSize.texelHeight;
  17982. this._maxMip.value = cubeUVSize.maxMip;
  17983. }
  17984. updateBefore( frame ) {
  17985. let pmrem = this._pmrem;
  17986. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17987. const texture = this._value;
  17988. if ( pmremVersion !== texture.pmremVersion ) {
  17989. if ( texture.isPMREMTexture === true ) {
  17990. pmrem = texture;
  17991. } else {
  17992. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17993. }
  17994. if ( pmrem !== null ) {
  17995. this._pmrem = pmrem;
  17996. this.updateFromTexture( pmrem );
  17997. }
  17998. }
  17999. }
  18000. setup( builder ) {
  18001. if ( this._generator === null ) {
  18002. this._generator = new PMREMGenerator( builder.renderer );
  18003. }
  18004. this.updateBefore( builder );
  18005. //
  18006. let uvNode = this.uvNode;
  18007. if ( uvNode === null && builder.context.getUV ) {
  18008. uvNode = builder.context.getUV( this );
  18009. }
  18010. //
  18011. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18012. //
  18013. let levelNode = this.levelNode;
  18014. if ( levelNode === null && builder.context.getTextureLevel ) {
  18015. levelNode = builder.context.getTextureLevel( this );
  18016. }
  18017. //
  18018. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18019. }
  18020. dispose() {
  18021. super.dispose();
  18022. if ( this._generator !== null ) this._generator.dispose();
  18023. }
  18024. }
  18025. /**
  18026. * Returns `true` if the given cube map image has been fully loaded.
  18027. *
  18028. * @private
  18029. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18030. * @return {boolean} Whether the given cube map is ready or not.
  18031. */
  18032. function isCubeMapReady( image ) {
  18033. if ( image === null || image === undefined ) return false;
  18034. let count = 0;
  18035. const length = 6;
  18036. for ( let i = 0; i < length; i ++ ) {
  18037. if ( image[ i ] !== undefined ) count ++;
  18038. }
  18039. return count === length;
  18040. }
  18041. /**
  18042. * Returns `true` if the given equirectangular image has been fully loaded.
  18043. *
  18044. * @private
  18045. * @param {(Image|Object)} image - The equirectangular image.
  18046. * @return {boolean} Whether the given cube map is ready or not.
  18047. */
  18048. function isEquirectangularMapReady( image ) {
  18049. if ( image === null || image === undefined ) return false;
  18050. return image.height > 0;
  18051. }
  18052. /**
  18053. * TSL function for creating a PMREM node.
  18054. *
  18055. * @tsl
  18056. * @function
  18057. * @param {Texture} value - The input texture.
  18058. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18059. * @param {?Node<float>} [levelNode=null] - The level node.
  18060. * @returns {PMREMNode}
  18061. */
  18062. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18063. const _envNodeCache = new WeakMap();
  18064. /**
  18065. * Represents a physical model for Image-based lighting (IBL). The environment
  18066. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18067. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18068. *
  18069. * @augments LightingNode
  18070. */
  18071. class EnvironmentNode extends LightingNode {
  18072. static get type() {
  18073. return 'EnvironmentNode';
  18074. }
  18075. /**
  18076. * Constructs a new environment node.
  18077. *
  18078. * @param {Node} [envNode=null] - A node representing the environment.
  18079. */
  18080. constructor( envNode = null ) {
  18081. super();
  18082. /**
  18083. * A node representing the environment.
  18084. *
  18085. * @type {?Node}
  18086. * @default null
  18087. */
  18088. this.envNode = envNode;
  18089. }
  18090. setup( builder ) {
  18091. const { material } = builder;
  18092. let envNode = this.envNode;
  18093. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18094. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18095. let cacheEnvNode = _envNodeCache.get( value );
  18096. if ( cacheEnvNode === undefined ) {
  18097. cacheEnvNode = pmremTexture( value );
  18098. _envNodeCache.set( value, cacheEnvNode );
  18099. }
  18100. envNode = cacheEnvNode;
  18101. }
  18102. //
  18103. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18104. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18105. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18106. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18107. const isolateRadiance = isolate( radiance );
  18108. const isolateIrradiance = isolate( irradiance );
  18109. //
  18110. builder.context.radiance.addAssign( isolateRadiance );
  18111. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18112. //
  18113. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18114. if ( clearcoatRadiance ) {
  18115. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18116. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18117. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18118. }
  18119. }
  18120. }
  18121. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18122. let reflectVec = null;
  18123. return {
  18124. getUV: () => {
  18125. if ( reflectVec === null ) {
  18126. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18127. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18128. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18129. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18130. }
  18131. return reflectVec;
  18132. },
  18133. getTextureLevel: () => {
  18134. return roughnessNode;
  18135. }
  18136. };
  18137. };
  18138. const createIrradianceContext = ( normalWorldNode ) => {
  18139. return {
  18140. getUV: () => {
  18141. return normalWorldNode;
  18142. },
  18143. getTextureLevel: () => {
  18144. return float( 1.0 );
  18145. }
  18146. };
  18147. };
  18148. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18149. /**
  18150. * Node material version of {@link MeshStandardMaterial}.
  18151. *
  18152. * @augments NodeMaterial
  18153. */
  18154. class MeshStandardNodeMaterial extends NodeMaterial {
  18155. static get type() {
  18156. return 'MeshStandardNodeMaterial';
  18157. }
  18158. /**
  18159. * Constructs a new mesh standard node material.
  18160. *
  18161. * @param {Object} [parameters] - The configuration parameter.
  18162. */
  18163. constructor( parameters ) {
  18164. super();
  18165. /**
  18166. * This flag can be used for type testing.
  18167. *
  18168. * @type {boolean}
  18169. * @readonly
  18170. * @default true
  18171. */
  18172. this.isMeshStandardNodeMaterial = true;
  18173. /**
  18174. * Set to `true` because standard materials react on lights.
  18175. *
  18176. * @type {boolean}
  18177. * @default true
  18178. */
  18179. this.lights = true;
  18180. /**
  18181. * The emissive color of standard materials is by default inferred from the `emissive`,
  18182. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18183. * overwrite the default and define the emissive color with a node instead.
  18184. *
  18185. * If you don't want to overwrite the emissive color but modify the existing
  18186. * value instead, use {@link materialEmissive}.
  18187. *
  18188. * @type {?Node<vec3>}
  18189. * @default null
  18190. */
  18191. this.emissiveNode = null;
  18192. /**
  18193. * The metalness of standard materials is by default inferred from the `metalness`,
  18194. * and `metalnessMap` properties. This node property allows to
  18195. * overwrite the default and define the metalness with a node instead.
  18196. *
  18197. * If you don't want to overwrite the metalness but modify the existing
  18198. * value instead, use {@link materialMetalness}.
  18199. *
  18200. * @type {?Node<float>}
  18201. * @default null
  18202. */
  18203. this.metalnessNode = null;
  18204. /**
  18205. * The roughness of standard materials is by default inferred from the `roughness`,
  18206. * and `roughnessMap` properties. This node property allows to
  18207. * overwrite the default and define the roughness with a node instead.
  18208. *
  18209. * If you don't want to overwrite the roughness but modify the existing
  18210. * value instead, use {@link materialRoughness}.
  18211. *
  18212. * @type {?Node<float>}
  18213. * @default null
  18214. */
  18215. this.roughnessNode = null;
  18216. this.setDefaultValues( _defaultValues$6 );
  18217. this.setValues( parameters );
  18218. }
  18219. /**
  18220. * Overwritten since this type of material uses {@link EnvironmentNode}
  18221. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18222. * method honors `Scene.environment`.
  18223. *
  18224. * @param {NodeBuilder} builder - The current node builder.
  18225. * @return {?EnvironmentNode<vec3>} The environment node.
  18226. */
  18227. setupEnvironment( builder ) {
  18228. let envNode = super.setupEnvironment( builder );
  18229. if ( envNode === null && builder.environmentNode ) {
  18230. envNode = builder.environmentNode;
  18231. }
  18232. return envNode ? new EnvironmentNode( envNode ) : null;
  18233. }
  18234. /**
  18235. * Setups the lighting model.
  18236. *
  18237. * @return {PhysicalLightingModel} The lighting model.
  18238. */
  18239. setupLightingModel( /*builder*/ ) {
  18240. return new PhysicalLightingModel();
  18241. }
  18242. /**
  18243. * Setups the specular related node variables.
  18244. */
  18245. setupSpecular() {
  18246. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18247. specularColor.assign( specularColorNode );
  18248. specularF90.assign( 1.0 );
  18249. }
  18250. /**
  18251. * Setups the standard specific node variables.
  18252. *
  18253. * @param {NodeBuilder} builder - The current node builder.
  18254. */
  18255. setupVariants() {
  18256. // METALNESS
  18257. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18258. metalness.assign( metalnessNode );
  18259. // ROUGHNESS
  18260. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18261. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18262. roughness.assign( roughnessNode );
  18263. // SPECULAR COLOR
  18264. this.setupSpecular();
  18265. // DIFFUSE COLOR
  18266. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  18267. }
  18268. copy( source ) {
  18269. this.emissiveNode = source.emissiveNode;
  18270. this.metalnessNode = source.metalnessNode;
  18271. this.roughnessNode = source.roughnessNode;
  18272. return super.copy( source );
  18273. }
  18274. }
  18275. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18276. /**
  18277. * Node material version of {@link MeshPhysicalMaterial}.
  18278. *
  18279. * @augments MeshStandardNodeMaterial
  18280. */
  18281. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18282. static get type() {
  18283. return 'MeshPhysicalNodeMaterial';
  18284. }
  18285. /**
  18286. * Constructs a new mesh physical node material.
  18287. *
  18288. * @param {Object} [parameters] - The configuration parameter.
  18289. */
  18290. constructor( parameters ) {
  18291. super();
  18292. /**
  18293. * This flag can be used for type testing.
  18294. *
  18295. * @type {boolean}
  18296. * @readonly
  18297. * @default true
  18298. */
  18299. this.isMeshPhysicalNodeMaterial = true;
  18300. /**
  18301. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18302. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18303. * and define the clearcoat with a node instead.
  18304. *
  18305. * If you don't want to overwrite the clearcoat but modify the existing
  18306. * value instead, use {@link materialClearcoat}.
  18307. *
  18308. * @type {?Node<float>}
  18309. * @default null
  18310. */
  18311. this.clearcoatNode = null;
  18312. /**
  18313. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18314. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18315. * and define the clearcoat roughness with a node instead.
  18316. *
  18317. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18318. * value instead, use {@link materialClearcoatRoughness}.
  18319. *
  18320. * @type {?Node<float>}
  18321. * @default null
  18322. */
  18323. this.clearcoatRoughnessNode = null;
  18324. /**
  18325. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18326. * property. This node property allows to overwrite the default
  18327. * and define the clearcoat normal with a node instead.
  18328. *
  18329. * If you don't want to overwrite the clearcoat normal but modify the existing
  18330. * value instead, use {@link materialClearcoatNormal}.
  18331. *
  18332. * @type {?Node<vec3>}
  18333. * @default null
  18334. */
  18335. this.clearcoatNormalNode = null;
  18336. /**
  18337. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18338. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18339. * and define the sheen with a node instead.
  18340. *
  18341. * If you don't want to overwrite the sheen but modify the existing
  18342. * value instead, use {@link materialSheen}.
  18343. *
  18344. * @type {?Node<vec3>}
  18345. * @default null
  18346. */
  18347. this.sheenNode = null;
  18348. /**
  18349. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18350. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18351. * and define the sheen roughness with a node instead.
  18352. *
  18353. * If you don't want to overwrite the sheen roughness but modify the existing
  18354. * value instead, use {@link materialSheenRoughness}.
  18355. *
  18356. * @type {?Node<float>}
  18357. * @default null
  18358. */
  18359. this.sheenRoughnessNode = null;
  18360. /**
  18361. * The iridescence of physical materials is by default inferred from the `iridescence`
  18362. * property. This node property allows to overwrite the default
  18363. * and define the iridescence with a node instead.
  18364. *
  18365. * If you don't want to overwrite the iridescence but modify the existing
  18366. * value instead, use {@link materialIridescence}.
  18367. *
  18368. * @type {?Node<float>}
  18369. * @default null
  18370. */
  18371. this.iridescenceNode = null;
  18372. /**
  18373. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18374. * property. This node property allows to overwrite the default
  18375. * and define the iridescence IOR with a node instead.
  18376. *
  18377. * If you don't want to overwrite the iridescence IOR but modify the existing
  18378. * value instead, use {@link materialIridescenceIOR}.
  18379. *
  18380. * @type {?Node<float>}
  18381. * @default null
  18382. */
  18383. this.iridescenceIORNode = null;
  18384. /**
  18385. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18386. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18387. * and define the iridescence thickness with a node instead.
  18388. *
  18389. * If you don't want to overwrite the iridescence thickness but modify the existing
  18390. * value instead, use {@link materialIridescenceThickness}.
  18391. *
  18392. * @type {?Node<float>}
  18393. * @default null
  18394. */
  18395. this.iridescenceThicknessNode = null;
  18396. /**
  18397. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18398. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18399. * and define the specular intensity with a node instead.
  18400. *
  18401. * If you don't want to overwrite the specular intensity but modify the existing
  18402. * value instead, use {@link materialSpecularIntensity}.
  18403. *
  18404. * @type {?Node<float>}
  18405. * @default null
  18406. */
  18407. this.specularIntensityNode = null;
  18408. /**
  18409. * The specular color of physical materials is by default inferred from the `specularColor`
  18410. * and `specularColorMap` properties. This node property allows to overwrite the default
  18411. * and define the specular color with a node instead.
  18412. *
  18413. * If you don't want to overwrite the specular color but modify the existing
  18414. * value instead, use {@link materialSpecularColor}.
  18415. *
  18416. * @type {?Node<vec3>}
  18417. * @default null
  18418. */
  18419. this.specularColorNode = null;
  18420. /**
  18421. * The ior of physical materials is by default inferred from the `ior`
  18422. * property. This node property allows to overwrite the default
  18423. * and define the ior with a node instead.
  18424. *
  18425. * If you don't want to overwrite the ior but modify the existing
  18426. * value instead, use {@link materialIOR}.
  18427. *
  18428. * @type {?Node<float>}
  18429. * @default null
  18430. */
  18431. this.iorNode = null;
  18432. /**
  18433. * The transmission of physical materials is by default inferred from the `transmission` and
  18434. * `transmissionMap` properties. This node property allows to overwrite the default
  18435. * and define the transmission with a node instead.
  18436. *
  18437. * If you don't want to overwrite the transmission but modify the existing
  18438. * value instead, use {@link materialTransmission}.
  18439. *
  18440. * @type {?Node<float>}
  18441. * @default null
  18442. */
  18443. this.transmissionNode = null;
  18444. /**
  18445. * The thickness of physical materials is by default inferred from the `thickness` and
  18446. * `thicknessMap` properties. This node property allows to overwrite the default
  18447. * and define the thickness with a node instead.
  18448. *
  18449. * If you don't want to overwrite the thickness but modify the existing
  18450. * value instead, use {@link materialThickness}.
  18451. *
  18452. * @type {?Node<float>}
  18453. * @default null
  18454. */
  18455. this.thicknessNode = null;
  18456. /**
  18457. * The attenuation distance of physical materials is by default inferred from the
  18458. * `attenuationDistance` property. This node property allows to overwrite the default
  18459. * and define the attenuation distance with a node instead.
  18460. *
  18461. * If you don't want to overwrite the attenuation distance but modify the existing
  18462. * value instead, use {@link materialAttenuationDistance}.
  18463. *
  18464. * @type {?Node<float>}
  18465. * @default null
  18466. */
  18467. this.attenuationDistanceNode = null;
  18468. /**
  18469. * The attenuation color of physical materials is by default inferred from the
  18470. * `attenuationColor` property. This node property allows to overwrite the default
  18471. * and define the attenuation color with a node instead.
  18472. *
  18473. * If you don't want to overwrite the attenuation color but modify the existing
  18474. * value instead, use {@link materialAttenuationColor}.
  18475. *
  18476. * @type {?Node<vec3>}
  18477. * @default null
  18478. */
  18479. this.attenuationColorNode = null;
  18480. /**
  18481. * The dispersion of physical materials is by default inferred from the
  18482. * `dispersion` property. This node property allows to overwrite the default
  18483. * and define the dispersion with a node instead.
  18484. *
  18485. * If you don't want to overwrite the dispersion but modify the existing
  18486. * value instead, use {@link materialDispersion}.
  18487. *
  18488. * @type {?Node<float>}
  18489. * @default null
  18490. */
  18491. this.dispersionNode = null;
  18492. /**
  18493. * The anisotropy of physical materials is by default inferred from the
  18494. * `anisotropy` property. This node property allows to overwrite the default
  18495. * and define the anisotropy with a node instead.
  18496. *
  18497. * If you don't want to overwrite the anisotropy but modify the existing
  18498. * value instead, use {@link materialAnisotropy}.
  18499. *
  18500. * @type {?Node<float>}
  18501. * @default null
  18502. */
  18503. this.anisotropyNode = null;
  18504. this.setDefaultValues( _defaultValues$5 );
  18505. this.setValues( parameters );
  18506. }
  18507. /**
  18508. * Whether the lighting model should use clearcoat or not.
  18509. *
  18510. * @type {boolean}
  18511. * @default true
  18512. */
  18513. get useClearcoat() {
  18514. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18515. }
  18516. /**
  18517. * Whether the lighting model should use iridescence or not.
  18518. *
  18519. * @type {boolean}
  18520. * @default true
  18521. */
  18522. get useIridescence() {
  18523. return this.iridescence > 0 || this.iridescenceNode !== null;
  18524. }
  18525. /**
  18526. * Whether the lighting model should use sheen or not.
  18527. *
  18528. * @type {boolean}
  18529. * @default true
  18530. */
  18531. get useSheen() {
  18532. return this.sheen > 0 || this.sheenNode !== null;
  18533. }
  18534. /**
  18535. * Whether the lighting model should use anisotropy or not.
  18536. *
  18537. * @type {boolean}
  18538. * @default true
  18539. */
  18540. get useAnisotropy() {
  18541. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18542. }
  18543. /**
  18544. * Whether the lighting model should use transmission or not.
  18545. *
  18546. * @type {boolean}
  18547. * @default true
  18548. */
  18549. get useTransmission() {
  18550. return this.transmission > 0 || this.transmissionNode !== null;
  18551. }
  18552. /**
  18553. * Whether the lighting model should use dispersion or not.
  18554. *
  18555. * @type {boolean}
  18556. * @default true
  18557. */
  18558. get useDispersion() {
  18559. return this.dispersion > 0 || this.dispersionNode !== null;
  18560. }
  18561. /**
  18562. * Setups the specular related node variables.
  18563. */
  18564. setupSpecular() {
  18565. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18566. ior.assign( iorNode );
  18567. 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 ) );
  18568. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18569. }
  18570. /**
  18571. * Setups the lighting model.
  18572. *
  18573. * @return {PhysicalLightingModel} The lighting model.
  18574. */
  18575. setupLightingModel( /*builder*/ ) {
  18576. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18577. }
  18578. /**
  18579. * Setups the physical specific node variables.
  18580. *
  18581. * @param {NodeBuilder} builder - The current node builder.
  18582. */
  18583. setupVariants( builder ) {
  18584. super.setupVariants( builder );
  18585. // CLEARCOAT
  18586. if ( this.useClearcoat ) {
  18587. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18588. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18589. clearcoat.assign( clearcoatNode );
  18590. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18591. }
  18592. // SHEEN
  18593. if ( this.useSheen ) {
  18594. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18595. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18596. sheen.assign( sheenNode );
  18597. sheenRoughness.assign( sheenRoughnessNode );
  18598. }
  18599. // IRIDESCENCE
  18600. if ( this.useIridescence ) {
  18601. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18602. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18603. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18604. iridescence.assign( iridescenceNode );
  18605. iridescenceIOR.assign( iridescenceIORNode );
  18606. iridescenceThickness.assign( iridescenceThicknessNode );
  18607. }
  18608. // ANISOTROPY
  18609. if ( this.useAnisotropy ) {
  18610. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18611. anisotropy.assign( anisotropyV.length() );
  18612. If( anisotropy.equal( 0.0 ), () => {
  18613. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18614. } ).Else( () => {
  18615. anisotropyV.divAssign( vec2( anisotropy ) );
  18616. anisotropy.assign( anisotropy.saturate() );
  18617. } );
  18618. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18619. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18620. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18621. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18622. }
  18623. // TRANSMISSION
  18624. if ( this.useTransmission ) {
  18625. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18626. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18627. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18628. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18629. transmission.assign( transmissionNode );
  18630. thickness.assign( thicknessNode );
  18631. attenuationDistance.assign( attenuationDistanceNode );
  18632. attenuationColor.assign( attenuationColorNode );
  18633. if ( this.useDispersion ) {
  18634. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18635. dispersion.assign( dispersionNode );
  18636. }
  18637. }
  18638. }
  18639. /**
  18640. * Setups the clearcoat normal node.
  18641. *
  18642. * @return {Node<vec3>} The clearcoat normal.
  18643. */
  18644. setupClearcoatNormal() {
  18645. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18646. }
  18647. setup( builder ) {
  18648. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18649. super.setup( builder );
  18650. }
  18651. copy( source ) {
  18652. this.clearcoatNode = source.clearcoatNode;
  18653. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18654. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18655. this.sheenNode = source.sheenNode;
  18656. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18657. this.iridescenceNode = source.iridescenceNode;
  18658. this.iridescenceIORNode = source.iridescenceIORNode;
  18659. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18660. this.specularIntensityNode = source.specularIntensityNode;
  18661. this.specularColorNode = source.specularColorNode;
  18662. this.transmissionNode = source.transmissionNode;
  18663. this.thicknessNode = source.thicknessNode;
  18664. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18665. this.attenuationColorNode = source.attenuationColorNode;
  18666. this.dispersionNode = source.dispersionNode;
  18667. this.anisotropyNode = source.anisotropyNode;
  18668. return super.copy( source );
  18669. }
  18670. }
  18671. /**
  18672. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18673. *
  18674. * @augments PhysicalLightingModel
  18675. */
  18676. class SSSLightingModel extends PhysicalLightingModel {
  18677. /**
  18678. * Constructs a new physical lighting model.
  18679. *
  18680. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18681. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18682. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18683. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18684. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18685. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18686. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18687. */
  18688. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18689. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18690. /**
  18691. * Whether the lighting model should use SSS or not.
  18692. *
  18693. * @type {boolean}
  18694. * @default false
  18695. */
  18696. this.useSSS = sss;
  18697. }
  18698. /**
  18699. * Extends the default implementation with a SSS term.
  18700. *
  18701. * 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/}
  18702. *
  18703. * @param {Object} input - The input data.
  18704. * @param {NodeBuilder} builder - The current node builder.
  18705. */
  18706. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18707. if ( this.useSSS === true ) {
  18708. const material = builder.material;
  18709. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18710. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18711. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18712. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18713. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18714. }
  18715. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18716. }
  18717. }
  18718. /**
  18719. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18720. * that implements a Subsurface scattering (SSS) term.
  18721. *
  18722. * @augments MeshPhysicalNodeMaterial
  18723. */
  18724. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18725. static get type() {
  18726. return 'MeshSSSNodeMaterial';
  18727. }
  18728. /**
  18729. * Constructs a new mesh SSS node material.
  18730. *
  18731. * @param {Object} [parameters] - The configuration parameter.
  18732. */
  18733. constructor( parameters ) {
  18734. super( parameters );
  18735. /**
  18736. * Represents the thickness color.
  18737. *
  18738. * @type {?Node<vec3>}
  18739. * @default null
  18740. */
  18741. this.thicknessColorNode = null;
  18742. /**
  18743. * Represents the distortion factor.
  18744. *
  18745. * @type {?Node<float>}
  18746. */
  18747. this.thicknessDistortionNode = float( 0.1 );
  18748. /**
  18749. * Represents the thickness ambient factor.
  18750. *
  18751. * @type {?Node<float>}
  18752. */
  18753. this.thicknessAmbientNode = float( 0.0 );
  18754. /**
  18755. * Represents the thickness attenuation.
  18756. *
  18757. * @type {?Node<float>}
  18758. */
  18759. this.thicknessAttenuationNode = float( .1 );
  18760. /**
  18761. * Represents the thickness power.
  18762. *
  18763. * @type {?Node<float>}
  18764. */
  18765. this.thicknessPowerNode = float( 2.0 );
  18766. /**
  18767. * Represents the thickness scale.
  18768. *
  18769. * @type {?Node<float>}
  18770. */
  18771. this.thicknessScaleNode = float( 10.0 );
  18772. }
  18773. /**
  18774. * Whether the lighting model should use SSS or not.
  18775. *
  18776. * @type {boolean}
  18777. * @default true
  18778. */
  18779. get useSSS() {
  18780. return this.thicknessColorNode !== null;
  18781. }
  18782. /**
  18783. * Setups the lighting model.
  18784. *
  18785. * @return {SSSLightingModel} The lighting model.
  18786. */
  18787. setupLightingModel( /*builder*/ ) {
  18788. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18789. }
  18790. copy( source ) {
  18791. this.thicknessColorNode = source.thicknessColorNode;
  18792. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18793. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18794. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18795. this.thicknessPowerNode = source.thicknessPowerNode;
  18796. this.thicknessScaleNode = source.thicknessScaleNode;
  18797. return super.copy( source );
  18798. }
  18799. }
  18800. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18801. // dotNL will be from -1.0 to 1.0
  18802. const dotNL = normal.dot( lightDirection );
  18803. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18804. if ( builder.material.gradientMap ) {
  18805. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18806. return vec3( gradientMap.r );
  18807. } else {
  18808. const fw = coord.fwidth().mul( 0.5 );
  18809. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18810. }
  18811. } );
  18812. /**
  18813. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18814. *
  18815. * @augments LightingModel
  18816. */
  18817. class ToonLightingModel extends LightingModel {
  18818. /**
  18819. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18820. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18821. *
  18822. * @param {Object} lightData - The light data.
  18823. * @param {NodeBuilder} builder - The current node builder.
  18824. */
  18825. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18826. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18827. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18828. }
  18829. /**
  18830. * Implements the indirect lighting.
  18831. *
  18832. * @param {NodeBuilder} builder - The current node builder.
  18833. */
  18834. indirect( builder ) {
  18835. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18836. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18837. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18838. }
  18839. }
  18840. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18841. /**
  18842. * Node material version of {@link MeshToonMaterial}.
  18843. *
  18844. * @augments NodeMaterial
  18845. */
  18846. class MeshToonNodeMaterial extends NodeMaterial {
  18847. static get type() {
  18848. return 'MeshToonNodeMaterial';
  18849. }
  18850. /**
  18851. * Constructs a new mesh toon node material.
  18852. *
  18853. * @param {Object} [parameters] - The configuration parameter.
  18854. */
  18855. constructor( parameters ) {
  18856. super();
  18857. /**
  18858. * This flag can be used for type testing.
  18859. *
  18860. * @type {boolean}
  18861. * @readonly
  18862. * @default true
  18863. */
  18864. this.isMeshToonNodeMaterial = true;
  18865. /**
  18866. * Set to `true` because toon materials react on lights.
  18867. *
  18868. * @type {boolean}
  18869. * @default true
  18870. */
  18871. this.lights = true;
  18872. this.setDefaultValues( _defaultValues$4 );
  18873. this.setValues( parameters );
  18874. }
  18875. /**
  18876. * Setups the lighting model.
  18877. *
  18878. * @return {ToonLightingModel} The lighting model.
  18879. */
  18880. setupLightingModel( /*builder*/ ) {
  18881. return new ToonLightingModel();
  18882. }
  18883. }
  18884. /**
  18885. * TSL function for creating a matcap uv node.
  18886. *
  18887. * Can be used to compute texture coordinates for projecting a
  18888. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18889. *
  18890. * @tsl
  18891. * @function
  18892. * @returns {Node<vec2>} The matcap UV coordinates.
  18893. */
  18894. const matcapUV = /*@__PURE__*/ Fn( () => {
  18895. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18896. const y = positionViewDirection.cross( x );
  18897. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18898. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18899. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18900. /**
  18901. * Node material version of {@link MeshMatcapMaterial}.
  18902. *
  18903. * @augments NodeMaterial
  18904. */
  18905. class MeshMatcapNodeMaterial extends NodeMaterial {
  18906. static get type() {
  18907. return 'MeshMatcapNodeMaterial';
  18908. }
  18909. /**
  18910. * Constructs a new mesh normal node material.
  18911. *
  18912. * @param {Object} [parameters] - The configuration parameter.
  18913. */
  18914. constructor( parameters ) {
  18915. super();
  18916. /**
  18917. * This flag can be used for type testing.
  18918. *
  18919. * @type {boolean}
  18920. * @readonly
  18921. * @default true
  18922. */
  18923. this.isMeshMatcapNodeMaterial = true;
  18924. this.setDefaultValues( _defaultValues$3 );
  18925. this.setValues( parameters );
  18926. }
  18927. /**
  18928. * Setups the matcap specific node variables.
  18929. *
  18930. * @param {NodeBuilder} builder - The current node builder.
  18931. */
  18932. setupVariants( builder ) {
  18933. const uv = matcapUV;
  18934. let matcapColor;
  18935. if ( builder.material.matcap ) {
  18936. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18937. } else {
  18938. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18939. }
  18940. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18941. }
  18942. }
  18943. /**
  18944. * Applies a rotation to the given position node.
  18945. *
  18946. * @augments TempNode
  18947. */
  18948. class RotateNode extends TempNode {
  18949. static get type() {
  18950. return 'RotateNode';
  18951. }
  18952. /**
  18953. * Constructs a new rotate node.
  18954. *
  18955. * @param {Node} positionNode - The position node.
  18956. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18957. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18958. */
  18959. constructor( positionNode, rotationNode ) {
  18960. super();
  18961. /**
  18962. * The position node.
  18963. *
  18964. * @type {Node}
  18965. */
  18966. this.positionNode = positionNode;
  18967. /**
  18968. * Represents the rotation that is applied to the position node.
  18969. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18970. *
  18971. * @type {Node}
  18972. */
  18973. this.rotationNode = rotationNode;
  18974. }
  18975. /**
  18976. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18977. *
  18978. * @param {NodeBuilder} builder - The current node builder.
  18979. * @return {string} The node's type.
  18980. */
  18981. getNodeType( builder ) {
  18982. return this.positionNode.getNodeType( builder );
  18983. }
  18984. setup( builder ) {
  18985. const { rotationNode, positionNode } = this;
  18986. const nodeType = this.getNodeType( builder );
  18987. if ( nodeType === 'vec2' ) {
  18988. const cosAngle = rotationNode.cos();
  18989. const sinAngle = rotationNode.sin();
  18990. const rotationMatrix = mat2(
  18991. cosAngle, sinAngle,
  18992. sinAngle.negate(), cosAngle
  18993. );
  18994. return rotationMatrix.mul( positionNode );
  18995. } else {
  18996. const rotation = rotationNode;
  18997. 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 ) );
  18998. 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 ) );
  18999. 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 ) );
  19000. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19001. }
  19002. }
  19003. }
  19004. /**
  19005. * TSL function for creating a rotate node.
  19006. *
  19007. * @tsl
  19008. * @function
  19009. * @param {Node} positionNode - The position node.
  19010. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19011. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19012. * @returns {RotateNode}
  19013. */
  19014. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19015. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19016. /**
  19017. * Node material version of {@link SpriteMaterial}.
  19018. *
  19019. * @augments NodeMaterial
  19020. */
  19021. class SpriteNodeMaterial extends NodeMaterial {
  19022. static get type() {
  19023. return 'SpriteNodeMaterial';
  19024. }
  19025. /**
  19026. * Constructs a new sprite node material.
  19027. *
  19028. * @param {Object} [parameters] - The configuration parameter.
  19029. */
  19030. constructor( parameters ) {
  19031. super();
  19032. /**
  19033. * This flag can be used for type testing.
  19034. *
  19035. * @type {boolean}
  19036. * @readonly
  19037. * @default true
  19038. */
  19039. this.isSpriteNodeMaterial = true;
  19040. this._useSizeAttenuation = true;
  19041. /**
  19042. * This property makes it possible to define the position of the sprite with a
  19043. * node. That can be useful when the material is used with instanced rendering
  19044. * and node data are defined with an instanced attribute node:
  19045. * ```js
  19046. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19047. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19048. * ```
  19049. * Another possibility is to compute the instanced data with a compute shader:
  19050. * ```js
  19051. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19052. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19053. * ```
  19054. *
  19055. * @type {?Node<vec2>}
  19056. * @default null
  19057. */
  19058. this.positionNode = null;
  19059. /**
  19060. * The rotation of sprite materials is by default inferred from the `rotation`,
  19061. * property. This node property allows to overwrite the default and define
  19062. * the rotation with a node instead.
  19063. *
  19064. * If you don't want to overwrite the rotation but modify the existing
  19065. * value instead, use {@link materialRotation}.
  19066. *
  19067. * @type {?Node<float>}
  19068. * @default null
  19069. */
  19070. this.rotationNode = null;
  19071. /**
  19072. * This node property provides an additional way to scale sprites next to
  19073. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19074. * is multiplied with the scale value of this node in the vertex shader.
  19075. *
  19076. * @type {?Node<vec2>}
  19077. * @default null
  19078. */
  19079. this.scaleNode = null;
  19080. /**
  19081. * In Sprites, the transparent property is enabled by default.
  19082. *
  19083. * @type {boolean}
  19084. * @default true
  19085. */
  19086. this.transparent = true;
  19087. this.setDefaultValues( _defaultValues$2 );
  19088. this.setValues( parameters );
  19089. }
  19090. /**
  19091. * Setups the position node in view space. This method implements
  19092. * the sprite specific vertex shader.
  19093. *
  19094. * @param {NodeBuilder} builder - The current node builder.
  19095. * @return {Node<vec3>} The position in view space.
  19096. */
  19097. setupPositionView( builder ) {
  19098. const { object, camera } = builder;
  19099. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19100. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19101. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19102. if ( scaleNode !== null ) {
  19103. scale = scale.mul( vec2( scaleNode ) );
  19104. }
  19105. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19106. scale = scale.mul( mvPosition.z.negate() );
  19107. }
  19108. let alignedPosition = positionGeometry.xy;
  19109. if ( object.center && object.center.isVector2 === true ) {
  19110. const center = reference$1( 'center', 'vec2', object );
  19111. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19112. }
  19113. alignedPosition = alignedPosition.mul( scale );
  19114. const rotation = float( rotationNode || materialRotation );
  19115. const rotatedPosition = rotate( alignedPosition, rotation );
  19116. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19117. }
  19118. copy( source ) {
  19119. this.positionNode = source.positionNode;
  19120. this.rotationNode = source.rotationNode;
  19121. this.scaleNode = source.scaleNode;
  19122. return super.copy( source );
  19123. }
  19124. /**
  19125. * Whether to use size attenuation or not.
  19126. *
  19127. * @type {boolean}
  19128. * @default true
  19129. */
  19130. get sizeAttenuation() {
  19131. return this._useSizeAttenuation;
  19132. }
  19133. set sizeAttenuation( value ) {
  19134. if ( this._useSizeAttenuation !== value ) {
  19135. this._useSizeAttenuation = value;
  19136. this.needsUpdate = true;
  19137. }
  19138. }
  19139. }
  19140. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19141. const _size$4 = /*@__PURE__*/ new Vector2();
  19142. /**
  19143. * Node material version of {@link PointsMaterial}.
  19144. *
  19145. * This material can be used in two ways:
  19146. *
  19147. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19148. * with a pixel size of `1`, it's not possible to define a size.
  19149. *
  19150. * ```js
  19151. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19152. * ```
  19153. *
  19154. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19155. * see {@link PointsNodeMaterial#sizeNode}.
  19156. *
  19157. * ```js
  19158. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19159. * ```
  19160. *
  19161. * @augments SpriteNodeMaterial
  19162. */
  19163. class PointsNodeMaterial extends SpriteNodeMaterial {
  19164. static get type() {
  19165. return 'PointsNodeMaterial';
  19166. }
  19167. /**
  19168. * Constructs a new points node material.
  19169. *
  19170. * @param {Object} [parameters] - The configuration parameter.
  19171. */
  19172. constructor( parameters ) {
  19173. super();
  19174. /**
  19175. * This node property provides an additional way to set the point size.
  19176. *
  19177. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19178. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19179. * backend. If an application wants to render points with a size larger than 1 pixel,
  19180. * the material should be used with {@link Sprite} and instancing.
  19181. *
  19182. * @type {?Node<vec2>}
  19183. * @default null
  19184. */
  19185. this.sizeNode = null;
  19186. /**
  19187. * This flag can be used for type testing.
  19188. *
  19189. * @type {boolean}
  19190. * @readonly
  19191. * @default true
  19192. */
  19193. this.isPointsNodeMaterial = true;
  19194. this.setDefaultValues( _defaultValues$1 );
  19195. this.setValues( parameters );
  19196. }
  19197. setupPositionView() {
  19198. const { positionNode } = this;
  19199. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19200. }
  19201. setupVertexSprite( builder ) {
  19202. const { material, camera } = builder;
  19203. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19204. let mvp = super.setupVertex( builder );
  19205. // skip further processing if the material is not a node material
  19206. if ( material.isNodeMaterial !== true ) {
  19207. return mvp;
  19208. }
  19209. // point size
  19210. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19211. pointSize = pointSize.mul( screenDPR );
  19212. // size attenuation
  19213. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19214. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19215. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19216. }
  19217. // scale
  19218. if ( scaleNode && scaleNode.isNode ) {
  19219. pointSize = pointSize.mul( vec2( scaleNode ) );
  19220. }
  19221. // compute offset
  19222. let offset = positionGeometry.xy;
  19223. // apply rotation
  19224. if ( rotationNode && rotationNode.isNode ) {
  19225. const rotation = float( rotationNode );
  19226. offset = rotate( offset, rotation );
  19227. }
  19228. // account for point size
  19229. offset = offset.mul( pointSize );
  19230. // scale by viewport size
  19231. offset = offset.div( viewportSize.div( 2 ) );
  19232. // compensate for the perspective divide
  19233. offset = offset.mul( mvp.w );
  19234. // add offset
  19235. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19236. return mvp;
  19237. }
  19238. setupVertex( builder ) {
  19239. if ( builder.object.isPoints ) {
  19240. return super.setupVertex( builder );
  19241. } else {
  19242. return this.setupVertexSprite( builder );
  19243. }
  19244. }
  19245. /**
  19246. * Whether alpha to coverage should be used or not.
  19247. *
  19248. * @type {boolean}
  19249. * @default true
  19250. */
  19251. get alphaToCoverage() {
  19252. return this._useAlphaToCoverage;
  19253. }
  19254. set alphaToCoverage( value ) {
  19255. if ( this._useAlphaToCoverage !== value ) {
  19256. this._useAlphaToCoverage = value;
  19257. this.needsUpdate = true;
  19258. }
  19259. }
  19260. }
  19261. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19262. const size = renderer.getSize( _size$4 ); // logical units
  19263. this.value = 0.5 * size.y;
  19264. } );
  19265. /**
  19266. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19267. *
  19268. * @augments LightingModel
  19269. */
  19270. class ShadowMaskModel extends LightingModel {
  19271. /**
  19272. * Constructs a new shadow mask model.
  19273. */
  19274. constructor() {
  19275. super();
  19276. /**
  19277. * The shadow mask node.
  19278. *
  19279. * @type {Node}
  19280. */
  19281. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19282. }
  19283. /**
  19284. * Only used to save the shadow mask.
  19285. *
  19286. * @param {Object} input - The input data.
  19287. */
  19288. direct( { lightNode } ) {
  19289. if ( lightNode.shadowNode !== null ) {
  19290. this.shadowNode.mulAssign( lightNode.shadowNode );
  19291. }
  19292. }
  19293. /**
  19294. * Uses the shadow mask to produce the final color.
  19295. *
  19296. * @param {NodeBuilder} builder - The current node builder.
  19297. */
  19298. finish( { context } ) {
  19299. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19300. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19301. }
  19302. }
  19303. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19304. /**
  19305. * Node material version of {@link ShadowMaterial}.
  19306. *
  19307. * @augments NodeMaterial
  19308. */
  19309. class ShadowNodeMaterial extends NodeMaterial {
  19310. static get type() {
  19311. return 'ShadowNodeMaterial';
  19312. }
  19313. /**
  19314. * Constructs a new shadow node material.
  19315. *
  19316. * @param {Object} [parameters] - The configuration parameter.
  19317. */
  19318. constructor( parameters ) {
  19319. super();
  19320. /**
  19321. * This flag can be used for type testing.
  19322. *
  19323. * @type {boolean}
  19324. * @readonly
  19325. * @default true
  19326. */
  19327. this.isShadowNodeMaterial = true;
  19328. /**
  19329. * Set to `true` because so it's possible to implement
  19330. * the shadow mask effect.
  19331. *
  19332. * @type {boolean}
  19333. * @default true
  19334. */
  19335. this.lights = true;
  19336. /**
  19337. * Overwritten since shadow materials are transparent
  19338. * by default.
  19339. *
  19340. * @type {boolean}
  19341. * @default true
  19342. */
  19343. this.transparent = true;
  19344. this.setDefaultValues( _defaultValues );
  19345. this.setValues( parameters );
  19346. }
  19347. /**
  19348. * Setups the lighting model.
  19349. *
  19350. * @return {ShadowMaskModel} The lighting model.
  19351. */
  19352. setupLightingModel( /*builder*/ ) {
  19353. return new ShadowMaskModel();
  19354. }
  19355. }
  19356. const scatteringDensity = property( 'vec3' );
  19357. const linearDepthRay = property( 'vec3' );
  19358. const outgoingRayLight = property( 'vec3' );
  19359. /**
  19360. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19361. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19362. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19363. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19364. *
  19365. * @augments LightingModel
  19366. */
  19367. class VolumetricLightingModel extends LightingModel {
  19368. constructor() {
  19369. super();
  19370. }
  19371. start( builder ) {
  19372. const { material, context } = builder;
  19373. const startPos = property( 'vec3' );
  19374. const endPos = property( 'vec3' );
  19375. // This approach dynamically changes the direction of the ray,
  19376. // 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.
  19377. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19378. startPos.assign( cameraPosition );
  19379. endPos.assign( positionWorld );
  19380. } ).Else( () => {
  19381. startPos.assign( positionWorld );
  19382. endPos.assign( cameraPosition );
  19383. } );
  19384. //
  19385. const viewVector = endPos.sub( startPos );
  19386. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19387. const stepSize = viewVector.length().div( steps ).toVar();
  19388. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19389. const distTravelled = float( 0.0 ).toVar();
  19390. const transmittance = vec3( 1 ).toVar();
  19391. if ( material.offsetNode ) {
  19392. // reduce banding
  19393. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19394. }
  19395. Loop( steps, () => {
  19396. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19397. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19398. if ( material.depthNode !== null ) {
  19399. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19400. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19401. }
  19402. context.positionWorld = positionRay;
  19403. context.shadowPositionWorld = positionRay;
  19404. context.positionView = positionViewRay;
  19405. scatteringDensity.assign( 0 );
  19406. let scatteringNode;
  19407. if ( material.scatteringNode ) {
  19408. scatteringNode = material.scatteringNode( {
  19409. positionRay
  19410. } );
  19411. }
  19412. super.start( builder );
  19413. if ( scatteringNode ) {
  19414. scatteringDensity.mulAssign( scatteringNode );
  19415. }
  19416. // beer's law
  19417. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19418. transmittance.mulAssign( falloff );
  19419. // move along the ray
  19420. distTravelled.addAssign( stepSize );
  19421. } );
  19422. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19423. }
  19424. scatteringLight( lightColor, builder ) {
  19425. const sceneDepthNode = builder.context.sceneDepthNode;
  19426. if ( sceneDepthNode ) {
  19427. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19428. scatteringDensity.addAssign( lightColor );
  19429. } );
  19430. } else {
  19431. scatteringDensity.addAssign( lightColor );
  19432. }
  19433. }
  19434. direct( { lightNode, lightColor }, builder ) {
  19435. // Ignore lights with infinite distance
  19436. if ( lightNode.light.distance === undefined ) return;
  19437. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19438. const directLight = lightColor.xyz.toVar();
  19439. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19440. this.scatteringLight( directLight, builder );
  19441. }
  19442. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19443. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19444. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19445. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19446. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19447. const P = builder.context.positionView;
  19448. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19449. this.scatteringLight( directLight, builder );
  19450. }
  19451. finish( builder ) {
  19452. builder.context.outgoingLight.assign( outgoingRayLight );
  19453. }
  19454. }
  19455. /**
  19456. * Volume node material.
  19457. *
  19458. * @augments NodeMaterial
  19459. */
  19460. class VolumeNodeMaterial extends NodeMaterial {
  19461. static get type() {
  19462. return 'VolumeNodeMaterial';
  19463. }
  19464. /**
  19465. * Constructs a new volume node material.
  19466. *
  19467. * @param {Object} [parameters] - The configuration parameter.
  19468. */
  19469. constructor( parameters ) {
  19470. super();
  19471. /**
  19472. * This flag can be used for type testing.
  19473. *
  19474. * @type {boolean}
  19475. * @readonly
  19476. * @default true
  19477. */
  19478. this.isVolumeNodeMaterial = true;
  19479. /**
  19480. * Number of steps used for raymarching.
  19481. *
  19482. * @type {number}
  19483. * @default 25
  19484. */
  19485. this.steps = 25;
  19486. /**
  19487. * Offsets the distance a ray has been traveled through a volume.
  19488. * Can be used to implement dithering to reduce banding.
  19489. *
  19490. * @type {Node<float>}
  19491. * @default null
  19492. */
  19493. this.offsetNode = null;
  19494. /**
  19495. * Node used for scattering calculations.
  19496. *
  19497. * @type {Function|FunctionNode<vec4>}
  19498. * @default null
  19499. */
  19500. this.scatteringNode = null;
  19501. this.lights = true;
  19502. this.transparent = true;
  19503. this.side = BackSide;
  19504. this.depthTest = false;
  19505. this.depthWrite = false;
  19506. this.setValues( parameters );
  19507. }
  19508. setupLightingModel() {
  19509. return new VolumetricLightingModel();
  19510. }
  19511. }
  19512. /**
  19513. * This module manages the internal animation loop of the renderer.
  19514. *
  19515. * @private
  19516. */
  19517. class Animation {
  19518. /**
  19519. * Constructs a new animation loop management component.
  19520. *
  19521. * @param {Renderer} renderer - A reference to the main renderer.
  19522. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19523. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19524. */
  19525. constructor( renderer, nodes, info ) {
  19526. /**
  19527. * A reference to the main renderer.
  19528. *
  19529. * @type {Renderer}
  19530. */
  19531. this.renderer = renderer;
  19532. /**
  19533. * Renderer component for managing nodes related logic.
  19534. *
  19535. * @type {Nodes}
  19536. */
  19537. this.nodes = nodes;
  19538. /**
  19539. * Renderer component for managing metrics and monitoring data.
  19540. *
  19541. * @type {Info}
  19542. */
  19543. this.info = info;
  19544. /**
  19545. * A reference to the context from `requestAnimationFrame()` can
  19546. * be called (usually `window`).
  19547. *
  19548. * @type {?(Window|XRSession)}
  19549. */
  19550. this._context = typeof self !== 'undefined' ? self : null;
  19551. /**
  19552. * The user-defined animation loop.
  19553. *
  19554. * @type {?Function}
  19555. * @default null
  19556. */
  19557. this._animationLoop = null;
  19558. /**
  19559. * The requestId which is returned from the `requestAnimationFrame()` call.
  19560. * Can be used to cancel the stop the animation loop.
  19561. *
  19562. * @type {?number}
  19563. * @default null
  19564. */
  19565. this._requestId = null;
  19566. }
  19567. /**
  19568. * Starts the internal animation loop.
  19569. */
  19570. start() {
  19571. const update = ( time, xrFrame ) => {
  19572. this._requestId = this._context.requestAnimationFrame( update );
  19573. if ( this.info.autoReset === true ) this.info.reset();
  19574. this.nodes.nodeFrame.update();
  19575. this.info.frame = this.nodes.nodeFrame.frameId;
  19576. this.renderer._inspector.begin();
  19577. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19578. this.renderer._inspector.finish();
  19579. };
  19580. update();
  19581. }
  19582. /**
  19583. * Stops the internal animation loop.
  19584. */
  19585. stop() {
  19586. this._context.cancelAnimationFrame( this._requestId );
  19587. this._requestId = null;
  19588. }
  19589. /**
  19590. * Returns the user-level animation loop.
  19591. *
  19592. * @return {?Function} The animation loop.
  19593. */
  19594. getAnimationLoop() {
  19595. return this._animationLoop;
  19596. }
  19597. /**
  19598. * Defines the user-level animation loop.
  19599. *
  19600. * @param {?Function} callback - The animation loop.
  19601. */
  19602. setAnimationLoop( callback ) {
  19603. this._animationLoop = callback;
  19604. }
  19605. /**
  19606. * Returns the animation context.
  19607. *
  19608. * @return {Window|XRSession} The animation context.
  19609. */
  19610. getContext() {
  19611. return this._context;
  19612. }
  19613. /**
  19614. * Defines the context in which `requestAnimationFrame()` is executed.
  19615. *
  19616. * @param {Window|XRSession} context - The context to set.
  19617. */
  19618. setContext( context ) {
  19619. this._context = context;
  19620. }
  19621. /**
  19622. * Frees all internal resources and stops the animation loop.
  19623. */
  19624. dispose() {
  19625. this.stop();
  19626. }
  19627. }
  19628. /**
  19629. * Data structure for the renderer. It allows defining values
  19630. * with chained, hierarchical keys. Keys are meant to be
  19631. * objects since the module internally works with Weak Maps
  19632. * for performance reasons.
  19633. *
  19634. * @private
  19635. */
  19636. class ChainMap {
  19637. /**
  19638. * Constructs a new Chain Map.
  19639. */
  19640. constructor() {
  19641. /**
  19642. * The root Weak Map.
  19643. *
  19644. * @type {WeakMap<Object, WeakMap>}
  19645. */
  19646. this.weakMap = new WeakMap();
  19647. }
  19648. /**
  19649. * Returns the value for the given array of keys.
  19650. *
  19651. * @param {Array<Object>} keys - List of keys.
  19652. * @return {any} The value. Returns `undefined` if no value was found.
  19653. */
  19654. get( keys ) {
  19655. let map = this.weakMap;
  19656. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19657. map = map.get( keys[ i ] );
  19658. if ( map === undefined ) return undefined;
  19659. }
  19660. return map.get( keys[ keys.length - 1 ] );
  19661. }
  19662. /**
  19663. * Sets the value for the given keys.
  19664. *
  19665. * @param {Array<Object>} keys - List of keys.
  19666. * @param {any} value - The value to set.
  19667. * @return {ChainMap} A reference to this Chain Map.
  19668. */
  19669. set( keys, value ) {
  19670. let map = this.weakMap;
  19671. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19672. const key = keys[ i ];
  19673. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19674. map = map.get( key );
  19675. }
  19676. map.set( keys[ keys.length - 1 ], value );
  19677. return this;
  19678. }
  19679. /**
  19680. * Deletes a value for the given keys.
  19681. *
  19682. * @param {Array<Object>} keys - The keys.
  19683. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19684. */
  19685. delete( keys ) {
  19686. let map = this.weakMap;
  19687. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19688. map = map.get( keys[ i ] );
  19689. if ( map === undefined ) return false;
  19690. }
  19691. return map.delete( keys[ keys.length - 1 ] );
  19692. }
  19693. }
  19694. let _id$9 = 0;
  19695. function getKeys( obj ) {
  19696. const keys = Object.keys( obj );
  19697. let proto = Object.getPrototypeOf( obj );
  19698. while ( proto ) {
  19699. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19700. for ( const key in descriptors ) {
  19701. if ( descriptors[ key ] !== undefined ) {
  19702. const descriptor = descriptors[ key ];
  19703. if ( descriptor && typeof descriptor.get === 'function' ) {
  19704. keys.push( key );
  19705. }
  19706. }
  19707. }
  19708. proto = Object.getPrototypeOf( proto );
  19709. }
  19710. return keys;
  19711. }
  19712. /**
  19713. * A render object is the renderer's representation of single entity that gets drawn
  19714. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19715. * scene since render objects also depend from the used material, the current render context
  19716. * and the current scene's lighting.
  19717. *
  19718. * In general, the basic process of the renderer is:
  19719. *
  19720. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19721. * - Process the render lists by calling one or more render commands for each render item.
  19722. * - For each render command, request a render object and perform the draw.
  19723. *
  19724. * The module provides an interface to get data required for the draw command like the actual
  19725. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19726. * creating render objects should only be done when necessary.
  19727. *
  19728. * @private
  19729. */
  19730. class RenderObject {
  19731. /**
  19732. * Constructs a new render object.
  19733. *
  19734. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19735. * @param {Geometries} geometries - Renderer component for managing geometries.
  19736. * @param {Renderer} renderer - The renderer.
  19737. * @param {Object3D} object - The 3D object.
  19738. * @param {Material} material - The 3D object's material.
  19739. * @param {Scene} scene - The scene the 3D object belongs to.
  19740. * @param {Camera} camera - The camera the object should be rendered with.
  19741. * @param {LightsNode} lightsNode - The lights node.
  19742. * @param {RenderContext} renderContext - The render context.
  19743. * @param {ClippingContext} clippingContext - The clipping context.
  19744. */
  19745. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19746. this.id = _id$9 ++;
  19747. /**
  19748. * Renderer component for managing nodes related logic.
  19749. *
  19750. * @type {Nodes}
  19751. * @private
  19752. */
  19753. this._nodes = nodes;
  19754. /**
  19755. * Renderer component for managing geometries.
  19756. *
  19757. * @type {Geometries}
  19758. * @private
  19759. */
  19760. this._geometries = geometries;
  19761. /**
  19762. * The renderer.
  19763. *
  19764. * @type {Renderer}
  19765. */
  19766. this.renderer = renderer;
  19767. /**
  19768. * The 3D object.
  19769. *
  19770. * @type {Object3D}
  19771. */
  19772. this.object = object;
  19773. /**
  19774. * The 3D object's material.
  19775. *
  19776. * @type {Material}
  19777. */
  19778. this.material = material;
  19779. /**
  19780. * The scene the 3D object belongs to.
  19781. *
  19782. * @type {Scene}
  19783. */
  19784. this.scene = scene;
  19785. /**
  19786. * The camera the 3D object should be rendered with.
  19787. *
  19788. * @type {Camera}
  19789. */
  19790. this.camera = camera;
  19791. /**
  19792. * The lights node.
  19793. *
  19794. * @type {LightsNode}
  19795. */
  19796. this.lightsNode = lightsNode;
  19797. /**
  19798. * The render context.
  19799. *
  19800. * @type {RenderContext}
  19801. */
  19802. this.context = renderContext;
  19803. /**
  19804. * The 3D object's geometry.
  19805. *
  19806. * @type {BufferGeometry}
  19807. */
  19808. this.geometry = object.geometry;
  19809. /**
  19810. * The render object's version.
  19811. *
  19812. * @type {number}
  19813. */
  19814. this.version = material.version;
  19815. /**
  19816. * The draw range of the geometry.
  19817. *
  19818. * @type {?Object}
  19819. * @default null
  19820. */
  19821. this.drawRange = null;
  19822. /**
  19823. * An array holding the buffer attributes
  19824. * of the render object. This entails attribute
  19825. * definitions on geometry and node level.
  19826. *
  19827. * @type {?Array<BufferAttribute>}
  19828. * @default null
  19829. */
  19830. this.attributes = null;
  19831. /**
  19832. * An object holding the version of the
  19833. * attributes. The keys are the attribute names
  19834. * and the values are the attribute versions.
  19835. *
  19836. * @type {?Object<string, number>}
  19837. * @default null
  19838. */
  19839. this.attributesId = null;
  19840. /**
  19841. * A reference to a render pipeline the render
  19842. * object is processed with.
  19843. *
  19844. * @type {RenderPipeline}
  19845. * @default null
  19846. */
  19847. this.pipeline = null;
  19848. /**
  19849. * Only relevant for objects using
  19850. * multiple materials. This represents a group entry
  19851. * from the respective `BufferGeometry`.
  19852. *
  19853. * @type {?{start: number, count: number}}
  19854. * @default null
  19855. */
  19856. this.group = null;
  19857. /**
  19858. * An array holding the vertex buffers which can
  19859. * be buffer attributes but also interleaved buffers.
  19860. *
  19861. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19862. * @default null
  19863. */
  19864. this.vertexBuffers = null;
  19865. /**
  19866. * The parameters for the draw command.
  19867. *
  19868. * @type {?Object}
  19869. * @default null
  19870. */
  19871. this.drawParams = null;
  19872. /**
  19873. * If this render object is used inside a render bundle,
  19874. * this property points to the respective bundle group.
  19875. *
  19876. * @type {?BundleGroup}
  19877. * @default null
  19878. */
  19879. this.bundle = null;
  19880. /**
  19881. * The clipping context.
  19882. *
  19883. * @type {ClippingContext}
  19884. */
  19885. this.clippingContext = clippingContext;
  19886. /**
  19887. * The clipping context's cache key.
  19888. *
  19889. * @type {string}
  19890. */
  19891. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19892. /**
  19893. * The initial node cache key.
  19894. *
  19895. * @type {number}
  19896. */
  19897. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19898. /**
  19899. * The initial cache key.
  19900. *
  19901. * @type {number}
  19902. */
  19903. this.initialCacheKey = this.getCacheKey();
  19904. /**
  19905. * The node builder state.
  19906. *
  19907. * @type {?NodeBuilderState}
  19908. * @private
  19909. * @default null
  19910. */
  19911. this._nodeBuilderState = null;
  19912. /**
  19913. * An array of bindings.
  19914. *
  19915. * @type {?Array<BindGroup>}
  19916. * @private
  19917. * @default null
  19918. */
  19919. this._bindings = null;
  19920. /**
  19921. * Reference to the node material observer.
  19922. *
  19923. * @type {?NodeMaterialObserver}
  19924. * @private
  19925. * @default null
  19926. */
  19927. this._monitor = null;
  19928. /**
  19929. * An event listener which is defined by `RenderObjects`. It performs
  19930. * clean up tasks when `dispose()` on this render object.
  19931. *
  19932. * @method
  19933. */
  19934. this.onDispose = null;
  19935. /**
  19936. * This flag can be used for type testing.
  19937. *
  19938. * @type {boolean}
  19939. * @readonly
  19940. * @default true
  19941. */
  19942. this.isRenderObject = true;
  19943. /**
  19944. * An event listener which is executed when `dispose()` is called on
  19945. * the material of this render object.
  19946. *
  19947. * @method
  19948. */
  19949. this.onMaterialDispose = () => {
  19950. this.dispose();
  19951. };
  19952. /**
  19953. * An event listener which is executed when `dispose()` is called on
  19954. * the geometry of this render object.
  19955. *
  19956. * @method
  19957. */
  19958. this.onGeometryDispose = () => {
  19959. // clear geometry cache attributes
  19960. this.attributes = null;
  19961. this.attributesId = null;
  19962. };
  19963. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19964. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19965. }
  19966. /**
  19967. * Updates the clipping context.
  19968. *
  19969. * @param {ClippingContext} context - The clipping context to set.
  19970. */
  19971. updateClipping( context ) {
  19972. this.clippingContext = context;
  19973. }
  19974. /**
  19975. * Whether the clipping requires an update or not.
  19976. *
  19977. * @type {boolean}
  19978. * @readonly
  19979. */
  19980. get clippingNeedsUpdate() {
  19981. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19982. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19983. return true;
  19984. }
  19985. /**
  19986. * The number of clipping planes defined in context of hardware clipping.
  19987. *
  19988. * @type {number}
  19989. * @readonly
  19990. */
  19991. get hardwareClippingPlanes() {
  19992. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19993. }
  19994. /**
  19995. * Returns the node builder state of this render object.
  19996. *
  19997. * @return {NodeBuilderState} The node builder state.
  19998. */
  19999. getNodeBuilderState() {
  20000. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20001. }
  20002. /**
  20003. * Returns the node material observer of this render object.
  20004. *
  20005. * @return {NodeMaterialObserver} The node material observer.
  20006. */
  20007. getMonitor() {
  20008. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20009. }
  20010. /**
  20011. * Returns an array of bind groups of this render object.
  20012. *
  20013. * @return {Array<BindGroup>} The bindings.
  20014. */
  20015. getBindings() {
  20016. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20017. }
  20018. /**
  20019. * Returns a binding group by group name of this render object.
  20020. *
  20021. * @param {string} name - The name of the binding group.
  20022. * @return {?BindGroup} The bindings.
  20023. */
  20024. getBindingGroup( name ) {
  20025. for ( const bindingGroup of this.getBindings() ) {
  20026. if ( bindingGroup.name === name ) {
  20027. return bindingGroup;
  20028. }
  20029. }
  20030. }
  20031. /**
  20032. * Returns the index of the render object's geometry.
  20033. *
  20034. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20035. */
  20036. getIndex() {
  20037. return this._geometries.getIndex( this );
  20038. }
  20039. /**
  20040. * Returns the indirect buffer attribute.
  20041. *
  20042. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20043. */
  20044. getIndirect() {
  20045. return this._geometries.getIndirect( this );
  20046. }
  20047. /**
  20048. * Returns an array that acts as a key for identifying the render object in a chain map.
  20049. *
  20050. * @return {Array<Object>} An array with object references.
  20051. */
  20052. getChainArray() {
  20053. return [ this.object, this.material, this.context, this.lightsNode ];
  20054. }
  20055. /**
  20056. * This method is used when the geometry of a 3D object has been exchanged and the
  20057. * respective render object now requires an update.
  20058. *
  20059. * @param {BufferGeometry} geometry - The geometry to set.
  20060. */
  20061. setGeometry( geometry ) {
  20062. this.geometry = geometry;
  20063. this.attributes = null;
  20064. this.attributesId = null;
  20065. }
  20066. /**
  20067. * Returns the buffer attributes of the render object. The returned array holds
  20068. * attribute definitions on geometry and node level.
  20069. *
  20070. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20071. */
  20072. getAttributes() {
  20073. if ( this.attributes !== null ) return this.attributes;
  20074. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20075. const geometry = this.geometry;
  20076. const attributes = [];
  20077. const vertexBuffers = new Set();
  20078. const attributesId = {};
  20079. for ( const nodeAttribute of nodeAttributes ) {
  20080. let attribute;
  20081. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20082. // node attribute
  20083. attribute = nodeAttribute.node.attribute;
  20084. } else {
  20085. // geometry attribute
  20086. attribute = geometry.getAttribute( nodeAttribute.name );
  20087. attributesId[ nodeAttribute.name ] = attribute.version;
  20088. }
  20089. if ( attribute === undefined ) continue;
  20090. attributes.push( attribute );
  20091. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20092. vertexBuffers.add( bufferAttribute );
  20093. }
  20094. this.attributes = attributes;
  20095. this.attributesId = attributesId;
  20096. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20097. return attributes;
  20098. }
  20099. /**
  20100. * Returns the vertex buffers of the render object.
  20101. *
  20102. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20103. */
  20104. getVertexBuffers() {
  20105. if ( this.vertexBuffers === null ) this.getAttributes();
  20106. return this.vertexBuffers;
  20107. }
  20108. /**
  20109. * Returns the draw parameters for the render object.
  20110. *
  20111. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20112. */
  20113. getDrawParameters() {
  20114. const { object, material, geometry, group, drawRange } = this;
  20115. const drawParams = this.drawParams || ( this.drawParams = {
  20116. vertexCount: 0,
  20117. firstVertex: 0,
  20118. instanceCount: 0,
  20119. firstInstance: 0
  20120. } );
  20121. const index = this.getIndex();
  20122. const hasIndex = ( index !== null );
  20123. let instanceCount = 1;
  20124. if ( geometry.isInstancedBufferGeometry === true ) {
  20125. instanceCount = geometry.instanceCount;
  20126. } else if ( object.count !== undefined ) {
  20127. instanceCount = Math.max( 0, object.count );
  20128. }
  20129. if ( instanceCount === 0 ) return null;
  20130. drawParams.instanceCount = instanceCount;
  20131. if ( object.isBatchedMesh === true ) return drawParams;
  20132. let rangeFactor = 1;
  20133. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20134. rangeFactor = 2;
  20135. }
  20136. let firstVertex = drawRange.start * rangeFactor;
  20137. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20138. if ( group !== null ) {
  20139. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20140. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20141. }
  20142. const position = geometry.attributes.position;
  20143. let itemCount = Infinity;
  20144. if ( hasIndex ) {
  20145. itemCount = index.count;
  20146. } else if ( position !== undefined && position !== null ) {
  20147. itemCount = position.count;
  20148. }
  20149. firstVertex = Math.max( firstVertex, 0 );
  20150. lastVertex = Math.min( lastVertex, itemCount );
  20151. const count = lastVertex - firstVertex;
  20152. if ( count < 0 || count === Infinity ) return null;
  20153. drawParams.vertexCount = count;
  20154. drawParams.firstVertex = firstVertex;
  20155. return drawParams;
  20156. }
  20157. /**
  20158. * Returns the render object's geometry cache key.
  20159. *
  20160. * The geometry cache key is part of the material cache key.
  20161. *
  20162. * @return {string} The geometry cache key.
  20163. */
  20164. getGeometryCacheKey() {
  20165. const { geometry } = this;
  20166. let cacheKey = '';
  20167. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20168. const attribute = geometry.attributes[ name ];
  20169. cacheKey += name + ',';
  20170. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20171. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20172. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20173. if ( attribute.normalized ) cacheKey += 'n,';
  20174. }
  20175. // structural equality isn't sufficient for morph targets since the
  20176. // data are maintained in textures. only if the targets are all equal
  20177. // the texture and thus the instance of `MorphNode` can be shared.
  20178. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20179. const targets = geometry.morphAttributes[ name ];
  20180. cacheKey += 'morph-' + name + ',';
  20181. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20182. const attribute = targets[ i ];
  20183. cacheKey += attribute.id + ',';
  20184. }
  20185. }
  20186. if ( geometry.index ) {
  20187. cacheKey += 'index,';
  20188. }
  20189. return cacheKey;
  20190. }
  20191. /**
  20192. * Returns the render object's material cache key.
  20193. *
  20194. * The material cache key is part of the render object cache key.
  20195. *
  20196. * @return {number} The material cache key.
  20197. */
  20198. getMaterialCacheKey() {
  20199. const { object, material, renderer } = this;
  20200. let cacheKey = material.customProgramCacheKey();
  20201. for ( const property of getKeys( material ) ) {
  20202. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20203. const value = material[ property ];
  20204. let valueKey;
  20205. if ( value !== null ) {
  20206. // some material values require a formatting
  20207. const type = typeof value;
  20208. if ( type === 'number' ) {
  20209. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20210. } else if ( type === 'object' ) {
  20211. valueKey = '{';
  20212. if ( value.isTexture ) {
  20213. valueKey += value.mapping;
  20214. // WebGPU must honor the sampler data because they are part of the bindings
  20215. if ( renderer.backend.isWebGPUBackend === true ) {
  20216. valueKey += value.magFilter;
  20217. valueKey += value.minFilter;
  20218. valueKey += value.wrapS;
  20219. valueKey += value.wrapT;
  20220. valueKey += value.wrapR;
  20221. }
  20222. }
  20223. valueKey += '}';
  20224. } else {
  20225. valueKey = String( value );
  20226. }
  20227. } else {
  20228. valueKey = String( value );
  20229. }
  20230. cacheKey += /*property + ':' +*/ valueKey + ',';
  20231. }
  20232. cacheKey += this.clippingContextCacheKey + ',';
  20233. if ( object.geometry ) {
  20234. cacheKey += this.getGeometryCacheKey();
  20235. }
  20236. if ( object.skeleton ) {
  20237. cacheKey += object.skeleton.bones.length + ',';
  20238. }
  20239. if ( object.isBatchedMesh ) {
  20240. cacheKey += object._matricesTexture.uuid + ',';
  20241. if ( object._colorsTexture !== null ) {
  20242. cacheKey += object._colorsTexture.uuid + ',';
  20243. }
  20244. }
  20245. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20246. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20247. cacheKey += object.uuid + ',';
  20248. }
  20249. cacheKey += object.receiveShadow + ',';
  20250. return hashString( cacheKey );
  20251. }
  20252. /**
  20253. * Whether the geometry requires an update or not.
  20254. *
  20255. * @type {boolean}
  20256. * @readonly
  20257. */
  20258. get needsGeometryUpdate() {
  20259. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20260. if ( this.attributes !== null ) {
  20261. const attributesId = this.attributesId;
  20262. for ( const name in attributesId ) {
  20263. const attribute = this.geometry.getAttribute( name );
  20264. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20265. return true;
  20266. }
  20267. }
  20268. }
  20269. return false;
  20270. }
  20271. /**
  20272. * Whether the render object requires an update or not.
  20273. *
  20274. * Note: There are two distinct places where render objects are checked for an update.
  20275. *
  20276. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20277. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20278. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20279. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20280. * a need for a refresh due to material, geometry or object related value changes.
  20281. *
  20282. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20283. * that performs the 'needsUpdate' check.
  20284. *
  20285. * @type {boolean}
  20286. * @readonly
  20287. */
  20288. get needsUpdate() {
  20289. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20290. }
  20291. /**
  20292. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20293. *
  20294. * @return {number} The cache key.
  20295. */
  20296. getDynamicCacheKey() {
  20297. let cacheKey = 0;
  20298. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20299. // the renderer is inside a shadow pass.
  20300. if ( this.material.isShadowPassMaterial !== true ) {
  20301. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20302. }
  20303. if ( this.camera.isArrayCamera ) {
  20304. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20305. }
  20306. if ( this.object.receiveShadow ) {
  20307. cacheKey = hash$1( cacheKey, 1 );
  20308. }
  20309. return cacheKey;
  20310. }
  20311. /**
  20312. * Returns the render object's cache key.
  20313. *
  20314. * @return {number} The cache key.
  20315. */
  20316. getCacheKey() {
  20317. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20318. }
  20319. /**
  20320. * Frees internal resources.
  20321. */
  20322. dispose() {
  20323. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20324. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20325. this.onDispose();
  20326. }
  20327. }
  20328. const _chainKeys$5 = [];
  20329. /**
  20330. * This module manages the render objects of the renderer.
  20331. *
  20332. * @private
  20333. */
  20334. class RenderObjects {
  20335. /**
  20336. * Constructs a new render object management component.
  20337. *
  20338. * @param {Renderer} renderer - The renderer.
  20339. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20340. * @param {Geometries} geometries - Renderer component for managing geometries.
  20341. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20342. * @param {Bindings} bindings - Renderer component for managing bindings.
  20343. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20344. */
  20345. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20346. /**
  20347. * The renderer.
  20348. *
  20349. * @type {Renderer}
  20350. */
  20351. this.renderer = renderer;
  20352. /**
  20353. * Renderer component for managing nodes related logic.
  20354. *
  20355. * @type {Nodes}
  20356. */
  20357. this.nodes = nodes;
  20358. /**
  20359. * Renderer component for managing geometries.
  20360. *
  20361. * @type {Geometries}
  20362. */
  20363. this.geometries = geometries;
  20364. /**
  20365. * Renderer component for managing pipelines.
  20366. *
  20367. * @type {Pipelines}
  20368. */
  20369. this.pipelines = pipelines;
  20370. /**
  20371. * Renderer component for managing bindings.
  20372. *
  20373. * @type {Bindings}
  20374. */
  20375. this.bindings = bindings;
  20376. /**
  20377. * Renderer component for managing metrics and monitoring data.
  20378. *
  20379. * @type {Info}
  20380. */
  20381. this.info = info;
  20382. /**
  20383. * A dictionary that manages render contexts in chain maps
  20384. * for each pass ID.
  20385. *
  20386. * @type {Object<string,ChainMap>}
  20387. */
  20388. this.chainMaps = {};
  20389. }
  20390. /**
  20391. * Returns a render object for the given object and state data.
  20392. *
  20393. * @param {Object3D} object - The 3D object.
  20394. * @param {Material} material - The 3D object's material.
  20395. * @param {Scene} scene - The scene the 3D object belongs to.
  20396. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20397. * @param {LightsNode} lightsNode - The lights node.
  20398. * @param {RenderContext} renderContext - The render context.
  20399. * @param {ClippingContext} clippingContext - The clipping context.
  20400. * @param {string} [passId] - An optional ID for identifying the pass.
  20401. * @return {RenderObject} The render object.
  20402. */
  20403. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20404. const chainMap = this.getChainMap( passId );
  20405. // reuse chainArray
  20406. _chainKeys$5[ 0 ] = object;
  20407. _chainKeys$5[ 1 ] = material;
  20408. _chainKeys$5[ 2 ] = renderContext;
  20409. _chainKeys$5[ 3 ] = lightsNode;
  20410. let renderObject = chainMap.get( _chainKeys$5 );
  20411. if ( renderObject === undefined ) {
  20412. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20413. chainMap.set( _chainKeys$5, renderObject );
  20414. } else {
  20415. renderObject.updateClipping( clippingContext );
  20416. if ( renderObject.needsGeometryUpdate ) {
  20417. renderObject.setGeometry( object.geometry );
  20418. }
  20419. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20420. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20421. renderObject.dispose();
  20422. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20423. } else {
  20424. renderObject.version = material.version;
  20425. }
  20426. }
  20427. }
  20428. _chainKeys$5.length = 0;
  20429. return renderObject;
  20430. }
  20431. /**
  20432. * Returns a chain map for the given pass ID.
  20433. *
  20434. * @param {string} [passId='default'] - The pass ID.
  20435. * @return {ChainMap} The chain map.
  20436. */
  20437. getChainMap( passId = 'default' ) {
  20438. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20439. }
  20440. /**
  20441. * Frees internal resources.
  20442. */
  20443. dispose() {
  20444. this.chainMaps = {};
  20445. }
  20446. /**
  20447. * Factory method for creating render objects with the given list of parameters.
  20448. *
  20449. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20450. * @param {Geometries} geometries - Renderer component for managing geometries.
  20451. * @param {Renderer} renderer - The renderer.
  20452. * @param {Object3D} object - The 3D object.
  20453. * @param {Material} material - The object's material.
  20454. * @param {Scene} scene - The scene the 3D object belongs to.
  20455. * @param {Camera} camera - The camera the object should be rendered with.
  20456. * @param {LightsNode} lightsNode - The lights node.
  20457. * @param {RenderContext} renderContext - The render context.
  20458. * @param {ClippingContext} clippingContext - The clipping context.
  20459. * @param {string} [passId] - An optional ID for identifying the pass.
  20460. * @return {RenderObject} The render object.
  20461. */
  20462. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20463. const chainMap = this.getChainMap( passId );
  20464. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20465. renderObject.onDispose = () => {
  20466. this.pipelines.delete( renderObject );
  20467. this.bindings.deleteForRender( renderObject );
  20468. this.nodes.delete( renderObject );
  20469. chainMap.delete( renderObject.getChainArray() );
  20470. };
  20471. return renderObject;
  20472. }
  20473. }
  20474. /**
  20475. * Data structure for the renderer. It is intended to manage
  20476. * data of objects in dictionaries.
  20477. *
  20478. * @private
  20479. */
  20480. class DataMap {
  20481. /**
  20482. * Constructs a new data map.
  20483. */
  20484. constructor() {
  20485. /**
  20486. * `DataMap` internally uses a weak map
  20487. * to manage its data.
  20488. *
  20489. * @type {WeakMap<Object, Object>}
  20490. */
  20491. this.data = new WeakMap();
  20492. }
  20493. /**
  20494. * Returns the dictionary for the given object.
  20495. *
  20496. * @param {Object} object - The object.
  20497. * @return {Object} The dictionary.
  20498. */
  20499. get( object ) {
  20500. let map = this.data.get( object );
  20501. if ( map === undefined ) {
  20502. map = {};
  20503. this.data.set( object, map );
  20504. }
  20505. return map;
  20506. }
  20507. /**
  20508. * Deletes the dictionary for the given object.
  20509. *
  20510. * @param {Object} object - The object.
  20511. * @return {?Object} The deleted dictionary.
  20512. */
  20513. delete( object ) {
  20514. let map = null;
  20515. if ( this.data.has( object ) ) {
  20516. map = this.data.get( object );
  20517. this.data.delete( object );
  20518. }
  20519. return map;
  20520. }
  20521. /**
  20522. * Returns `true` if the given object has a dictionary defined.
  20523. *
  20524. * @param {Object} object - The object to test.
  20525. * @return {boolean} Whether a dictionary is defined or not.
  20526. */
  20527. has( object ) {
  20528. return this.data.has( object );
  20529. }
  20530. /**
  20531. * Frees internal resources.
  20532. */
  20533. dispose() {
  20534. this.data = new WeakMap();
  20535. }
  20536. }
  20537. const AttributeType = {
  20538. VERTEX: 1,
  20539. INDEX: 2,
  20540. STORAGE: 3,
  20541. INDIRECT: 4
  20542. };
  20543. // size of a chunk in bytes (STD140 layout)
  20544. const GPU_CHUNK_BYTES = 16;
  20545. // @TODO: Move to src/constants.js
  20546. const BlendColorFactor = 211;
  20547. const OneMinusBlendColorFactor = 212;
  20548. /**
  20549. * This renderer module manages geometry attributes.
  20550. *
  20551. * @private
  20552. * @augments DataMap
  20553. */
  20554. class Attributes extends DataMap {
  20555. /**
  20556. * Constructs a new attribute management component.
  20557. *
  20558. * @param {Backend} backend - The renderer's backend.
  20559. */
  20560. constructor( backend ) {
  20561. super();
  20562. /**
  20563. * The renderer's backend.
  20564. *
  20565. * @type {Backend}
  20566. */
  20567. this.backend = backend;
  20568. }
  20569. /**
  20570. * Deletes the data for the given attribute.
  20571. *
  20572. * @param {BufferAttribute} attribute - The attribute.
  20573. * @return {?Object} The deleted attribute data.
  20574. */
  20575. delete( attribute ) {
  20576. const attributeData = super.delete( attribute );
  20577. if ( attributeData !== null ) {
  20578. this.backend.destroyAttribute( attribute );
  20579. }
  20580. return attributeData;
  20581. }
  20582. /**
  20583. * Updates the given attribute. This method creates attribute buffers
  20584. * for new attributes and updates data for existing ones.
  20585. *
  20586. * @param {BufferAttribute} attribute - The attribute to update.
  20587. * @param {number} type - The attribute type.
  20588. */
  20589. update( attribute, type ) {
  20590. const data = this.get( attribute );
  20591. if ( data.version === undefined ) {
  20592. if ( type === AttributeType.VERTEX ) {
  20593. this.backend.createAttribute( attribute );
  20594. } else if ( type === AttributeType.INDEX ) {
  20595. this.backend.createIndexAttribute( attribute );
  20596. } else if ( type === AttributeType.STORAGE ) {
  20597. this.backend.createStorageAttribute( attribute );
  20598. } else if ( type === AttributeType.INDIRECT ) {
  20599. this.backend.createIndirectStorageAttribute( attribute );
  20600. }
  20601. data.version = this._getBufferAttribute( attribute ).version;
  20602. } else {
  20603. const bufferAttribute = this._getBufferAttribute( attribute );
  20604. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20605. this.backend.updateAttribute( attribute );
  20606. data.version = bufferAttribute.version;
  20607. }
  20608. }
  20609. }
  20610. /**
  20611. * Utility method for handling interleaved buffer attributes correctly.
  20612. * To process them, their `InterleavedBuffer` is returned.
  20613. *
  20614. * @param {BufferAttribute} attribute - The attribute.
  20615. * @return {BufferAttribute|InterleavedBuffer}
  20616. */
  20617. _getBufferAttribute( attribute ) {
  20618. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20619. return attribute;
  20620. }
  20621. }
  20622. /**
  20623. * Returns the wireframe version for the given geometry.
  20624. *
  20625. * @private
  20626. * @function
  20627. * @param {BufferGeometry} geometry - The geometry.
  20628. * @return {number} The version.
  20629. */
  20630. function getWireframeVersion( geometry ) {
  20631. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20632. }
  20633. /**
  20634. * Returns a wireframe index attribute for the given geometry.
  20635. *
  20636. * @private
  20637. * @function
  20638. * @param {BufferGeometry} geometry - The geometry.
  20639. * @return {BufferAttribute} The wireframe index attribute.
  20640. */
  20641. function getWireframeIndex( geometry ) {
  20642. const indices = [];
  20643. const geometryIndex = geometry.index;
  20644. const geometryPosition = geometry.attributes.position;
  20645. if ( geometryIndex !== null ) {
  20646. const array = geometryIndex.array;
  20647. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20648. const a = array[ i + 0 ];
  20649. const b = array[ i + 1 ];
  20650. const c = array[ i + 2 ];
  20651. indices.push( a, b, b, c, c, a );
  20652. }
  20653. } else {
  20654. const array = geometryPosition.array;
  20655. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20656. const a = i + 0;
  20657. const b = i + 1;
  20658. const c = i + 2;
  20659. indices.push( a, b, b, c, c, a );
  20660. }
  20661. }
  20662. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20663. attribute.version = getWireframeVersion( geometry );
  20664. return attribute;
  20665. }
  20666. /**
  20667. * This renderer module manages geometries.
  20668. *
  20669. * @private
  20670. * @augments DataMap
  20671. */
  20672. class Geometries extends DataMap {
  20673. /**
  20674. * Constructs a new geometry management component.
  20675. *
  20676. * @param {Attributes} attributes - Renderer component for managing attributes.
  20677. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20678. */
  20679. constructor( attributes, info ) {
  20680. super();
  20681. /**
  20682. * Renderer component for managing attributes.
  20683. *
  20684. * @type {Attributes}
  20685. */
  20686. this.attributes = attributes;
  20687. /**
  20688. * Renderer component for managing metrics and monitoring data.
  20689. *
  20690. * @type {Info}
  20691. */
  20692. this.info = info;
  20693. /**
  20694. * Weak Map for managing attributes for wireframe rendering.
  20695. *
  20696. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20697. */
  20698. this.wireframes = new WeakMap();
  20699. /**
  20700. * This Weak Map is used to make sure buffer attributes are
  20701. * updated only once per render call.
  20702. *
  20703. * @type {WeakMap<BufferAttribute,number>}
  20704. */
  20705. this.attributeCall = new WeakMap();
  20706. /**
  20707. * Stores the event listeners attached to geometries.
  20708. *
  20709. * @private
  20710. * @type {Map<BufferGeometry,Function>}
  20711. */
  20712. this._geometryDisposeListeners = new Map();
  20713. }
  20714. /**
  20715. * Returns `true` if the given render object has an initialized geometry.
  20716. *
  20717. * @param {RenderObject} renderObject - The render object.
  20718. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20719. */
  20720. has( renderObject ) {
  20721. const geometry = renderObject.geometry;
  20722. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20723. }
  20724. /**
  20725. * Prepares the geometry of the given render object for rendering.
  20726. *
  20727. * @param {RenderObject} renderObject - The render object.
  20728. */
  20729. updateForRender( renderObject ) {
  20730. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20731. this.updateAttributes( renderObject );
  20732. }
  20733. /**
  20734. * Initializes the geometry of the given render object.
  20735. *
  20736. * @param {RenderObject} renderObject - The render object.
  20737. */
  20738. initGeometry( renderObject ) {
  20739. const geometry = renderObject.geometry;
  20740. const geometryData = this.get( geometry );
  20741. geometryData.initialized = true;
  20742. this.info.memory.geometries ++;
  20743. const onDispose = () => {
  20744. this.info.memory.geometries --;
  20745. const index = geometry.index;
  20746. const geometryAttributes = renderObject.getAttributes();
  20747. if ( index !== null ) {
  20748. this.attributes.delete( index );
  20749. }
  20750. for ( const geometryAttribute of geometryAttributes ) {
  20751. this.attributes.delete( geometryAttribute );
  20752. }
  20753. const wireframeAttribute = this.wireframes.get( geometry );
  20754. if ( wireframeAttribute !== undefined ) {
  20755. this.attributes.delete( wireframeAttribute );
  20756. }
  20757. geometry.removeEventListener( 'dispose', onDispose );
  20758. this._geometryDisposeListeners.delete( geometry );
  20759. };
  20760. geometry.addEventListener( 'dispose', onDispose );
  20761. // see #31798 why tracking separate remove listeners is required right now
  20762. // TODO: Re-evaluate how onDispose() is managed in this component
  20763. this._geometryDisposeListeners.set( geometry, onDispose );
  20764. }
  20765. /**
  20766. * Updates the geometry attributes of the given render object.
  20767. *
  20768. * @param {RenderObject} renderObject - The render object.
  20769. */
  20770. updateAttributes( renderObject ) {
  20771. // attributes
  20772. const attributes = renderObject.getAttributes();
  20773. for ( const attribute of attributes ) {
  20774. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20775. this.updateAttribute( attribute, AttributeType.STORAGE );
  20776. } else {
  20777. this.updateAttribute( attribute, AttributeType.VERTEX );
  20778. }
  20779. }
  20780. // indexes
  20781. const index = this.getIndex( renderObject );
  20782. if ( index !== null ) {
  20783. this.updateAttribute( index, AttributeType.INDEX );
  20784. }
  20785. // indirect
  20786. const indirect = renderObject.geometry.indirect;
  20787. if ( indirect !== null ) {
  20788. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20789. }
  20790. }
  20791. /**
  20792. * Updates the given attribute.
  20793. *
  20794. * @param {BufferAttribute} attribute - The attribute to update.
  20795. * @param {number} type - The attribute type.
  20796. */
  20797. updateAttribute( attribute, type ) {
  20798. const callId = this.info.render.calls;
  20799. if ( ! attribute.isInterleavedBufferAttribute ) {
  20800. if ( this.attributeCall.get( attribute ) !== callId ) {
  20801. this.attributes.update( attribute, type );
  20802. this.attributeCall.set( attribute, callId );
  20803. }
  20804. } else {
  20805. if ( this.attributeCall.get( attribute ) === undefined ) {
  20806. this.attributes.update( attribute, type );
  20807. this.attributeCall.set( attribute, callId );
  20808. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20809. this.attributes.update( attribute, type );
  20810. this.attributeCall.set( attribute.data, callId );
  20811. this.attributeCall.set( attribute, callId );
  20812. }
  20813. }
  20814. }
  20815. /**
  20816. * Returns the indirect buffer attribute of the given render object.
  20817. *
  20818. * @param {RenderObject} renderObject - The render object.
  20819. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20820. */
  20821. getIndirect( renderObject ) {
  20822. return renderObject.geometry.indirect;
  20823. }
  20824. /**
  20825. * Returns the index of the given render object's geometry. This is implemented
  20826. * in a method to return a wireframe index if necessary.
  20827. *
  20828. * @param {RenderObject} renderObject - The render object.
  20829. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20830. */
  20831. getIndex( renderObject ) {
  20832. const { geometry, material } = renderObject;
  20833. let index = geometry.index;
  20834. if ( material.wireframe === true ) {
  20835. const wireframes = this.wireframes;
  20836. let wireframeAttribute = wireframes.get( geometry );
  20837. if ( wireframeAttribute === undefined ) {
  20838. wireframeAttribute = getWireframeIndex( geometry );
  20839. wireframes.set( geometry, wireframeAttribute );
  20840. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20841. this.attributes.delete( wireframeAttribute );
  20842. wireframeAttribute = getWireframeIndex( geometry );
  20843. wireframes.set( geometry, wireframeAttribute );
  20844. }
  20845. index = wireframeAttribute;
  20846. }
  20847. return index;
  20848. }
  20849. dispose() {
  20850. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  20851. geometry.removeEventListener( 'dispose', onDispose );
  20852. }
  20853. this._geometryDisposeListeners.clear();
  20854. }
  20855. }
  20856. /**
  20857. * This renderer module provides a series of statistical information
  20858. * about the GPU memory and the rendering process. Useful for debugging
  20859. * and monitoring.
  20860. */
  20861. class Info {
  20862. /**
  20863. * Constructs a new info component.
  20864. */
  20865. constructor() {
  20866. /**
  20867. * Whether frame related metrics should automatically
  20868. * be resetted or not. This property should be set to `false`
  20869. * by apps which manage their own animation loop. They must
  20870. * then call `renderer.info.reset()` once per frame manually.
  20871. *
  20872. * @type {boolean}
  20873. * @default true
  20874. */
  20875. this.autoReset = true;
  20876. /**
  20877. * The current frame ID. This ID is managed
  20878. * by `NodeFrame`.
  20879. *
  20880. * @type {number}
  20881. * @readonly
  20882. * @default 0
  20883. */
  20884. this.frame = 0;
  20885. /**
  20886. * The number of render calls since the
  20887. * app has been started.
  20888. *
  20889. * @type {number}
  20890. * @readonly
  20891. * @default 0
  20892. */
  20893. this.calls = 0;
  20894. /**
  20895. * Render related metrics.
  20896. *
  20897. * @type {Object}
  20898. * @readonly
  20899. * @property {number} calls - The number of render calls since the app has been started.
  20900. * @property {number} frameCalls - The number of render calls of the current frame.
  20901. * @property {number} drawCalls - The number of draw calls of the current frame.
  20902. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20903. * @property {number} points - The number of rendered point primitives of the current frame.
  20904. * @property {number} lines - The number of rendered line primitives of the current frame.
  20905. * @property {number} timestamp - The timestamp of the frame.
  20906. */
  20907. this.render = {
  20908. calls: 0,
  20909. frameCalls: 0,
  20910. drawCalls: 0,
  20911. triangles: 0,
  20912. points: 0,
  20913. lines: 0,
  20914. timestamp: 0,
  20915. };
  20916. /**
  20917. * Compute related metrics.
  20918. *
  20919. * @type {Object}
  20920. * @readonly
  20921. * @property {number} calls - The number of compute calls since the app has been started.
  20922. * @property {number} frameCalls - The number of compute calls of the current frame.
  20923. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20924. */
  20925. this.compute = {
  20926. calls: 0,
  20927. frameCalls: 0,
  20928. timestamp: 0
  20929. };
  20930. /**
  20931. * Memory related metrics.
  20932. *
  20933. * @type {Object}
  20934. * @readonly
  20935. * @property {number} geometries - The number of active geometries.
  20936. * @property {number} frameCalls - The number of active textures.
  20937. */
  20938. this.memory = {
  20939. geometries: 0,
  20940. textures: 0
  20941. };
  20942. }
  20943. /**
  20944. * This method should be executed per draw call and updates the corresponding metrics.
  20945. *
  20946. * @param {Object3D} object - The 3D object that is going to be rendered.
  20947. * @param {number} count - The vertex or index count.
  20948. * @param {number} instanceCount - The instance count.
  20949. */
  20950. update( object, count, instanceCount ) {
  20951. this.render.drawCalls ++;
  20952. if ( object.isMesh || object.isSprite ) {
  20953. this.render.triangles += instanceCount * ( count / 3 );
  20954. } else if ( object.isPoints ) {
  20955. this.render.points += instanceCount * count;
  20956. } else if ( object.isLineSegments ) {
  20957. this.render.lines += instanceCount * ( count / 2 );
  20958. } else if ( object.isLine ) {
  20959. this.render.lines += instanceCount * ( count - 1 );
  20960. } else {
  20961. error( 'WebGPUInfo: Unknown object type.' );
  20962. }
  20963. }
  20964. /**
  20965. * Resets frame related metrics.
  20966. */
  20967. reset() {
  20968. this.render.drawCalls = 0;
  20969. this.render.frameCalls = 0;
  20970. this.compute.frameCalls = 0;
  20971. this.render.triangles = 0;
  20972. this.render.points = 0;
  20973. this.render.lines = 0;
  20974. }
  20975. /**
  20976. * Performs a complete reset of the object.
  20977. */
  20978. dispose() {
  20979. this.reset();
  20980. this.calls = 0;
  20981. this.render.calls = 0;
  20982. this.compute.calls = 0;
  20983. this.render.timestamp = 0;
  20984. this.compute.timestamp = 0;
  20985. this.memory.geometries = 0;
  20986. this.memory.textures = 0;
  20987. }
  20988. }
  20989. /**
  20990. * Abstract class for representing pipelines.
  20991. *
  20992. * @private
  20993. * @abstract
  20994. */
  20995. class Pipeline {
  20996. /**
  20997. * Constructs a new pipeline.
  20998. *
  20999. * @param {string} cacheKey - The pipeline's cache key.
  21000. */
  21001. constructor( cacheKey ) {
  21002. /**
  21003. * The pipeline's cache key.
  21004. *
  21005. * @type {string}
  21006. */
  21007. this.cacheKey = cacheKey;
  21008. /**
  21009. * How often the pipeline is currently in use.
  21010. *
  21011. * @type {number}
  21012. * @default 0
  21013. */
  21014. this.usedTimes = 0;
  21015. }
  21016. }
  21017. /**
  21018. * Class for representing render pipelines.
  21019. *
  21020. * @private
  21021. * @augments Pipeline
  21022. */
  21023. class RenderPipeline extends Pipeline {
  21024. /**
  21025. * Constructs a new render pipeline.
  21026. *
  21027. * @param {string} cacheKey - The pipeline's cache key.
  21028. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21029. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21030. */
  21031. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21032. super( cacheKey );
  21033. /**
  21034. * The pipeline's vertex shader.
  21035. *
  21036. * @type {ProgrammableStage}
  21037. */
  21038. this.vertexProgram = vertexProgram;
  21039. /**
  21040. * The pipeline's fragment shader.
  21041. *
  21042. * @type {ProgrammableStage}
  21043. */
  21044. this.fragmentProgram = fragmentProgram;
  21045. }
  21046. }
  21047. /**
  21048. * Class for representing compute pipelines.
  21049. *
  21050. * @private
  21051. * @augments Pipeline
  21052. */
  21053. class ComputePipeline extends Pipeline {
  21054. /**
  21055. * Constructs a new render pipeline.
  21056. *
  21057. * @param {string} cacheKey - The pipeline's cache key.
  21058. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21059. */
  21060. constructor( cacheKey, computeProgram ) {
  21061. super( cacheKey );
  21062. /**
  21063. * The pipeline's compute shader.
  21064. *
  21065. * @type {ProgrammableStage}
  21066. */
  21067. this.computeProgram = computeProgram;
  21068. /**
  21069. * This flag can be used for type testing.
  21070. *
  21071. * @type {boolean}
  21072. * @readonly
  21073. * @default true
  21074. */
  21075. this.isComputePipeline = true;
  21076. }
  21077. }
  21078. let _id$8 = 0;
  21079. /**
  21080. * Class for representing programmable stages which are vertex,
  21081. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21082. * they represent the programmable part of a pipeline.
  21083. *
  21084. * @private
  21085. */
  21086. class ProgrammableStage {
  21087. /**
  21088. * Constructs a new programmable stage.
  21089. *
  21090. * @param {string} code - The shader code.
  21091. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21092. * @param {string} name - The name of the shader.
  21093. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21094. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21095. */
  21096. constructor( code, stage, name, transforms = null, attributes = null ) {
  21097. /**
  21098. * The id of the programmable stage.
  21099. *
  21100. * @type {number}
  21101. */
  21102. this.id = _id$8 ++;
  21103. /**
  21104. * The shader code.
  21105. *
  21106. * @type {string}
  21107. */
  21108. this.code = code;
  21109. /**
  21110. * The type of stage.
  21111. *
  21112. * @type {string}
  21113. */
  21114. this.stage = stage;
  21115. /**
  21116. * The name of the stage.
  21117. * This is used for debugging purposes.
  21118. *
  21119. * @type {string}
  21120. */
  21121. this.name = name;
  21122. /**
  21123. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21124. *
  21125. * @type {?Array<Object>}
  21126. */
  21127. this.transforms = transforms;
  21128. /**
  21129. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21130. *
  21131. * @type {?Array<Object>}
  21132. */
  21133. this.attributes = attributes;
  21134. /**
  21135. * How often the programmable stage is currently in use.
  21136. *
  21137. * @type {number}
  21138. * @default 0
  21139. */
  21140. this.usedTimes = 0;
  21141. }
  21142. }
  21143. /**
  21144. * This renderer module manages the pipelines of the renderer.
  21145. *
  21146. * @private
  21147. * @augments DataMap
  21148. */
  21149. class Pipelines extends DataMap {
  21150. /**
  21151. * Constructs a new pipeline management component.
  21152. *
  21153. * @param {Backend} backend - The renderer's backend.
  21154. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21155. */
  21156. constructor( backend, nodes ) {
  21157. super();
  21158. /**
  21159. * The renderer's backend.
  21160. *
  21161. * @type {Backend}
  21162. */
  21163. this.backend = backend;
  21164. /**
  21165. * Renderer component for managing nodes related logic.
  21166. *
  21167. * @type {Nodes}
  21168. */
  21169. this.nodes = nodes;
  21170. /**
  21171. * A references to the bindings management component.
  21172. * This reference will be set inside the `Bindings`
  21173. * constructor.
  21174. *
  21175. * @type {?Bindings}
  21176. * @default null
  21177. */
  21178. this.bindings = null;
  21179. /**
  21180. * Internal cache for maintaining pipelines.
  21181. * The key of the map is a cache key, the value the pipeline.
  21182. *
  21183. * @type {Map<string,Pipeline>}
  21184. */
  21185. this.caches = new Map();
  21186. /**
  21187. * This dictionary maintains for each shader stage type (vertex,
  21188. * fragment and compute) the programmable stage objects which
  21189. * represent the actual shader code.
  21190. *
  21191. * @type {Object<string,Map<string, ProgrammableStage>>}
  21192. */
  21193. this.programs = {
  21194. vertex: new Map(),
  21195. fragment: new Map(),
  21196. compute: new Map()
  21197. };
  21198. }
  21199. /**
  21200. * Returns a compute pipeline for the given compute node.
  21201. *
  21202. * @param {Node} computeNode - The compute node.
  21203. * @param {Array<BindGroup>} bindings - The bindings.
  21204. * @return {ComputePipeline} The compute pipeline.
  21205. */
  21206. getForCompute( computeNode, bindings ) {
  21207. const { backend } = this;
  21208. const data = this.get( computeNode );
  21209. if ( this._needsComputeUpdate( computeNode ) ) {
  21210. const previousPipeline = data.pipeline;
  21211. if ( previousPipeline ) {
  21212. previousPipeline.usedTimes --;
  21213. previousPipeline.computeProgram.usedTimes --;
  21214. }
  21215. // get shader
  21216. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21217. // programmable stage
  21218. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21219. if ( stageCompute === undefined ) {
  21220. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21221. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21222. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21223. backend.createProgram( stageCompute );
  21224. }
  21225. // determine compute pipeline
  21226. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21227. let pipeline = this.caches.get( cacheKey );
  21228. if ( pipeline === undefined ) {
  21229. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21230. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21231. }
  21232. // keep track of all used times
  21233. pipeline.usedTimes ++;
  21234. stageCompute.usedTimes ++;
  21235. //
  21236. data.version = computeNode.version;
  21237. data.pipeline = pipeline;
  21238. }
  21239. return data.pipeline;
  21240. }
  21241. /**
  21242. * Returns a render pipeline for the given render object.
  21243. *
  21244. * @param {RenderObject} renderObject - The render object.
  21245. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21246. * @return {RenderPipeline} The render pipeline.
  21247. */
  21248. getForRender( renderObject, promises = null ) {
  21249. const { backend } = this;
  21250. const data = this.get( renderObject );
  21251. if ( this._needsRenderUpdate( renderObject ) ) {
  21252. const previousPipeline = data.pipeline;
  21253. if ( previousPipeline ) {
  21254. previousPipeline.usedTimes --;
  21255. previousPipeline.vertexProgram.usedTimes --;
  21256. previousPipeline.fragmentProgram.usedTimes --;
  21257. }
  21258. // get shader
  21259. const nodeBuilderState = renderObject.getNodeBuilderState();
  21260. const name = renderObject.material ? renderObject.material.name : '';
  21261. // programmable stages
  21262. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21263. if ( stageVertex === undefined ) {
  21264. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21265. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21266. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21267. backend.createProgram( stageVertex );
  21268. }
  21269. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21270. if ( stageFragment === undefined ) {
  21271. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21272. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21273. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21274. backend.createProgram( stageFragment );
  21275. }
  21276. // determine render pipeline
  21277. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21278. let pipeline = this.caches.get( cacheKey );
  21279. if ( pipeline === undefined ) {
  21280. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21281. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21282. } else {
  21283. renderObject.pipeline = pipeline;
  21284. }
  21285. // keep track of all used times
  21286. pipeline.usedTimes ++;
  21287. stageVertex.usedTimes ++;
  21288. stageFragment.usedTimes ++;
  21289. //
  21290. data.pipeline = pipeline;
  21291. }
  21292. return data.pipeline;
  21293. }
  21294. /**
  21295. * Deletes the pipeline for the given render object.
  21296. *
  21297. * @param {RenderObject} object - The render object.
  21298. * @return {?Object} The deleted dictionary.
  21299. */
  21300. delete( object ) {
  21301. const pipeline = this.get( object ).pipeline;
  21302. if ( pipeline ) {
  21303. // pipeline
  21304. pipeline.usedTimes --;
  21305. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21306. // programs
  21307. if ( pipeline.isComputePipeline ) {
  21308. pipeline.computeProgram.usedTimes --;
  21309. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21310. } else {
  21311. pipeline.fragmentProgram.usedTimes --;
  21312. pipeline.vertexProgram.usedTimes --;
  21313. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21314. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21315. }
  21316. }
  21317. return super.delete( object );
  21318. }
  21319. /**
  21320. * Frees internal resources.
  21321. */
  21322. dispose() {
  21323. super.dispose();
  21324. this.caches = new Map();
  21325. this.programs = {
  21326. vertex: new Map(),
  21327. fragment: new Map(),
  21328. compute: new Map()
  21329. };
  21330. }
  21331. /**
  21332. * Updates the pipeline for the given render object.
  21333. *
  21334. * @param {RenderObject} renderObject - The render object.
  21335. */
  21336. updateForRender( renderObject ) {
  21337. this.getForRender( renderObject );
  21338. }
  21339. /**
  21340. * Returns a compute pipeline for the given parameters.
  21341. *
  21342. * @private
  21343. * @param {Node} computeNode - The compute node.
  21344. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21345. * @param {string} cacheKey - The cache key.
  21346. * @param {Array<BindGroup>} bindings - The bindings.
  21347. * @return {ComputePipeline} The compute pipeline.
  21348. */
  21349. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21350. // check for existing pipeline
  21351. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21352. let pipeline = this.caches.get( cacheKey );
  21353. if ( pipeline === undefined ) {
  21354. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21355. this.caches.set( cacheKey, pipeline );
  21356. this.backend.createComputePipeline( pipeline, bindings );
  21357. }
  21358. return pipeline;
  21359. }
  21360. /**
  21361. * Returns a render pipeline for the given parameters.
  21362. *
  21363. * @private
  21364. * @param {RenderObject} renderObject - The render object.
  21365. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21366. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21367. * @param {string} cacheKey - The cache key.
  21368. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21369. * @return {ComputePipeline} The compute pipeline.
  21370. */
  21371. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21372. // check for existing pipeline
  21373. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21374. let pipeline = this.caches.get( cacheKey );
  21375. if ( pipeline === undefined ) {
  21376. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21377. this.caches.set( cacheKey, pipeline );
  21378. renderObject.pipeline = pipeline;
  21379. // The `promises` array is `null` by default and only set to an empty array when
  21380. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21381. // pending promises that resolve when the render pipelines are ready for rendering.
  21382. this.backend.createRenderPipeline( renderObject, promises );
  21383. }
  21384. return pipeline;
  21385. }
  21386. /**
  21387. * Computes a cache key representing a compute pipeline.
  21388. *
  21389. * @private
  21390. * @param {Node} computeNode - The compute node.
  21391. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21392. * @return {string} The cache key.
  21393. */
  21394. _getComputeCacheKey( computeNode, stageCompute ) {
  21395. return computeNode.id + ',' + stageCompute.id;
  21396. }
  21397. /**
  21398. * Computes a cache key representing a render pipeline.
  21399. *
  21400. * @private
  21401. * @param {RenderObject} renderObject - The render object.
  21402. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21403. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21404. * @return {string} The cache key.
  21405. */
  21406. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21407. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21408. }
  21409. /**
  21410. * Releases the given pipeline.
  21411. *
  21412. * @private
  21413. * @param {Pipeline} pipeline - The pipeline to release.
  21414. */
  21415. _releasePipeline( pipeline ) {
  21416. this.caches.delete( pipeline.cacheKey );
  21417. }
  21418. /**
  21419. * Releases the shader program.
  21420. *
  21421. * @private
  21422. * @param {Object} program - The shader program to release.
  21423. */
  21424. _releaseProgram( program ) {
  21425. const code = program.code;
  21426. const stage = program.stage;
  21427. this.programs[ stage ].delete( code );
  21428. }
  21429. /**
  21430. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21431. *
  21432. * @private
  21433. * @param {Node} computeNode - The compute node.
  21434. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21435. */
  21436. _needsComputeUpdate( computeNode ) {
  21437. const data = this.get( computeNode );
  21438. return data.pipeline === undefined || data.version !== computeNode.version;
  21439. }
  21440. /**
  21441. * Returns `true` if the render pipeline for the given render object requires an update.
  21442. *
  21443. * @private
  21444. * @param {RenderObject} renderObject - The render object.
  21445. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21446. */
  21447. _needsRenderUpdate( renderObject ) {
  21448. const data = this.get( renderObject );
  21449. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21450. }
  21451. }
  21452. /**
  21453. * This renderer module manages the bindings of the renderer.
  21454. *
  21455. * @private
  21456. * @augments DataMap
  21457. */
  21458. class Bindings extends DataMap {
  21459. /**
  21460. * Constructs a new bindings management component.
  21461. *
  21462. * @param {Backend} backend - The renderer's backend.
  21463. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21464. * @param {Textures} textures - Renderer component for managing textures.
  21465. * @param {Attributes} attributes - Renderer component for managing attributes.
  21466. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21467. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21468. */
  21469. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21470. super();
  21471. /**
  21472. * The renderer's backend.
  21473. *
  21474. * @type {Backend}
  21475. */
  21476. this.backend = backend;
  21477. /**
  21478. * Renderer component for managing textures.
  21479. *
  21480. * @type {Textures}
  21481. */
  21482. this.textures = textures;
  21483. /**
  21484. * Renderer component for managing pipelines.
  21485. *
  21486. * @type {Pipelines}
  21487. */
  21488. this.pipelines = pipelines;
  21489. /**
  21490. * Renderer component for managing attributes.
  21491. *
  21492. * @type {Attributes}
  21493. */
  21494. this.attributes = attributes;
  21495. /**
  21496. * Renderer component for managing nodes related logic.
  21497. *
  21498. * @type {Nodes}
  21499. */
  21500. this.nodes = nodes;
  21501. /**
  21502. * Renderer component for managing metrics and monitoring data.
  21503. *
  21504. * @type {Info}
  21505. */
  21506. this.info = info;
  21507. this.pipelines.bindings = this; // assign bindings to pipelines
  21508. }
  21509. /**
  21510. * Returns the bind groups for the given render object.
  21511. *
  21512. * @param {RenderObject} renderObject - The render object.
  21513. * @return {Array<BindGroup>} The bind groups.
  21514. */
  21515. getForRender( renderObject ) {
  21516. const bindings = renderObject.getBindings();
  21517. for ( const bindGroup of bindings ) {
  21518. const groupData = this.get( bindGroup );
  21519. if ( groupData.bindGroup === undefined ) {
  21520. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21521. this._init( bindGroup );
  21522. this.backend.createBindings( bindGroup, bindings, 0 );
  21523. groupData.bindGroup = bindGroup;
  21524. }
  21525. }
  21526. return bindings;
  21527. }
  21528. /**
  21529. * Returns the bind groups for the given compute node.
  21530. *
  21531. * @param {Node} computeNode - The compute node.
  21532. * @return {Array<BindGroup>} The bind groups.
  21533. */
  21534. getForCompute( computeNode ) {
  21535. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21536. for ( const bindGroup of bindings ) {
  21537. const groupData = this.get( bindGroup );
  21538. if ( groupData.bindGroup === undefined ) {
  21539. this._init( bindGroup );
  21540. this.backend.createBindings( bindGroup, bindings, 0 );
  21541. groupData.bindGroup = bindGroup;
  21542. }
  21543. }
  21544. return bindings;
  21545. }
  21546. /**
  21547. * Updates the bindings for the given compute node.
  21548. *
  21549. * @param {Node} computeNode - The compute node.
  21550. */
  21551. updateForCompute( computeNode ) {
  21552. this._updateBindings( this.getForCompute( computeNode ) );
  21553. }
  21554. /**
  21555. * Updates the bindings for the given render object.
  21556. *
  21557. * @param {RenderObject} renderObject - The render object.
  21558. */
  21559. updateForRender( renderObject ) {
  21560. this._updateBindings( this.getForRender( renderObject ) );
  21561. }
  21562. /**
  21563. * Deletes the bindings for the given compute node.
  21564. *
  21565. * @param {Node} computeNode - The compute node.
  21566. */
  21567. deleteForCompute( computeNode ) {
  21568. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21569. for ( const bindGroup of bindings ) {
  21570. this.delete( bindGroup );
  21571. }
  21572. }
  21573. /**
  21574. * Deletes the bindings for the given renderObject node.
  21575. *
  21576. * @param {RenderObject} renderObject - The renderObject.
  21577. */
  21578. deleteForRender( renderObject ) {
  21579. const bindings = renderObject.getBindings();
  21580. for ( const bindGroup of bindings ) {
  21581. this.delete( bindGroup );
  21582. }
  21583. }
  21584. /**
  21585. * Updates the given array of bindings.
  21586. *
  21587. * @param {Array<BindGroup>} bindings - The bind groups.
  21588. */
  21589. _updateBindings( bindings ) {
  21590. for ( const bindGroup of bindings ) {
  21591. this._update( bindGroup, bindings );
  21592. }
  21593. }
  21594. /**
  21595. * Initializes the given bind group.
  21596. *
  21597. * @param {BindGroup} bindGroup - The bind group to initialize.
  21598. */
  21599. _init( bindGroup ) {
  21600. for ( const binding of bindGroup.bindings ) {
  21601. if ( binding.isSampledTexture ) {
  21602. this.textures.updateTexture( binding.texture );
  21603. } else if ( binding.isSampler ) {
  21604. this.textures.updateSampler( binding.texture );
  21605. } else if ( binding.isStorageBuffer ) {
  21606. const attribute = binding.attribute;
  21607. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21608. this.attributes.update( attribute, attributeType );
  21609. }
  21610. }
  21611. }
  21612. /**
  21613. * Updates the given bind group.
  21614. *
  21615. * @param {BindGroup} bindGroup - The bind group to update.
  21616. * @param {Array<BindGroup>} bindings - The bind groups.
  21617. */
  21618. _update( bindGroup, bindings ) {
  21619. const { backend } = this;
  21620. let needsBindingsUpdate = false;
  21621. let cacheBindings = true;
  21622. let cacheIndex = 0;
  21623. let version = 0;
  21624. // iterate over all bindings and check if buffer updates or a new binding group is required
  21625. for ( const binding of bindGroup.bindings ) {
  21626. if ( binding.isNodeUniformsGroup ) {
  21627. const updated = this.nodes.updateGroup( binding );
  21628. // every uniforms group is a uniform buffer. So if no update is required,
  21629. // we move one with the next binding. Otherwise the next if block will update the group.
  21630. if ( updated === false ) continue;
  21631. }
  21632. if ( binding.isStorageBuffer ) {
  21633. const attribute = binding.attribute;
  21634. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21635. this.attributes.update( attribute, attributeType );
  21636. }
  21637. if ( binding.isUniformBuffer ) {
  21638. const updated = binding.update();
  21639. if ( updated ) {
  21640. backend.updateBinding( binding );
  21641. }
  21642. } else if ( binding.isSampledTexture ) {
  21643. const updated = binding.update();
  21644. // get the texture data after the update, to sync the texture reference from node
  21645. const texture = binding.texture;
  21646. const texturesTextureData = this.textures.get( texture );
  21647. if ( updated ) {
  21648. // version: update the texture data or create a new one
  21649. this.textures.updateTexture( texture );
  21650. // generation: update the bindings if a new texture has been created
  21651. if ( binding.generation !== texturesTextureData.generation ) {
  21652. binding.generation = texturesTextureData.generation;
  21653. needsBindingsUpdate = true;
  21654. cacheBindings = false;
  21655. }
  21656. }
  21657. const textureData = backend.get( texture );
  21658. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21659. cacheBindings = false;
  21660. } else {
  21661. cacheIndex = cacheIndex * 10 + texture.id;
  21662. version += texture.version;
  21663. }
  21664. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  21665. const textureData = this.get( texture );
  21666. if ( binding.store === true ) {
  21667. textureData.needsMipmap = true;
  21668. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21669. this.backend.generateMipmaps( texture );
  21670. textureData.needsMipmap = false;
  21671. }
  21672. }
  21673. } else if ( binding.isSampler ) {
  21674. const updated = binding.update();
  21675. if ( updated ) {
  21676. const samplerKey = this.textures.updateSampler( binding.texture );
  21677. if ( binding.samplerKey !== samplerKey ) {
  21678. binding.samplerKey = samplerKey;
  21679. needsBindingsUpdate = true;
  21680. cacheBindings = false;
  21681. }
  21682. }
  21683. }
  21684. }
  21685. if ( needsBindingsUpdate === true ) {
  21686. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21687. }
  21688. }
  21689. }
  21690. /**
  21691. * Default sorting function for opaque render items.
  21692. *
  21693. * @private
  21694. * @function
  21695. * @param {Object} a - The first render item.
  21696. * @param {Object} b - The second render item.
  21697. * @return {number} A numeric value which defines the sort order.
  21698. */
  21699. function painterSortStable( a, b ) {
  21700. if ( a.groupOrder !== b.groupOrder ) {
  21701. return a.groupOrder - b.groupOrder;
  21702. } else if ( a.renderOrder !== b.renderOrder ) {
  21703. return a.renderOrder - b.renderOrder;
  21704. } else if ( a.z !== b.z ) {
  21705. return a.z - b.z;
  21706. } else {
  21707. return a.id - b.id;
  21708. }
  21709. }
  21710. /**
  21711. * Default sorting function for transparent render items.
  21712. *
  21713. * @private
  21714. * @function
  21715. * @param {Object} a - The first render item.
  21716. * @param {Object} b - The second render item.
  21717. * @return {number} A numeric value which defines the sort order.
  21718. */
  21719. function reversePainterSortStable( a, b ) {
  21720. if ( a.groupOrder !== b.groupOrder ) {
  21721. return a.groupOrder - b.groupOrder;
  21722. } else if ( a.renderOrder !== b.renderOrder ) {
  21723. return a.renderOrder - b.renderOrder;
  21724. } else if ( a.z !== b.z ) {
  21725. return b.z - a.z;
  21726. } else {
  21727. return a.id - b.id;
  21728. }
  21729. }
  21730. /**
  21731. * Returns `true` if the given transparent material requires a double pass.
  21732. *
  21733. * @private
  21734. * @function
  21735. * @param {Material} material - The transparent material.
  21736. * @return {boolean} Whether the given material requires a double pass or not.
  21737. */
  21738. function needsDoublePass( material ) {
  21739. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21740. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21741. }
  21742. /**
  21743. * When the renderer analyzes the scene at the beginning of a render call,
  21744. * it stores 3D object for further processing in render lists. Depending on the
  21745. * properties of a 3D objects (like their transformation or material state), the
  21746. * objects are maintained in ordered lists for the actual rendering.
  21747. *
  21748. * Render lists are unique per scene and camera combination.
  21749. *
  21750. * @private
  21751. * @augments Pipeline
  21752. */
  21753. class RenderList {
  21754. /**
  21755. * Constructs a render list.
  21756. *
  21757. * @param {Lighting} lighting - The lighting management component.
  21758. * @param {Scene} scene - The scene.
  21759. * @param {Camera} camera - The camera the scene is rendered with.
  21760. */
  21761. constructor( lighting, scene, camera ) {
  21762. /**
  21763. * 3D objects are transformed into render items and stored in this array.
  21764. *
  21765. * @type {Array<Object>}
  21766. */
  21767. this.renderItems = [];
  21768. /**
  21769. * The current render items index.
  21770. *
  21771. * @type {number}
  21772. * @default 0
  21773. */
  21774. this.renderItemsIndex = 0;
  21775. /**
  21776. * A list with opaque render items.
  21777. *
  21778. * @type {Array<Object>}
  21779. */
  21780. this.opaque = [];
  21781. /**
  21782. * A list with transparent render items which require
  21783. * double pass rendering (e.g. transmissive objects).
  21784. *
  21785. * @type {Array<Object>}
  21786. */
  21787. this.transparentDoublePass = [];
  21788. /**
  21789. * A list with transparent render items.
  21790. *
  21791. * @type {Array<Object>}
  21792. */
  21793. this.transparent = [];
  21794. /**
  21795. * A list with transparent render bundle data.
  21796. *
  21797. * @type {Array<Object>}
  21798. */
  21799. this.bundles = [];
  21800. /**
  21801. * The render list's lights node. This node is later
  21802. * relevant for the actual analytical light nodes which
  21803. * compute the scene's lighting in the shader.
  21804. *
  21805. * @type {LightsNode}
  21806. */
  21807. this.lightsNode = lighting.getNode( scene, camera );
  21808. /**
  21809. * The scene's lights stored in an array. This array
  21810. * is used to setup the lights node.
  21811. *
  21812. * @type {Array<Light>}
  21813. */
  21814. this.lightsArray = [];
  21815. /**
  21816. * The scene.
  21817. *
  21818. * @type {Scene}
  21819. */
  21820. this.scene = scene;
  21821. /**
  21822. * The camera the scene is rendered with.
  21823. *
  21824. * @type {Camera}
  21825. */
  21826. this.camera = camera;
  21827. /**
  21828. * How many objects perform occlusion query tests.
  21829. *
  21830. * @type {number}
  21831. * @default 0
  21832. */
  21833. this.occlusionQueryCount = 0;
  21834. }
  21835. /**
  21836. * This method is called right at the beginning of a render call
  21837. * before the scene is analyzed. It prepares the internal data
  21838. * structures for the upcoming render lists generation.
  21839. *
  21840. * @return {RenderList} A reference to this render list.
  21841. */
  21842. begin() {
  21843. this.renderItemsIndex = 0;
  21844. this.opaque.length = 0;
  21845. this.transparentDoublePass.length = 0;
  21846. this.transparent.length = 0;
  21847. this.bundles.length = 0;
  21848. this.lightsArray.length = 0;
  21849. this.occlusionQueryCount = 0;
  21850. return this;
  21851. }
  21852. /**
  21853. * Returns a render item for the giving render item state. The state is defined
  21854. * by a series of object-related parameters.
  21855. *
  21856. * The method avoids object creation by holding render items and reusing them in
  21857. * subsequent render calls (just with different property values).
  21858. *
  21859. * @param {Object3D} object - The 3D object.
  21860. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21861. * @param {Material} material - The 3D object's material.
  21862. * @param {number} groupOrder - The current group order.
  21863. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21864. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21865. * @param {ClippingContext} clippingContext - The current clipping context.
  21866. * @return {Object} The render item.
  21867. */
  21868. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21869. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21870. if ( renderItem === undefined ) {
  21871. renderItem = {
  21872. id: object.id,
  21873. object: object,
  21874. geometry: geometry,
  21875. material: material,
  21876. groupOrder: groupOrder,
  21877. renderOrder: object.renderOrder,
  21878. z: z,
  21879. group: group,
  21880. clippingContext: clippingContext
  21881. };
  21882. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21883. } else {
  21884. renderItem.id = object.id;
  21885. renderItem.object = object;
  21886. renderItem.geometry = geometry;
  21887. renderItem.material = material;
  21888. renderItem.groupOrder = groupOrder;
  21889. renderItem.renderOrder = object.renderOrder;
  21890. renderItem.z = z;
  21891. renderItem.group = group;
  21892. renderItem.clippingContext = clippingContext;
  21893. }
  21894. this.renderItemsIndex ++;
  21895. return renderItem;
  21896. }
  21897. /**
  21898. * Pushes the given object as a render item to the internal render lists.
  21899. * The selected lists depend on the object properties.
  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. */
  21909. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21910. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21911. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21912. if ( material.transparent === true || material.transmission > 0 ) {
  21913. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21914. this.transparent.push( renderItem );
  21915. } else {
  21916. this.opaque.push( renderItem );
  21917. }
  21918. }
  21919. /**
  21920. * Inserts the given object as a render item at the start of the internal render lists.
  21921. * The selected lists depend on the object properties.
  21922. *
  21923. * @param {Object3D} object - The 3D object.
  21924. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21925. * @param {Material} material - The 3D object's material.
  21926. * @param {number} groupOrder - The current group order.
  21927. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21928. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21929. * @param {ClippingContext} clippingContext - The current clipping context.
  21930. */
  21931. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21932. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21933. if ( material.transparent === true || material.transmission > 0 ) {
  21934. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21935. this.transparent.unshift( renderItem );
  21936. } else {
  21937. this.opaque.unshift( renderItem );
  21938. }
  21939. }
  21940. /**
  21941. * Pushes render bundle group data into the render list.
  21942. *
  21943. * @param {Object} group - Bundle group data.
  21944. */
  21945. pushBundle( group ) {
  21946. this.bundles.push( group );
  21947. }
  21948. /**
  21949. * Pushes a light into the render list.
  21950. *
  21951. * @param {Light} light - The light.
  21952. */
  21953. pushLight( light ) {
  21954. this.lightsArray.push( light );
  21955. }
  21956. /**
  21957. * Sorts the internal render lists.
  21958. *
  21959. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21960. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21961. */
  21962. sort( customOpaqueSort, customTransparentSort ) {
  21963. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21964. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21965. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21966. }
  21967. /**
  21968. * This method performs finalizing tasks right after the render lists
  21969. * have been generated.
  21970. */
  21971. finish() {
  21972. // update lights
  21973. this.lightsNode.setLights( this.lightsArray );
  21974. // Clear references from inactive renderItems in the list
  21975. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21976. const renderItem = this.renderItems[ i ];
  21977. if ( renderItem.id === null ) break;
  21978. renderItem.id = null;
  21979. renderItem.object = null;
  21980. renderItem.geometry = null;
  21981. renderItem.material = null;
  21982. renderItem.groupOrder = null;
  21983. renderItem.renderOrder = null;
  21984. renderItem.z = null;
  21985. renderItem.group = null;
  21986. renderItem.clippingContext = null;
  21987. }
  21988. }
  21989. }
  21990. const _chainKeys$4 = [];
  21991. /**
  21992. * This renderer module manages the render lists which are unique
  21993. * per scene and camera combination.
  21994. *
  21995. * @private
  21996. */
  21997. class RenderLists {
  21998. /**
  21999. * Constructs a render lists management component.
  22000. *
  22001. * @param {Lighting} lighting - The lighting management component.
  22002. */
  22003. constructor( lighting ) {
  22004. /**
  22005. * The lighting management component.
  22006. *
  22007. * @type {Lighting}
  22008. */
  22009. this.lighting = lighting;
  22010. /**
  22011. * The internal chain map which holds the render lists.
  22012. *
  22013. * @type {ChainMap}
  22014. */
  22015. this.lists = new ChainMap();
  22016. }
  22017. /**
  22018. * Returns a render list for the given scene and camera.
  22019. *
  22020. * @param {Scene} scene - The scene.
  22021. * @param {Camera} camera - The camera.
  22022. * @return {RenderList} The render list.
  22023. */
  22024. get( scene, camera ) {
  22025. const lists = this.lists;
  22026. _chainKeys$4[ 0 ] = scene;
  22027. _chainKeys$4[ 1 ] = camera;
  22028. let list = lists.get( _chainKeys$4 );
  22029. if ( list === undefined ) {
  22030. list = new RenderList( this.lighting, scene, camera );
  22031. lists.set( _chainKeys$4, list );
  22032. }
  22033. _chainKeys$4.length = 0;
  22034. return list;
  22035. }
  22036. /**
  22037. * Frees all internal resources.
  22038. */
  22039. dispose() {
  22040. this.lists = new ChainMap();
  22041. }
  22042. }
  22043. let _id$7 = 0;
  22044. /**
  22045. * Any render or compute command is executed in a specific context that defines
  22046. * the state of the renderer and its backend. Typical examples for such context
  22047. * data are the current clear values or data from the active framebuffer. This
  22048. * module is used to represent these contexts as objects.
  22049. *
  22050. * @private
  22051. */
  22052. class RenderContext {
  22053. /**
  22054. * Constructs a new render context.
  22055. */
  22056. constructor() {
  22057. /**
  22058. * The context's ID.
  22059. *
  22060. * @type {number}
  22061. */
  22062. this.id = _id$7 ++;
  22063. /**
  22064. * Whether the current active framebuffer has a color attachment.
  22065. *
  22066. * @type {boolean}
  22067. * @default true
  22068. */
  22069. this.color = true;
  22070. /**
  22071. * Whether the color attachment should be cleared or not.
  22072. *
  22073. * @type {boolean}
  22074. * @default true
  22075. */
  22076. this.clearColor = true;
  22077. /**
  22078. * The clear color value.
  22079. *
  22080. * @type {Object}
  22081. * @default true
  22082. */
  22083. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22084. /**
  22085. * Whether the current active framebuffer has a depth attachment.
  22086. *
  22087. * @type {boolean}
  22088. * @default true
  22089. */
  22090. this.depth = true;
  22091. /**
  22092. * Whether the depth attachment should be cleared or not.
  22093. *
  22094. * @type {boolean}
  22095. * @default true
  22096. */
  22097. this.clearDepth = true;
  22098. /**
  22099. * The clear depth value.
  22100. *
  22101. * @type {number}
  22102. * @default 1
  22103. */
  22104. this.clearDepthValue = 1;
  22105. /**
  22106. * Whether the current active framebuffer has a stencil attachment.
  22107. *
  22108. * @type {boolean}
  22109. * @default false
  22110. */
  22111. this.stencil = false;
  22112. /**
  22113. * Whether the stencil attachment should be cleared or not.
  22114. *
  22115. * @type {boolean}
  22116. * @default true
  22117. */
  22118. this.clearStencil = true;
  22119. /**
  22120. * The clear stencil value.
  22121. *
  22122. * @type {number}
  22123. * @default 1
  22124. */
  22125. this.clearStencilValue = 1;
  22126. /**
  22127. * By default the viewport encloses the entire framebuffer If a smaller
  22128. * viewport is manually defined, this property is to `true` by the renderer.
  22129. *
  22130. * @type {boolean}
  22131. * @default false
  22132. */
  22133. this.viewport = false;
  22134. /**
  22135. * The viewport value. This value is in physical pixels meaning it incorporates
  22136. * the renderer's pixel ratio. The viewport property of render targets or
  22137. * the renderer is in logical pixels.
  22138. *
  22139. * @type {Vector4}
  22140. */
  22141. this.viewportValue = new Vector4();
  22142. /**
  22143. * When the scissor test is active and scissor rectangle smaller than the
  22144. * framebuffers dimensions, this property is to `true` by the renderer.
  22145. *
  22146. * @type {boolean}
  22147. * @default false
  22148. */
  22149. this.scissor = false;
  22150. /**
  22151. * The scissor rectangle.
  22152. *
  22153. * @type {Vector4}
  22154. */
  22155. this.scissorValue = new Vector4();
  22156. /**
  22157. * The active render target.
  22158. *
  22159. * @type {?RenderTarget}
  22160. * @default null
  22161. */
  22162. this.renderTarget = null;
  22163. /**
  22164. * The textures of the active render target.
  22165. * `null` when no render target is set.
  22166. *
  22167. * @type {?Array<Texture>}
  22168. * @default null
  22169. */
  22170. this.textures = null;
  22171. /**
  22172. * The depth texture of the active render target.
  22173. * `null` when no render target is set.
  22174. *
  22175. * @type {?DepthTexture}
  22176. * @default null
  22177. */
  22178. this.depthTexture = null;
  22179. /**
  22180. * The active cube face.
  22181. *
  22182. * @type {number}
  22183. * @default 0
  22184. */
  22185. this.activeCubeFace = 0;
  22186. /**
  22187. * The active mipmap level.
  22188. *
  22189. * @type {number}
  22190. * @default 0
  22191. */
  22192. this.activeMipmapLevel = 0;
  22193. /**
  22194. * The number of MSAA samples. This value is always `1` when
  22195. * MSAA isn't used.
  22196. *
  22197. * @type {number}
  22198. * @default 1
  22199. */
  22200. this.sampleCount = 1;
  22201. /**
  22202. * The active render target's width in physical pixels.
  22203. *
  22204. * @type {number}
  22205. * @default 0
  22206. */
  22207. this.width = 0;
  22208. /**
  22209. * The active render target's height in physical pixels.
  22210. *
  22211. * @type {number}
  22212. * @default 0
  22213. */
  22214. this.height = 0;
  22215. /**
  22216. * The occlusion query count.
  22217. *
  22218. * @type {number}
  22219. * @default 0
  22220. */
  22221. this.occlusionQueryCount = 0;
  22222. /**
  22223. * The current clipping context.
  22224. *
  22225. * @type {?ClippingContext}
  22226. * @default null
  22227. */
  22228. this.clippingContext = null;
  22229. /**
  22230. * This flag can be used for type testing.
  22231. *
  22232. * @type {boolean}
  22233. * @readonly
  22234. * @default true
  22235. */
  22236. this.isRenderContext = true;
  22237. }
  22238. /**
  22239. * Returns the cache key of this render context.
  22240. *
  22241. * @return {number} The cache key.
  22242. */
  22243. getCacheKey() {
  22244. return getCacheKey( this );
  22245. }
  22246. }
  22247. /**
  22248. * Computes a cache key for the given render context. This key
  22249. * should identify the render target state so it is possible to
  22250. * configure the correct attachments in the respective backend.
  22251. *
  22252. * @param {RenderContext} renderContext - The render context.
  22253. * @return {number} The cache key.
  22254. */
  22255. function getCacheKey( renderContext ) {
  22256. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22257. const values = [ activeCubeFace, activeMipmapLevel ];
  22258. for ( const texture of textures ) {
  22259. values.push( texture.id );
  22260. }
  22261. return hashArray( values );
  22262. }
  22263. const _chainKeys$3 = [];
  22264. const _defaultScene = /*@__PURE__*/ new Scene();
  22265. const _defaultCamera = /*@__PURE__*/ new Camera();
  22266. /**
  22267. * This module manages the render contexts of the renderer.
  22268. *
  22269. * @private
  22270. */
  22271. class RenderContexts {
  22272. /**
  22273. * Constructs a new render context management component.
  22274. */
  22275. constructor() {
  22276. /**
  22277. * A dictionary that manages render contexts in chain maps
  22278. * for each attachment state.
  22279. *
  22280. * @type {Object<string,ChainMap>}
  22281. */
  22282. this.chainMaps = {};
  22283. }
  22284. /**
  22285. * Returns a render context for the given scene, camera and render target.
  22286. *
  22287. * @param {Scene} scene - The scene.
  22288. * @param {Camera} camera - The camera that is used to render the scene.
  22289. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22290. * @return {RenderContext} The render context.
  22291. */
  22292. get( scene, camera, renderTarget = null ) {
  22293. _chainKeys$3[ 0 ] = scene;
  22294. _chainKeys$3[ 1 ] = camera;
  22295. let attachmentState;
  22296. if ( renderTarget === null ) {
  22297. attachmentState = 'default';
  22298. } else {
  22299. const format = renderTarget.texture.format;
  22300. const count = renderTarget.textures.length;
  22301. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22302. }
  22303. const chainMap = this._getChainMap( attachmentState );
  22304. let renderState = chainMap.get( _chainKeys$3 );
  22305. if ( renderState === undefined ) {
  22306. renderState = new RenderContext();
  22307. chainMap.set( _chainKeys$3, renderState );
  22308. }
  22309. _chainKeys$3.length = 0;
  22310. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22311. return renderState;
  22312. }
  22313. /**
  22314. * Returns a render context intended for clear operations.
  22315. *
  22316. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22317. * @return {RenderContext} The render context.
  22318. */
  22319. getForClear( renderTarget = null ) {
  22320. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22321. }
  22322. /**
  22323. * Returns a chain map for the given attachment state.
  22324. *
  22325. * @private
  22326. * @param {string} attachmentState - The attachment state.
  22327. * @return {ChainMap} The chain map.
  22328. */
  22329. _getChainMap( attachmentState ) {
  22330. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22331. }
  22332. /**
  22333. * Frees internal resources.
  22334. */
  22335. dispose() {
  22336. this.chainMaps = {};
  22337. }
  22338. }
  22339. const _size$3 = /*@__PURE__*/ new Vector3();
  22340. /**
  22341. * This module manages the textures of the renderer.
  22342. *
  22343. * @private
  22344. * @augments DataMap
  22345. */
  22346. class Textures extends DataMap {
  22347. /**
  22348. * Constructs a new texture management component.
  22349. *
  22350. * @param {Renderer} renderer - The renderer.
  22351. * @param {Backend} backend - The renderer's backend.
  22352. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22353. */
  22354. constructor( renderer, backend, info ) {
  22355. super();
  22356. /**
  22357. * The renderer.
  22358. *
  22359. * @type {Renderer}
  22360. */
  22361. this.renderer = renderer;
  22362. /**
  22363. * The backend.
  22364. *
  22365. * @type {Backend}
  22366. */
  22367. this.backend = backend;
  22368. /**
  22369. * Renderer component for managing metrics and monitoring data.
  22370. *
  22371. * @type {Info}
  22372. */
  22373. this.info = info;
  22374. }
  22375. /**
  22376. * Updates the given render target. Based on the given render target configuration,
  22377. * it updates the texture states representing the attachments of the framebuffer.
  22378. *
  22379. * @param {RenderTarget} renderTarget - The render target to update.
  22380. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22381. */
  22382. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22383. const renderTargetData = this.get( renderTarget );
  22384. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22385. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22386. const textures = renderTarget.textures;
  22387. const size = this.getSize( textures[ 0 ] );
  22388. const mipWidth = size.width >> activeMipmapLevel;
  22389. const mipHeight = size.height >> activeMipmapLevel;
  22390. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22391. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22392. let textureNeedsUpdate = false;
  22393. if ( depthTexture === undefined && useDepthTexture ) {
  22394. depthTexture = new DepthTexture();
  22395. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22396. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22397. depthTexture.image.width = mipWidth;
  22398. depthTexture.image.height = mipHeight;
  22399. depthTexture.image.depth = size.depth;
  22400. depthTexture.renderTarget = renderTarget;
  22401. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22402. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22403. }
  22404. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22405. textureNeedsUpdate = true;
  22406. if ( depthTexture ) {
  22407. depthTexture.needsUpdate = true;
  22408. depthTexture.image.width = mipWidth;
  22409. depthTexture.image.height = mipHeight;
  22410. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22411. }
  22412. }
  22413. renderTargetData.width = size.width;
  22414. renderTargetData.height = size.height;
  22415. renderTargetData.textures = textures;
  22416. renderTargetData.depthTexture = depthTexture || null;
  22417. renderTargetData.depth = renderTarget.depthBuffer;
  22418. renderTargetData.stencil = renderTarget.stencilBuffer;
  22419. renderTargetData.renderTarget = renderTarget;
  22420. if ( renderTargetData.sampleCount !== sampleCount ) {
  22421. textureNeedsUpdate = true;
  22422. if ( depthTexture ) {
  22423. depthTexture.needsUpdate = true;
  22424. }
  22425. renderTargetData.sampleCount = sampleCount;
  22426. }
  22427. //
  22428. const options = { sampleCount };
  22429. // XR render targets require no texture updates
  22430. if ( renderTarget.isXRRenderTarget !== true ) {
  22431. for ( let i = 0; i < textures.length; i ++ ) {
  22432. const texture = textures[ i ];
  22433. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22434. this.updateTexture( texture, options );
  22435. }
  22436. if ( depthTexture ) {
  22437. this.updateTexture( depthTexture, options );
  22438. }
  22439. }
  22440. // dispose handler
  22441. if ( renderTargetData.initialized !== true ) {
  22442. renderTargetData.initialized = true;
  22443. // dispose
  22444. const onDispose = () => {
  22445. renderTarget.removeEventListener( 'dispose', onDispose );
  22446. for ( let i = 0; i < textures.length; i ++ ) {
  22447. this._destroyTexture( textures[ i ] );
  22448. }
  22449. if ( depthTexture ) {
  22450. this._destroyTexture( depthTexture );
  22451. }
  22452. this.delete( renderTarget );
  22453. this.backend.delete( renderTarget );
  22454. };
  22455. renderTarget.addEventListener( 'dispose', onDispose );
  22456. }
  22457. }
  22458. /**
  22459. * Updates the given texture. Depending on the texture state, this method
  22460. * triggers the upload of texture data to the GPU memory. If the texture data are
  22461. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22462. *
  22463. * @param {Texture} texture - The texture to update.
  22464. * @param {Object} [options={}] - The options.
  22465. */
  22466. updateTexture( texture, options = {} ) {
  22467. const textureData = this.get( texture );
  22468. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22469. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22470. const backend = this.backend;
  22471. if ( isRenderTarget && textureData.initialized === true ) {
  22472. // it's an update
  22473. backend.destroyTexture( texture );
  22474. }
  22475. //
  22476. if ( texture.isFramebufferTexture ) {
  22477. const renderTarget = this.renderer.getRenderTarget();
  22478. if ( renderTarget ) {
  22479. texture.type = renderTarget.texture.type;
  22480. } else {
  22481. texture.type = UnsignedByteType;
  22482. }
  22483. }
  22484. //
  22485. const { width, height, depth } = this.getSize( texture );
  22486. options.width = width;
  22487. options.height = height;
  22488. options.depth = depth;
  22489. options.needsMipmaps = this.needsMipmaps( texture );
  22490. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22491. // TODO: Uniformly handle mipmap definitions
  22492. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22493. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22494. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22495. //
  22496. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22497. backend.createTexture( texture, options );
  22498. textureData.generation = texture.version;
  22499. } else {
  22500. if ( texture.version > 0 ) {
  22501. const image = texture.image;
  22502. if ( image === undefined ) {
  22503. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22504. } else if ( image.complete === false ) {
  22505. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22506. } else {
  22507. if ( texture.images ) {
  22508. const images = [];
  22509. for ( const image of texture.images ) {
  22510. images.push( image );
  22511. }
  22512. options.images = images;
  22513. } else {
  22514. options.image = image;
  22515. }
  22516. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22517. backend.createTexture( texture, options );
  22518. textureData.isDefaultTexture = false;
  22519. textureData.generation = texture.version;
  22520. }
  22521. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22522. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  22523. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  22524. backend.generateMipmaps( texture );
  22525. }
  22526. if ( texture.onUpdate ) texture.onUpdate( texture );
  22527. }
  22528. } else {
  22529. // async update
  22530. backend.createDefaultTexture( texture );
  22531. textureData.isDefaultTexture = true;
  22532. textureData.generation = texture.version;
  22533. }
  22534. }
  22535. // dispose handler
  22536. if ( textureData.initialized !== true ) {
  22537. textureData.initialized = true;
  22538. textureData.generation = texture.version;
  22539. //
  22540. this.info.memory.textures ++;
  22541. //
  22542. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22543. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22544. }
  22545. // dispose
  22546. const onDispose = () => {
  22547. texture.removeEventListener( 'dispose', onDispose );
  22548. this._destroyTexture( texture );
  22549. };
  22550. texture.addEventListener( 'dispose', onDispose );
  22551. }
  22552. //
  22553. textureData.version = texture.version;
  22554. }
  22555. /**
  22556. * Updates the sampler for the given texture. This method has no effect
  22557. * for the WebGL backend since it has no concept of samplers. Texture
  22558. * parameters are configured with the `texParameter()` command for each
  22559. * texture.
  22560. *
  22561. * In WebGPU, samplers are objects like textures and it's possible to share
  22562. * them when the texture parameters match.
  22563. *
  22564. * @param {Texture} texture - The texture to update the sampler for.
  22565. * @return {string} The current sampler key.
  22566. */
  22567. updateSampler( texture ) {
  22568. return this.backend.updateSampler( texture );
  22569. }
  22570. /**
  22571. * Computes the size of the given texture and writes the result
  22572. * into the target vector. This vector is also returned by the
  22573. * method.
  22574. *
  22575. * If no texture data are available for the compute yet, the method
  22576. * returns default size values.
  22577. *
  22578. * @param {Texture} texture - The texture to compute the size for.
  22579. * @param {Vector3} target - The target vector.
  22580. * @return {Vector3} The target vector.
  22581. */
  22582. getSize( texture, target = _size$3 ) {
  22583. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22584. if ( image ) {
  22585. if ( image.image !== undefined ) image = image.image;
  22586. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22587. target.width = image.videoWidth || 1;
  22588. target.height = image.videoHeight || 1;
  22589. target.depth = 1;
  22590. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22591. target.width = image.displayWidth || 1;
  22592. target.height = image.displayHeight || 1;
  22593. target.depth = 1;
  22594. } else {
  22595. target.width = image.width || 1;
  22596. target.height = image.height || 1;
  22597. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22598. }
  22599. } else {
  22600. target.width = target.height = target.depth = 1;
  22601. }
  22602. return target;
  22603. }
  22604. /**
  22605. * Computes the number of mipmap levels for the given texture.
  22606. *
  22607. * @param {Texture} texture - The texture.
  22608. * @param {number} width - The texture's width.
  22609. * @param {number} height - The texture's height.
  22610. * @return {number} The number of mipmap levels.
  22611. */
  22612. getMipLevels( texture, width, height ) {
  22613. let mipLevelCount;
  22614. if ( texture.mipmaps.length > 0 ) {
  22615. mipLevelCount = texture.mipmaps.length;
  22616. } else {
  22617. if ( texture.isCompressedTexture === true ) {
  22618. // it is not possible to compute mipmaps for compressed textures. So
  22619. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22620. // level of 1
  22621. mipLevelCount = 1;
  22622. } else {
  22623. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22624. }
  22625. }
  22626. return mipLevelCount;
  22627. }
  22628. /**
  22629. * Returns `true` if the given texture makes use of mipmapping.
  22630. *
  22631. * @param {Texture} texture - The texture.
  22632. * @return {boolean} Whether mipmaps are required or not.
  22633. */
  22634. needsMipmaps( texture ) {
  22635. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22636. }
  22637. /**
  22638. * Frees internal resource when the given texture isn't
  22639. * required anymore.
  22640. *
  22641. * @param {Texture} texture - The texture to destroy.
  22642. */
  22643. _destroyTexture( texture ) {
  22644. if ( this.has( texture ) === true ) {
  22645. // if a texture is not ready for use, it falls back to a default texture so it's possible
  22646. // to use it for rendering. If a texture in this state is disposed, it's important to
  22647. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  22648. // other textures.
  22649. const isDefaultTexture = this.get( texture ).isDefaultTexture;
  22650. this.backend.destroyTexture( texture, isDefaultTexture );
  22651. this.delete( texture );
  22652. this.info.memory.textures --;
  22653. }
  22654. }
  22655. }
  22656. /**
  22657. * A four-component version of {@link Color} which is internally
  22658. * used by the renderer to represents clear color with alpha as
  22659. * one object.
  22660. *
  22661. * @private
  22662. * @augments Color
  22663. */
  22664. class Color4 extends Color {
  22665. /**
  22666. * Constructs a new four-component color.
  22667. * You can also pass a single THREE.Color, hex or
  22668. * string argument to this constructor.
  22669. *
  22670. * @param {number|string} [r=1] - The red value.
  22671. * @param {number} [g=1] - The green value.
  22672. * @param {number} [b=1] - The blue value.
  22673. * @param {number} [a=1] - The alpha value.
  22674. */
  22675. constructor( r, g, b, a = 1 ) {
  22676. super( r, g, b );
  22677. this.a = a;
  22678. }
  22679. /**
  22680. * Overwrites the default to honor alpha.
  22681. * You can also pass a single THREE.Color, hex or
  22682. * string argument to this method.
  22683. *
  22684. * @param {number|string|Color} r - The red value.
  22685. * @param {number} [g] - The green value.
  22686. * @param {number} [b] - The blue value.
  22687. * @param {number} [a=1] - The alpha value.
  22688. * @return {Color4} A reference to this object.
  22689. */
  22690. set( r, g, b, a = 1 ) {
  22691. this.a = a;
  22692. return super.set( r, g, b );
  22693. }
  22694. /**
  22695. * Overwrites the default to honor alpha.
  22696. *
  22697. * @param {Color4} color - The color to copy.
  22698. * @return {Color4} A reference to this object.
  22699. */
  22700. copy( color ) {
  22701. if ( color.a !== undefined ) this.a = color.a;
  22702. return super.copy( color );
  22703. }
  22704. /**
  22705. * Overwrites the default to honor alpha.
  22706. *
  22707. * @return {Color4} The cloned color.
  22708. */
  22709. clone() {
  22710. return new this.constructor( this.r, this.g, this.b, this.a );
  22711. }
  22712. }
  22713. /**
  22714. * Special version of {@link PropertyNode} which is used for parameters.
  22715. *
  22716. * @augments PropertyNode
  22717. */
  22718. class ParameterNode extends PropertyNode {
  22719. static get type() {
  22720. return 'ParameterNode';
  22721. }
  22722. /**
  22723. * Constructs a new parameter node.
  22724. *
  22725. * @param {string} nodeType - The type of the node.
  22726. * @param {?string} [name=null] - The name of the parameter in the shader.
  22727. */
  22728. constructor( nodeType, name = null ) {
  22729. super( nodeType, name );
  22730. /**
  22731. * This flag can be used for type testing.
  22732. *
  22733. * @type {boolean}
  22734. * @readonly
  22735. * @default true
  22736. */
  22737. this.isParameterNode = true;
  22738. }
  22739. /**
  22740. * Gets the type of a member variable in the parameter node.
  22741. *
  22742. * @param {NodeBuilder} builder - The node builder.
  22743. * @param {string} name - The name of the member variable.
  22744. * @returns {string}
  22745. */
  22746. getMemberType( builder, name ) {
  22747. const type = this.getNodeType( builder );
  22748. const struct = builder.getStructTypeNode( type );
  22749. let memberType;
  22750. if ( struct !== null ) {
  22751. memberType = struct.getMemberType( builder, name );
  22752. } else {
  22753. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  22754. memberType = 'float';
  22755. }
  22756. return memberType;
  22757. }
  22758. getHash() {
  22759. return this.uuid;
  22760. }
  22761. generate() {
  22762. return this.name;
  22763. }
  22764. }
  22765. /**
  22766. * TSL function for creating a parameter node.
  22767. *
  22768. * @tsl
  22769. * @function
  22770. * @param {string} type - The type of the node.
  22771. * @param {?string} name - The name of the parameter in the shader.
  22772. * @returns {ParameterNode}
  22773. */
  22774. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22775. /**
  22776. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22777. * They are usually needed in cases like `If`, `Else`.
  22778. *
  22779. * @augments Node
  22780. */
  22781. class StackNode extends Node {
  22782. static get type() {
  22783. return 'StackNode';
  22784. }
  22785. /**
  22786. * Constructs a new stack node.
  22787. *
  22788. * @param {?StackNode} [parent=null] - The parent stack node.
  22789. */
  22790. constructor( parent = null ) {
  22791. super();
  22792. /**
  22793. * List of nodes.
  22794. *
  22795. * @type {Array<Node>}
  22796. */
  22797. this.nodes = [];
  22798. /**
  22799. * The output node.
  22800. *
  22801. * @type {?Node}
  22802. * @default null
  22803. */
  22804. this.outputNode = null;
  22805. /**
  22806. * The parent stack node.
  22807. *
  22808. * @type {?StackNode}
  22809. * @default null
  22810. */
  22811. this.parent = parent;
  22812. /**
  22813. * The current conditional node.
  22814. *
  22815. * @private
  22816. * @type {ConditionalNode}
  22817. * @default null
  22818. */
  22819. this._currentCond = null;
  22820. /**
  22821. * The expression node. Only
  22822. * relevant for Switch/Case.
  22823. *
  22824. * @private
  22825. * @type {Node}
  22826. * @default null
  22827. */
  22828. this._expressionNode = null;
  22829. /**
  22830. * This flag can be used for type testing.
  22831. *
  22832. * @type {boolean}
  22833. * @readonly
  22834. * @default true
  22835. */
  22836. this.isStackNode = true;
  22837. }
  22838. getNodeType( builder ) {
  22839. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22840. }
  22841. getMemberType( builder, name ) {
  22842. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22843. }
  22844. /**
  22845. * Adds a node to this stack.
  22846. *
  22847. * @param {Node} node - The node to add.
  22848. * @return {StackNode} A reference to this stack node.
  22849. */
  22850. add( node ) {
  22851. if ( node.isNode !== true ) {
  22852. error( 'TSL: Invalid node added to stack.' );
  22853. return this;
  22854. }
  22855. this.nodes.push( node );
  22856. return this;
  22857. }
  22858. /**
  22859. * Represent an `if` statement in TSL.
  22860. *
  22861. * @param {Node} boolNode - Represents the condition.
  22862. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22863. * @return {StackNode} A reference to this stack node.
  22864. */
  22865. If( boolNode, method ) {
  22866. const methodNode = new ShaderNode( method );
  22867. this._currentCond = select( boolNode, methodNode );
  22868. return this.add( this._currentCond );
  22869. }
  22870. /**
  22871. * Represent an `elseif` statement in TSL.
  22872. *
  22873. * @param {Node} boolNode - Represents the condition.
  22874. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22875. * @return {StackNode} A reference to this stack node.
  22876. */
  22877. ElseIf( boolNode, method ) {
  22878. const methodNode = new ShaderNode( method );
  22879. const ifNode = select( boolNode, methodNode );
  22880. this._currentCond.elseNode = ifNode;
  22881. this._currentCond = ifNode;
  22882. return this;
  22883. }
  22884. /**
  22885. * Represent an `else` statement in TSL.
  22886. *
  22887. * @param {Function} method - TSL code which is executed in the `else` case.
  22888. * @return {StackNode} A reference to this stack node.
  22889. */
  22890. Else( method ) {
  22891. this._currentCond.elseNode = new ShaderNode( method );
  22892. return this;
  22893. }
  22894. /**
  22895. * Represents a `switch` statement in TSL.
  22896. *
  22897. * @param {any} expression - Represents the expression.
  22898. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22899. * @return {StackNode} A reference to this stack node.
  22900. */
  22901. Switch( expression ) {
  22902. this._expressionNode = nodeObject( expression );
  22903. return this;
  22904. }
  22905. /**
  22906. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22907. * The last parameter must be the callback method that should be executed in the `true` case.
  22908. *
  22909. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22910. * @return {StackNode} A reference to this stack node.
  22911. */
  22912. Case( ...params ) {
  22913. const caseNodes = [];
  22914. // extract case nodes from the parameter list
  22915. if ( params.length >= 2 ) {
  22916. for ( let i = 0; i < params.length - 1; i ++ ) {
  22917. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22918. }
  22919. } else {
  22920. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22921. }
  22922. // extract method
  22923. const method = params[ params.length - 1 ];
  22924. const methodNode = new ShaderNode( method );
  22925. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22926. let caseNode = caseNodes[ 0 ];
  22927. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22928. caseNode = caseNode.or( caseNodes[ i ] );
  22929. }
  22930. // build condition
  22931. const condNode = select( caseNode, methodNode );
  22932. if ( this._currentCond === null ) {
  22933. this._currentCond = condNode;
  22934. return this.add( this._currentCond );
  22935. } else {
  22936. this._currentCond.elseNode = condNode;
  22937. this._currentCond = condNode;
  22938. return this;
  22939. }
  22940. }
  22941. /**
  22942. * Represents the default code block of a Switch/Case statement.
  22943. *
  22944. * @param {Function} method - TSL code which is executed in the `else` case.
  22945. * @return {StackNode} A reference to this stack node.
  22946. */
  22947. Default( method ) {
  22948. this.Else( method );
  22949. return this;
  22950. }
  22951. setup( builder ) {
  22952. const nodeProperties = builder.getNodeProperties( this );
  22953. let index = 0;
  22954. for ( const childNode of this.getChildren() ) {
  22955. if ( childNode.isVarNode && childNode.intent === true ) {
  22956. if ( childNode.isAssign( builder ) !== true ) {
  22957. continue;
  22958. }
  22959. }
  22960. nodeProperties[ 'node' + index ++ ] = childNode;
  22961. }
  22962. // return a outputNode if exists or null
  22963. return nodeProperties.outputNode || null;
  22964. }
  22965. get hasOutput() {
  22966. return this.outputNode && this.outputNode.isNode;
  22967. }
  22968. build( builder, ...params ) {
  22969. const previousBuildStack = builder.currentStack;
  22970. const previousStack = getCurrentStack();
  22971. setCurrentStack( this );
  22972. builder.currentStack = this;
  22973. const buildStage = builder.buildStage;
  22974. for ( const node of this.nodes ) {
  22975. if ( node.isVarNode && node.intent === true ) {
  22976. if ( node.isAssign( builder ) !== true ) {
  22977. continue;
  22978. }
  22979. }
  22980. if ( buildStage === 'setup' ) {
  22981. node.build( builder );
  22982. } else if ( buildStage === 'analyze' ) {
  22983. node.build( builder, this );
  22984. } else if ( buildStage === 'generate' ) {
  22985. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22986. const parents = stages && stages[ builder.shaderStage ];
  22987. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22988. continue; // skip var nodes that are only used in .toVarying()
  22989. }
  22990. node.build( builder, 'void' );
  22991. }
  22992. }
  22993. //
  22994. let result;
  22995. if ( this.hasOutput ) {
  22996. result = this.outputNode.build( builder, ...params );
  22997. } else {
  22998. result = super.build( builder, ...params );
  22999. }
  23000. setCurrentStack( previousStack );
  23001. builder.currentStack = previousBuildStack;
  23002. return result;
  23003. }
  23004. }
  23005. /**
  23006. * TSL function for creating a stack node.
  23007. *
  23008. * @tsl
  23009. * @function
  23010. * @param {?StackNode} [parent=null] - The parent stack node.
  23011. * @returns {StackNode}
  23012. */
  23013. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23014. /**
  23015. * Generates a layout for struct members.
  23016. * This function takes an object representing struct members and returns an array of member layouts.
  23017. * Each member layout includes the member's name, type, and whether it is atomic.
  23018. *
  23019. * @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.
  23020. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23021. */
  23022. function getMembersLayout( members ) {
  23023. return Object.entries( members ).map( ( [ name, value ] ) => {
  23024. if ( typeof value === 'string' ) {
  23025. return { name, type: value, atomic: false };
  23026. }
  23027. return { name, type: value.type, atomic: value.atomic || false };
  23028. } );
  23029. }
  23030. /**
  23031. * Represents a struct type node in the node-based system.
  23032. * This class is used to define and manage the layout and types of struct members.
  23033. * It extends the base Node class and provides methods to get the length of the struct,
  23034. * retrieve member types, and generate the struct type for a builder.
  23035. *
  23036. * @augments Node
  23037. */
  23038. class StructTypeNode extends Node {
  23039. static get type() {
  23040. return 'StructTypeNode';
  23041. }
  23042. /**
  23043. * Creates an instance of StructTypeNode.
  23044. *
  23045. * @param {Object} membersLayout - The layout of the members for the struct.
  23046. * @param {?string} [name=null] - The optional name of the struct.
  23047. */
  23048. constructor( membersLayout, name = null ) {
  23049. super( 'struct' );
  23050. /**
  23051. * The layout of the members for the struct
  23052. *
  23053. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23054. */
  23055. this.membersLayout = getMembersLayout( membersLayout );
  23056. /**
  23057. * The name of the struct.
  23058. *
  23059. * @type {?string}
  23060. * @default null
  23061. */
  23062. this.name = name;
  23063. /**
  23064. * This flag can be used for type testing.
  23065. *
  23066. * @type {boolean}
  23067. * @readonly
  23068. * @default true
  23069. */
  23070. this.isStructLayoutNode = true;
  23071. }
  23072. /**
  23073. * Returns the length of the struct.
  23074. * The length is calculated by summing the lengths of the struct's members.
  23075. *
  23076. * @returns {number} The length of the struct.
  23077. */
  23078. getLength() {
  23079. const GPU_CHUNK_BYTES = 8;
  23080. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23081. let offset = 0; // global buffer offset in bytes
  23082. for ( const member of this.membersLayout ) {
  23083. const type = member.type;
  23084. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23085. const boundary = getByteBoundaryFromType( type );
  23086. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23087. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23088. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23089. offset += chunkPadding;
  23090. // Check for chunk overflow
  23091. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23092. // Add padding to the end of the chunk
  23093. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23094. }
  23095. offset += itemSize;
  23096. }
  23097. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23098. }
  23099. getMemberType( builder, name ) {
  23100. const member = this.membersLayout.find( m => m.name === name );
  23101. return member ? member.type : 'void';
  23102. }
  23103. getNodeType( builder ) {
  23104. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23105. return structType.name;
  23106. }
  23107. setup( builder ) {
  23108. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23109. builder.addInclude( this );
  23110. }
  23111. generate( builder ) {
  23112. return this.getNodeType( builder );
  23113. }
  23114. }
  23115. /**
  23116. * StructNode allows to create custom structures with multiple members.
  23117. * This can also be used to define structures in attribute and uniform data.
  23118. *
  23119. * ```js
  23120. * // Define a custom struct
  23121. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23122. *
  23123. * // Create a new instance of the struct
  23124. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23125. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23126. *
  23127. * // Access the struct members
  23128. * const min = bb.get( 'min' );
  23129. *
  23130. * // Assign a new value to a member
  23131. * min.assign( vec3() );
  23132. * ```
  23133. * @augments Node
  23134. */
  23135. class StructNode extends Node {
  23136. static get type() {
  23137. return 'StructNode';
  23138. }
  23139. constructor( structTypeNode, values ) {
  23140. super( 'vec3' );
  23141. this.structTypeNode = structTypeNode;
  23142. this.values = values;
  23143. this.isStructNode = true;
  23144. }
  23145. getNodeType( builder ) {
  23146. return this.structTypeNode.getNodeType( builder );
  23147. }
  23148. getMemberType( builder, name ) {
  23149. return this.structTypeNode.getMemberType( builder, name );
  23150. }
  23151. generate( builder ) {
  23152. const nodeVar = builder.getVarFromNode( this );
  23153. const structType = nodeVar.type;
  23154. const propertyName = builder.getPropertyName( nodeVar );
  23155. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23156. return nodeVar.name;
  23157. }
  23158. }
  23159. /**
  23160. * TSL function for creating a struct node.
  23161. *
  23162. * @tsl
  23163. * @function
  23164. * @param {Object} membersLayout - The layout of the struct members.
  23165. * @param {?string} [name=null] - The name of the struct.
  23166. * @returns {Function} The struct function.
  23167. */
  23168. const struct = ( membersLayout, name = null ) => {
  23169. const structLayout = new StructTypeNode( membersLayout, name );
  23170. const struct = ( ...params ) => {
  23171. let values = null;
  23172. if ( params.length > 0 ) {
  23173. if ( params[ 0 ].isNode ) {
  23174. values = {};
  23175. const names = Object.keys( membersLayout );
  23176. for ( let i = 0; i < params.length; i ++ ) {
  23177. values[ names[ i ] ] = params[ i ];
  23178. }
  23179. } else {
  23180. values = params[ 0 ];
  23181. }
  23182. }
  23183. return nodeObject( new StructNode( structLayout, values ) );
  23184. };
  23185. struct.layout = structLayout;
  23186. struct.isStruct = true;
  23187. return struct;
  23188. };
  23189. /**
  23190. * This node can be used to define multiple outputs in a shader programs.
  23191. *
  23192. * @augments Node
  23193. */
  23194. class OutputStructNode extends Node {
  23195. static get type() {
  23196. return 'OutputStructNode';
  23197. }
  23198. /**
  23199. * Constructs a new output struct node. The constructor can be invoked with an
  23200. * arbitrary number of nodes representing the members.
  23201. *
  23202. * @param {...Node} members - A parameter list of nodes.
  23203. */
  23204. constructor( ...members ) {
  23205. super();
  23206. /**
  23207. * An array of nodes which defines the output.
  23208. *
  23209. * @type {Array<Node>}
  23210. */
  23211. this.members = members;
  23212. /**
  23213. * This flag can be used for type testing.
  23214. *
  23215. * @type {boolean}
  23216. * @readonly
  23217. * @default true
  23218. */
  23219. this.isOutputStructNode = true;
  23220. }
  23221. getNodeType( builder ) {
  23222. const properties = builder.getNodeProperties( this );
  23223. if ( properties.membersLayout === undefined ) {
  23224. const members = this.members;
  23225. const membersLayout = [];
  23226. for ( let i = 0; i < members.length; i ++ ) {
  23227. const name = 'm' + i;
  23228. const type = members[ i ].getNodeType( builder );
  23229. membersLayout.push( { name, type, index: i } );
  23230. }
  23231. properties.membersLayout = membersLayout;
  23232. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23233. }
  23234. return properties.structType.name;
  23235. }
  23236. generate( builder ) {
  23237. const propertyName = builder.getOutputStructName();
  23238. const members = this.members;
  23239. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23240. for ( let i = 0; i < members.length; i ++ ) {
  23241. const snippet = members[ i ].build( builder );
  23242. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23243. }
  23244. return propertyName;
  23245. }
  23246. }
  23247. /**
  23248. * TSL function for creating an output struct node.
  23249. *
  23250. * @tsl
  23251. * @function
  23252. * @param {...Node} members - A parameter list of nodes.
  23253. * @returns {OutputStructNode}
  23254. */
  23255. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23256. /**
  23257. * Returns the MRT texture index for the given name.
  23258. *
  23259. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23260. * @param {string} name - The name of the MRT texture which index is requested.
  23261. * @return {number} The texture index.
  23262. */
  23263. function getTextureIndex( textures, name ) {
  23264. for ( let i = 0; i < textures.length; i ++ ) {
  23265. if ( textures[ i ].name === name ) {
  23266. return i;
  23267. }
  23268. }
  23269. return -1;
  23270. }
  23271. /**
  23272. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23273. * post-processing is shown below:
  23274. * ```js
  23275. * const mrtNode = mrt( {
  23276. * output: output,
  23277. * normal: normalView
  23278. * } ) );
  23279. * ```
  23280. * The MRT output is defined as a dictionary.
  23281. *
  23282. * @augments OutputStructNode
  23283. */
  23284. class MRTNode extends OutputStructNode {
  23285. static get type() {
  23286. return 'MRTNode';
  23287. }
  23288. /**
  23289. * Constructs a new output struct node.
  23290. *
  23291. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23292. */
  23293. constructor( outputNodes ) {
  23294. super();
  23295. /**
  23296. * A dictionary representing the MRT outputs. The key
  23297. * is the name of the output, the value the node which produces
  23298. * the output result.
  23299. *
  23300. * @type {Object<string, Node>}
  23301. */
  23302. this.outputNodes = outputNodes;
  23303. /**
  23304. * This flag can be used for type testing.
  23305. *
  23306. * @type {boolean}
  23307. * @readonly
  23308. * @default true
  23309. */
  23310. this.isMRTNode = true;
  23311. }
  23312. /**
  23313. * Returns `true` if the MRT node has an output with the given name.
  23314. *
  23315. * @param {string} name - The name of the output.
  23316. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23317. */
  23318. has( name ) {
  23319. return this.outputNodes[ name ] !== undefined;
  23320. }
  23321. /**
  23322. * Returns the output node for the given name.
  23323. *
  23324. * @param {string} name - The name of the output.
  23325. * @return {Node} The output node.
  23326. */
  23327. get( name ) {
  23328. return this.outputNodes[ name ];
  23329. }
  23330. /**
  23331. * Merges the outputs of the given MRT node with the outputs of this node.
  23332. *
  23333. * @param {MRTNode} mrtNode - The MRT to merge.
  23334. * @return {MRTNode} A new MRT node with merged outputs..
  23335. */
  23336. merge( mrtNode ) {
  23337. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23338. return mrt( outputs );
  23339. }
  23340. setup( builder ) {
  23341. const outputNodes = this.outputNodes;
  23342. const mrt = builder.renderer.getRenderTarget();
  23343. const members = [];
  23344. const textures = mrt.textures;
  23345. for ( const name in outputNodes ) {
  23346. const index = getTextureIndex( textures, name );
  23347. members[ index ] = vec4( outputNodes[ name ] );
  23348. }
  23349. this.members = members;
  23350. return super.setup( builder );
  23351. }
  23352. }
  23353. /**
  23354. * TSL function for creating a MRT node.
  23355. *
  23356. * @tsl
  23357. * @function
  23358. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23359. * @returns {MRTNode}
  23360. */
  23361. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23362. /**
  23363. * This node represents an operation that reinterprets the bit representation of a value
  23364. * in one type as a value in another type.
  23365. *
  23366. * @augments TempNode
  23367. */
  23368. class BitcastNode extends TempNode {
  23369. static get type() {
  23370. return 'BitcastNode';
  23371. }
  23372. /**
  23373. * Constructs a new bitcast node.
  23374. *
  23375. * @param {Node} valueNode - The value to convert.
  23376. * @param {string} conversionType - The type to convert to.
  23377. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23378. */
  23379. constructor( valueNode, conversionType, inputType = null ) {
  23380. super();
  23381. /**
  23382. * The data to bitcast to a new type.
  23383. *
  23384. * @type {Node}
  23385. */
  23386. this.valueNode = valueNode;
  23387. /**
  23388. * The type the value will be converted to.
  23389. *
  23390. * @type {string}
  23391. */
  23392. this.conversionType = conversionType;
  23393. /**
  23394. * The expected input data type of the bitcast operation.
  23395. *
  23396. *
  23397. * @type {string}
  23398. * @default null
  23399. */
  23400. this.inputType = inputType;
  23401. /**
  23402. * This flag can be used for type testing.
  23403. *
  23404. * @type {boolean}
  23405. * @readonly
  23406. * @default true
  23407. */
  23408. this.isBitcastNode = true;
  23409. }
  23410. getNodeType( builder ) {
  23411. // GLSL aliasing
  23412. if ( this.inputType !== null ) {
  23413. const valueType = this.valueNode.getNodeType( builder );
  23414. const valueLength = builder.getTypeLength( valueType );
  23415. return builder.getTypeFromLength( valueLength, this.conversionType );
  23416. }
  23417. return this.conversionType;
  23418. }
  23419. generate( builder ) {
  23420. const type = this.getNodeType( builder );
  23421. let inputType = '';
  23422. if ( this.inputType !== null ) {
  23423. const valueType = this.valueNode.getNodeType( builder );
  23424. const valueTypeLength = builder.getTypeLength( valueType );
  23425. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23426. } else {
  23427. inputType = this.valueNode.getNodeType( builder );
  23428. }
  23429. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23430. }
  23431. }
  23432. /**
  23433. * Reinterpret the bit representation of a value in one type as a value in another type.
  23434. *
  23435. * @tsl
  23436. * @function
  23437. * @param {Node | number} x - The parameter.
  23438. * @param {string} y - The new type.
  23439. * @returns {Node}
  23440. */
  23441. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23442. /**
  23443. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23444. *
  23445. * @tsl
  23446. * @function
  23447. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23448. * @returns {BitcastNode}
  23449. */
  23450. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23451. /**
  23452. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23453. *
  23454. * @tsl
  23455. * @function
  23456. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23457. * @returns {BitcastNode}
  23458. */
  23459. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23460. /**
  23461. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23462. *
  23463. * @tsl
  23464. * @function
  23465. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23466. * @returns {BitcastNode}
  23467. */
  23468. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23469. /**
  23470. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23471. *
  23472. * @tsl
  23473. * @function
  23474. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23475. * @returns {BitcastNode}
  23476. */
  23477. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23478. /**
  23479. * Generates a hash value in the range `[0, 1]` from the given seed.
  23480. *
  23481. * @tsl
  23482. * @function
  23483. * @param {Node<float>} seed - The seed.
  23484. * @return {Node<float>} The hash value.
  23485. */
  23486. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23487. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23488. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23489. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23490. const result = word.shiftRight( 22 ).bitXor( word );
  23491. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23492. } );
  23493. /**
  23494. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23495. * The corners are mapped to `0` and the center to `1`.
  23496. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23497. *
  23498. * @tsl
  23499. * @function
  23500. * @param {Node<float>} x - The value to remap.
  23501. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23502. * @return {Node<float>} The remapped value.
  23503. */
  23504. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23505. /**
  23506. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23507. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23508. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23509. *
  23510. * @tsl
  23511. * @function
  23512. * @param {Node<float>} x - The value to remap.
  23513. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23514. * @return {Node<float>} The remapped value.
  23515. */
  23516. 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 ) );
  23517. /**
  23518. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23519. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23520. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23521. *
  23522. * @tsl
  23523. * @function
  23524. * @param {Node<float>} x - The value to remap.
  23525. * @param {Node<float>} a - First control parameter.
  23526. * @param {Node<float>} b - Second control parameter.
  23527. * @return {Node<float>} The remapped value.
  23528. */
  23529. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23530. /**
  23531. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23532. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23533. *
  23534. * @tsl
  23535. * @function
  23536. * @param {Node<float>} x - The value to compute the sin for.
  23537. * @param {Node<float>} k - Controls the amount of bounces.
  23538. * @return {Node<float>} The result value.
  23539. */
  23540. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23541. // https://github.com/cabbibo/glsl-tri-noise-3d
  23542. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23543. return x.fract().sub( .5 ).abs();
  23544. } ).setLayout( {
  23545. name: 'tri',
  23546. type: 'float',
  23547. inputs: [
  23548. { name: 'x', type: 'float' }
  23549. ]
  23550. } );
  23551. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23552. 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. ) ) ) ) );
  23553. } ).setLayout( {
  23554. name: 'tri3',
  23555. type: 'vec3',
  23556. inputs: [
  23557. { name: 'p', type: 'vec3' }
  23558. ]
  23559. } );
  23560. /**
  23561. * Generates a noise value from the given position, speed and time parameters.
  23562. *
  23563. * @tsl
  23564. * @function
  23565. * @param {Node<vec3>} position - The position.
  23566. * @param {Node<float>} speed - The speed.
  23567. * @param {Node<float>} time - The time.
  23568. * @return {Node<float>} The generated noise.
  23569. */
  23570. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23571. const p = vec3( position ).toVar();
  23572. const z = float( 1.4 ).toVar();
  23573. const rz = float( 0.0 ).toVar();
  23574. const bp = vec3( p ).toVar();
  23575. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23576. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23577. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23578. bp.mulAssign( 1.8 );
  23579. z.mulAssign( 1.5 );
  23580. p.mulAssign( 1.2 );
  23581. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23582. rz.addAssign( t.div( z ) );
  23583. bp.addAssign( 0.14 );
  23584. } );
  23585. return rz;
  23586. } ).setLayout( {
  23587. name: 'triNoise3D',
  23588. type: 'float',
  23589. inputs: [
  23590. { name: 'position', type: 'vec3' },
  23591. { name: 'speed', type: 'float' },
  23592. { name: 'time', type: 'float' }
  23593. ]
  23594. } );
  23595. /**
  23596. * This class allows to define multiple overloaded versions
  23597. * of the same function. Depending on the parameters of the function
  23598. * call, the node picks the best-fit overloaded version.
  23599. *
  23600. * @augments Node
  23601. */
  23602. class FunctionOverloadingNode extends Node {
  23603. static get type() {
  23604. return 'FunctionOverloadingNode';
  23605. }
  23606. /**
  23607. * Constructs a new function overloading node.
  23608. *
  23609. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23610. * @param {...Node} parametersNodes - A list of parameter nodes.
  23611. */
  23612. constructor( functionNodes = [], ...parametersNodes ) {
  23613. super();
  23614. /**
  23615. * Array of `Fn` function definitions.
  23616. *
  23617. * @type {Array<Function>}
  23618. */
  23619. this.functionNodes = functionNodes;
  23620. /**
  23621. * A list of parameter nodes.
  23622. *
  23623. * @type {Array<Node>}
  23624. */
  23625. this.parametersNodes = parametersNodes;
  23626. /**
  23627. * The selected overloaded function call.
  23628. *
  23629. * @private
  23630. * @type {ShaderCallNodeInternal}
  23631. */
  23632. this._candidateFnCall = null;
  23633. /**
  23634. * This node is marked as global.
  23635. *
  23636. * @type {boolean}
  23637. * @default true
  23638. */
  23639. this.global = true;
  23640. }
  23641. /**
  23642. * This method is overwritten since the node type is inferred from
  23643. * the function's return type.
  23644. *
  23645. * @param {NodeBuilder} builder - The current node builder.
  23646. * @return {string} The node type.
  23647. */
  23648. getNodeType() {
  23649. return this.functionNodes[ 0 ].shaderNode.layout.type;
  23650. }
  23651. setup( builder ) {
  23652. const params = this.parametersNodes;
  23653. let candidateFnCall = this._candidateFnCall;
  23654. if ( candidateFnCall === null ) {
  23655. let candidateFn = null;
  23656. let candidateScore = -1;
  23657. for ( const functionNode of this.functionNodes ) {
  23658. const shaderNode = functionNode.shaderNode;
  23659. const layout = shaderNode.layout;
  23660. if ( layout === null ) {
  23661. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23662. }
  23663. const inputs = layout.inputs;
  23664. if ( params.length === inputs.length ) {
  23665. let score = 0;
  23666. for ( let i = 0; i < params.length; i ++ ) {
  23667. const param = params[ i ];
  23668. const input = inputs[ i ];
  23669. if ( param.getNodeType( builder ) === input.type ) {
  23670. score ++;
  23671. } else {
  23672. score = 0;
  23673. }
  23674. }
  23675. if ( score > candidateScore ) {
  23676. candidateFn = functionNode;
  23677. candidateScore = score;
  23678. }
  23679. }
  23680. }
  23681. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  23682. }
  23683. return candidateFnCall;
  23684. }
  23685. }
  23686. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23687. /**
  23688. * TSL function for creating a function overloading node.
  23689. *
  23690. * @tsl
  23691. * @function
  23692. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23693. * @returns {FunctionOverloadingNode}
  23694. */
  23695. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23696. /**
  23697. * Represents the elapsed time in seconds.
  23698. *
  23699. * @tsl
  23700. * @type {UniformNode<float>}
  23701. */
  23702. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23703. /**
  23704. * Represents the delta time in seconds.
  23705. *
  23706. * @tsl
  23707. * @type {UniformNode<float>}
  23708. */
  23709. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23710. /**
  23711. * Represents the current frame ID.
  23712. *
  23713. * @tsl
  23714. * @type {UniformNode<uint>}
  23715. */
  23716. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23717. /**
  23718. * Generates a sine wave oscillation based on a timer.
  23719. *
  23720. * @tsl
  23721. * @function
  23722. * @param {Node<float>} t - The timer to generate the oscillation with.
  23723. * @return {Node<float>} The oscillation node.
  23724. */
  23725. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23726. /**
  23727. * Generates a square wave oscillation based on a timer.
  23728. *
  23729. * @tsl
  23730. * @function
  23731. * @param {Node<float>} t - The timer to generate the oscillation with.
  23732. * @return {Node<float>} The oscillation node.
  23733. */
  23734. const oscSquare = ( t = time ) => t.fract().round();
  23735. /**
  23736. * Generates a triangle wave oscillation based on a timer.
  23737. *
  23738. * @tsl
  23739. * @function
  23740. * @param {Node<float>} t - The timer to generate the oscillation with.
  23741. * @return {Node<float>} The oscillation node.
  23742. */
  23743. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23744. /**
  23745. * Generates a sawtooth wave oscillation based on a timer.
  23746. *
  23747. * @tsl
  23748. * @function
  23749. * @param {Node<float>} t - The timer to generate the oscillation with.
  23750. * @return {Node<float>} The oscillation node.
  23751. */
  23752. const oscSawtooth = ( t = time ) => t.fract();
  23753. /**
  23754. * Rotates the given uv coordinates around a center point
  23755. *
  23756. * @tsl
  23757. * @function
  23758. * @param {Node<vec2>} uv - The uv coordinates.
  23759. * @param {Node<float>} rotation - The rotation defined in radians.
  23760. * @param {Node<vec2>} center - The center of rotation
  23761. * @return {Node<vec2>} The rotated uv coordinates.
  23762. */
  23763. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23764. return rotate( uv.sub( center ), rotation ).add( center );
  23765. } );
  23766. /**
  23767. * Applies a spherical warping effect to the given uv coordinates.
  23768. *
  23769. * @tsl
  23770. * @function
  23771. * @param {Node<vec2>} uv - The uv coordinates.
  23772. * @param {Node<float>} strength - The strength of the effect.
  23773. * @param {Node<vec2>} center - The center point
  23774. * @return {Node<vec2>} The updated uv coordinates.
  23775. */
  23776. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23777. const delta = uv.sub( center );
  23778. const delta2 = delta.dot( delta );
  23779. const delta4 = delta2.mul( delta2 );
  23780. const deltaOffset = delta4.mul( strength );
  23781. return uv.add( delta.mul( deltaOffset ) );
  23782. } );
  23783. /**
  23784. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23785. * oriented always towards the camera.
  23786. *
  23787. * ```js
  23788. * material.vertexNode = billboarding();
  23789. * ```
  23790. *
  23791. * @tsl
  23792. * @function
  23793. * @param {Object} config - The configuration object.
  23794. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23795. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23796. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23797. * @return {Node<vec3>} The updated vertex position in clip space.
  23798. */
  23799. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23800. let worldMatrix;
  23801. if ( position !== null ) {
  23802. worldMatrix = modelWorldMatrix.toVar();
  23803. worldMatrix[ 3 ][ 0 ] = position.x;
  23804. worldMatrix[ 3 ][ 1 ] = position.y;
  23805. worldMatrix[ 3 ][ 2 ] = position.z;
  23806. } else {
  23807. worldMatrix = modelWorldMatrix;
  23808. }
  23809. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23810. if ( defined( horizontal ) ) {
  23811. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23812. modelViewMatrix[ 0 ][ 1 ] = 0;
  23813. modelViewMatrix[ 0 ][ 2 ] = 0;
  23814. }
  23815. if ( defined( vertical ) ) {
  23816. modelViewMatrix[ 1 ][ 0 ] = 0;
  23817. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23818. modelViewMatrix[ 1 ][ 2 ] = 0;
  23819. }
  23820. modelViewMatrix[ 2 ][ 0 ] = 0;
  23821. modelViewMatrix[ 2 ][ 1 ] = 0;
  23822. modelViewMatrix[ 2 ][ 2 ] = 1;
  23823. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23824. } );
  23825. /**
  23826. * A special version of a screen uv function that involves a depth comparison
  23827. * when computing the final uvs. The function mitigates visual errors when
  23828. * using viewport texture nodes for refraction purposes. Without this function
  23829. * objects in front of a refractive surface might appear on the refractive surface
  23830. * which is incorrect.
  23831. *
  23832. * @tsl
  23833. * @function
  23834. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23835. * @return {Node<vec2>} The update uv coordinates.
  23836. */
  23837. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23838. const depth = linearDepth();
  23839. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23840. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23841. return finalUV;
  23842. } );
  23843. /**
  23844. * Can be used to compute texture coordinates for animated sprite sheets.
  23845. *
  23846. * ```js
  23847. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23848. *
  23849. * material.colorNode = texture( spriteSheet, uvNode );
  23850. * ```
  23851. *
  23852. * @augments Node
  23853. */
  23854. class SpriteSheetUVNode extends Node {
  23855. static get type() {
  23856. return 'SpriteSheetUVNode';
  23857. }
  23858. /**
  23859. * Constructs a new sprite sheet uv node.
  23860. *
  23861. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23862. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23863. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23864. */
  23865. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23866. super( 'vec2' );
  23867. /**
  23868. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23869. *
  23870. * @type {Node<vec2>}
  23871. */
  23872. this.countNode = countNode;
  23873. /**
  23874. * The uv node.
  23875. *
  23876. * @type {Node<vec2>}
  23877. */
  23878. this.uvNode = uvNode;
  23879. /**
  23880. * The node that defines the current frame/sprite.
  23881. *
  23882. * @type {Node<float>}
  23883. */
  23884. this.frameNode = frameNode;
  23885. }
  23886. setup() {
  23887. const { frameNode, uvNode, countNode } = this;
  23888. const { width, height } = countNode;
  23889. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23890. const column = frameNum.mod( width );
  23891. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23892. const scale = countNode.reciprocal();
  23893. const uvFrameOffset = vec2( column, row );
  23894. return uvNode.add( uvFrameOffset ).mul( scale );
  23895. }
  23896. }
  23897. /**
  23898. * TSL function for creating a sprite sheet uv node.
  23899. *
  23900. * @tsl
  23901. * @function
  23902. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23903. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23904. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23905. * @returns {SpriteSheetUVNode}
  23906. */
  23907. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23908. /**
  23909. * TSL function for creating a triplanar textures node.
  23910. *
  23911. * Can be used for triplanar texture mapping.
  23912. *
  23913. * ```js
  23914. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23915. * ```
  23916. *
  23917. * @tsl
  23918. * @function
  23919. * @param {Node} textureXNode - First texture node.
  23920. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23921. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23922. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23923. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23924. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23925. * @returns {Node<vec4>}
  23926. */
  23927. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23928. // Reference: https://github.com/keijiro/StandardTriplanar
  23929. // Blending factor of triplanar mapping
  23930. let bf = normalNode.abs().normalize();
  23931. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23932. // Triplanar mapping
  23933. const tx = positionNode.yz.mul( scaleNode );
  23934. const ty = positionNode.zx.mul( scaleNode );
  23935. const tz = positionNode.xy.mul( scaleNode );
  23936. // Base color
  23937. const textureX = textureXNode.value;
  23938. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23939. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23940. const cx = texture( textureX, tx ).mul( bf.x );
  23941. const cy = texture( textureY, ty ).mul( bf.y );
  23942. const cz = texture( textureZ, tz ).mul( bf.z );
  23943. return add( cx, cy, cz );
  23944. } );
  23945. /**
  23946. * TSL function for creating a triplanar textures node.
  23947. *
  23948. * @tsl
  23949. * @function
  23950. * @param {Node} textureXNode - First texture node.
  23951. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23952. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23953. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23954. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23955. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23956. * @returns {Node<vec4>}
  23957. */
  23958. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23959. const _reflectorPlane = new Plane();
  23960. const _normal = new Vector3();
  23961. const _reflectorWorldPosition = new Vector3();
  23962. const _cameraWorldPosition = new Vector3();
  23963. const _rotationMatrix = new Matrix4();
  23964. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23965. const clipPlane = new Vector4();
  23966. const _view = new Vector3();
  23967. const _target = new Vector3();
  23968. const _q = new Vector4();
  23969. const _size$2 = new Vector2();
  23970. const _defaultRT = new RenderTarget();
  23971. const _defaultUV = screenUV.flipX();
  23972. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23973. let _inReflector = false;
  23974. /**
  23975. * This node can be used to implement mirror-like flat reflective surfaces.
  23976. *
  23977. * ```js
  23978. * const groundReflector = reflector();
  23979. * material.colorNode = groundReflector;
  23980. *
  23981. * const plane = new Mesh( geometry, material );
  23982. * plane.add( groundReflector.target );
  23983. * ```
  23984. *
  23985. * @augments TextureNode
  23986. */
  23987. class ReflectorNode extends TextureNode {
  23988. static get type() {
  23989. return 'ReflectorNode';
  23990. }
  23991. /**
  23992. * Constructs a new reflector node.
  23993. *
  23994. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23995. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23996. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23997. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23998. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23999. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24000. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24001. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24002. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24003. */
  24004. constructor( parameters = {} ) {
  24005. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  24006. /**
  24007. * A reference to the internal reflector base node which holds the actual implementation.
  24008. *
  24009. * @private
  24010. * @type {ReflectorBaseNode}
  24011. * @default ReflectorBaseNode
  24012. */
  24013. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  24014. /**
  24015. * A reference to the internal depth node.
  24016. *
  24017. * @private
  24018. * @type {?Node}
  24019. * @default null
  24020. */
  24021. this._depthNode = null;
  24022. this.setUpdateMatrix( false );
  24023. }
  24024. /**
  24025. * A reference to the internal reflector node.
  24026. *
  24027. * @type {ReflectorBaseNode}
  24028. */
  24029. get reflector() {
  24030. return this._reflectorBaseNode;
  24031. }
  24032. /**
  24033. * A reference to 3D object the reflector is linked to.
  24034. *
  24035. * @type {Object3D}
  24036. */
  24037. get target() {
  24038. return this._reflectorBaseNode.target;
  24039. }
  24040. /**
  24041. * Returns a node representing the mirror's depth. That can be used
  24042. * to implement more advanced reflection effects like distance attenuation.
  24043. *
  24044. * @return {Node} The depth node.
  24045. */
  24046. getDepthNode() {
  24047. if ( this._depthNode === null ) {
  24048. if ( this._reflectorBaseNode.depth !== true ) {
  24049. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  24050. }
  24051. this._depthNode = nodeObject( new ReflectorNode( {
  24052. defaultTexture: _defaultRT.depthTexture,
  24053. reflector: this._reflectorBaseNode
  24054. } ) );
  24055. }
  24056. return this._depthNode;
  24057. }
  24058. setup( builder ) {
  24059. // ignore if used in post-processing
  24060. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  24061. return super.setup( builder );
  24062. }
  24063. clone() {
  24064. const newNode = new this.constructor( this.reflectorNode );
  24065. newNode.uvNode = this.uvNode;
  24066. newNode.levelNode = this.levelNode;
  24067. newNode.biasNode = this.biasNode;
  24068. newNode.sampler = this.sampler;
  24069. newNode.depthNode = this.depthNode;
  24070. newNode.compareNode = this.compareNode;
  24071. newNode.gradNode = this.gradNode;
  24072. newNode.offsetNode = this.offsetNode;
  24073. newNode._reflectorBaseNode = this._reflectorBaseNode;
  24074. return newNode;
  24075. }
  24076. /**
  24077. * Frees internal resources. Should be called when the node is no longer in use.
  24078. */
  24079. dispose() {
  24080. super.dispose();
  24081. this._reflectorBaseNode.dispose();
  24082. }
  24083. }
  24084. /**
  24085. * Holds the actual implementation of the reflector.
  24086. *
  24087. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  24088. * in `ReflectorNode`, see #29619.
  24089. *
  24090. * @private
  24091. * @augments Node
  24092. */
  24093. class ReflectorBaseNode extends Node {
  24094. static get type() {
  24095. return 'ReflectorBaseNode';
  24096. }
  24097. /**
  24098. * Constructs a new reflector base node.
  24099. *
  24100. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  24101. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24102. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24103. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24104. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24105. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24106. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24107. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24108. */
  24109. constructor( textureNode, parameters = {} ) {
  24110. super();
  24111. const {
  24112. target = new Object3D(),
  24113. resolutionScale = 1,
  24114. generateMipmaps = false,
  24115. bounces = true,
  24116. depth = false,
  24117. samples = 0
  24118. } = parameters;
  24119. /**
  24120. * Represents the rendered reflections as a texture node.
  24121. *
  24122. * @type {TextureNode}
  24123. */
  24124. this.textureNode = textureNode;
  24125. /**
  24126. * The 3D object the reflector is linked to.
  24127. *
  24128. * @type {Object3D}
  24129. * @default {new Object3D()}
  24130. */
  24131. this.target = target;
  24132. /**
  24133. * The resolution scale.
  24134. *
  24135. * @type {number}
  24136. * @default {1}
  24137. */
  24138. this.resolutionScale = resolutionScale;
  24139. if ( parameters.resolution !== undefined ) {
  24140. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  24141. this.resolutionScale = parameters.resolution;
  24142. }
  24143. /**
  24144. * Whether mipmaps should be generated or not.
  24145. *
  24146. * @type {boolean}
  24147. * @default {false}
  24148. */
  24149. this.generateMipmaps = generateMipmaps;
  24150. /**
  24151. * Whether reflectors can render other reflector nodes or not.
  24152. *
  24153. * @type {boolean}
  24154. * @default {true}
  24155. */
  24156. this.bounces = bounces;
  24157. /**
  24158. * Whether depth data should be generated or not.
  24159. *
  24160. * @type {boolean}
  24161. * @default {false}
  24162. */
  24163. this.depth = depth;
  24164. /**
  24165. * The number of anti-aliasing samples for the render-target
  24166. *
  24167. * @type {number}
  24168. * @default {0}
  24169. */
  24170. this.samples = samples;
  24171. /**
  24172. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  24173. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  24174. *
  24175. * @type {string}
  24176. * @default 'render'
  24177. */
  24178. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  24179. /**
  24180. * Weak map for managing virtual cameras.
  24181. *
  24182. * @type {WeakMap<Camera, Camera>}
  24183. */
  24184. this.virtualCameras = new WeakMap();
  24185. /**
  24186. * Weak map for managing render targets.
  24187. *
  24188. * @type {Map<Camera, RenderTarget>}
  24189. */
  24190. this.renderTargets = new Map();
  24191. /**
  24192. * Force render even if reflector is facing away from camera.
  24193. *
  24194. * @type {boolean}
  24195. * @default {false}
  24196. */
  24197. this.forceUpdate = false;
  24198. /**
  24199. * Whether the reflector has been rendered or not.
  24200. *
  24201. * When the reflector is facing away from the camera,
  24202. * this flag is set to `false` and the texture will be empty(black).
  24203. *
  24204. * @type {boolean}
  24205. * @default {false}
  24206. */
  24207. this.hasOutput = false;
  24208. }
  24209. /**
  24210. * Updates the resolution of the internal render target.
  24211. *
  24212. * @private
  24213. * @param {RenderTarget} renderTarget - The render target to resize.
  24214. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  24215. */
  24216. _updateResolution( renderTarget, renderer ) {
  24217. const resolution = this.resolutionScale;
  24218. renderer.getDrawingBufferSize( _size$2 );
  24219. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  24220. }
  24221. setup( builder ) {
  24222. this._updateResolution( _defaultRT, builder.renderer );
  24223. return super.setup( builder );
  24224. }
  24225. /**
  24226. * Frees internal resources. Should be called when the node is no longer in use.
  24227. */
  24228. dispose() {
  24229. super.dispose();
  24230. for ( const renderTarget of this.renderTargets.values() ) {
  24231. renderTarget.dispose();
  24232. }
  24233. }
  24234. /**
  24235. * Returns a virtual camera for the given camera. The virtual camera is used to
  24236. * render the scene from the reflector's view so correct reflections can be produced.
  24237. *
  24238. * @param {Camera} camera - The scene's camera.
  24239. * @return {Camera} The corresponding virtual camera.
  24240. */
  24241. getVirtualCamera( camera ) {
  24242. let virtualCamera = this.virtualCameras.get( camera );
  24243. if ( virtualCamera === undefined ) {
  24244. virtualCamera = camera.clone();
  24245. this.virtualCameras.set( camera, virtualCamera );
  24246. }
  24247. return virtualCamera;
  24248. }
  24249. /**
  24250. * Returns a render target for the given camera. The reflections are rendered
  24251. * into this render target.
  24252. *
  24253. * @param {Camera} camera - The scene's camera.
  24254. * @return {RenderTarget} The render target.
  24255. */
  24256. getRenderTarget( camera ) {
  24257. let renderTarget = this.renderTargets.get( camera );
  24258. if ( renderTarget === undefined ) {
  24259. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  24260. if ( this.generateMipmaps === true ) {
  24261. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  24262. renderTarget.texture.generateMipmaps = true;
  24263. }
  24264. if ( this.depth === true ) {
  24265. renderTarget.depthTexture = new DepthTexture();
  24266. }
  24267. this.renderTargets.set( camera, renderTarget );
  24268. }
  24269. return renderTarget;
  24270. }
  24271. updateBefore( frame ) {
  24272. if ( this.bounces === false && _inReflector ) return false;
  24273. _inReflector = true;
  24274. const { scene, camera, renderer, material } = frame;
  24275. const { target } = this;
  24276. const virtualCamera = this.getVirtualCamera( camera );
  24277. const renderTarget = this.getRenderTarget( virtualCamera );
  24278. renderer.getDrawingBufferSize( _size$2 );
  24279. this._updateResolution( renderTarget, renderer );
  24280. //
  24281. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  24282. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  24283. _rotationMatrix.extractRotation( target.matrixWorld );
  24284. _normal.set( 0, 0, 1 );
  24285. _normal.applyMatrix4( _rotationMatrix );
  24286. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  24287. // Avoid rendering when reflector is facing away unless forcing an update
  24288. const isFacingAway = _view.dot( _normal ) > 0;
  24289. let needsClear = false;
  24290. if ( isFacingAway === true && this.forceUpdate === false ) {
  24291. if ( this.hasOutput === false ) {
  24292. _inReflector = false;
  24293. return;
  24294. }
  24295. needsClear = true;
  24296. }
  24297. _view.reflect( _normal ).negate();
  24298. _view.add( _reflectorWorldPosition );
  24299. _rotationMatrix.extractRotation( camera.matrixWorld );
  24300. _lookAtPosition.set( 0, 0, -1 );
  24301. _lookAtPosition.applyMatrix4( _rotationMatrix );
  24302. _lookAtPosition.add( _cameraWorldPosition );
  24303. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  24304. _target.reflect( _normal ).negate();
  24305. _target.add( _reflectorWorldPosition );
  24306. //
  24307. virtualCamera.coordinateSystem = camera.coordinateSystem;
  24308. virtualCamera.position.copy( _view );
  24309. virtualCamera.up.set( 0, 1, 0 );
  24310. virtualCamera.up.applyMatrix4( _rotationMatrix );
  24311. virtualCamera.up.reflect( _normal );
  24312. virtualCamera.lookAt( _target );
  24313. virtualCamera.near = camera.near;
  24314. virtualCamera.far = camera.far;
  24315. virtualCamera.updateMatrixWorld();
  24316. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  24317. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  24318. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  24319. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  24320. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  24321. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  24322. const projectionMatrix = virtualCamera.projectionMatrix;
  24323. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  24324. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  24325. _q.z = -1;
  24326. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  24327. // Calculate the scaled plane vector
  24328. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  24329. const clipBias = 0;
  24330. // Replacing the third row of the projection matrix
  24331. projectionMatrix.elements[ 2 ] = clipPlane.x;
  24332. projectionMatrix.elements[ 6 ] = clipPlane.y;
  24333. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  24334. projectionMatrix.elements[ 14 ] = clipPlane.w;
  24335. //
  24336. this.textureNode.value = renderTarget.texture;
  24337. if ( this.depth === true ) {
  24338. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  24339. }
  24340. material.visible = false;
  24341. const currentRenderTarget = renderer.getRenderTarget();
  24342. const currentMRT = renderer.getMRT();
  24343. const currentAutoClear = renderer.autoClear;
  24344. renderer.setMRT( null );
  24345. renderer.setRenderTarget( renderTarget );
  24346. renderer.autoClear = true;
  24347. const previousName = scene.name;
  24348. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  24349. if ( needsClear ) {
  24350. renderer.clear();
  24351. this.hasOutput = false;
  24352. } else {
  24353. renderer.render( scene, virtualCamera );
  24354. this.hasOutput = true;
  24355. }
  24356. scene.name = previousName;
  24357. renderer.setMRT( currentMRT );
  24358. renderer.setRenderTarget( currentRenderTarget );
  24359. renderer.autoClear = currentAutoClear;
  24360. material.visible = true;
  24361. _inReflector = false;
  24362. this.forceUpdate = false;
  24363. }
  24364. /**
  24365. * The resolution scale.
  24366. *
  24367. * @deprecated
  24368. * @type {number}
  24369. * @default {1}
  24370. */
  24371. get resolution() {
  24372. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24373. return this.resolutionScale;
  24374. }
  24375. set resolution( value ) {
  24376. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24377. this.resolutionScale = value;
  24378. }
  24379. }
  24380. /**
  24381. * TSL function for creating a reflector node.
  24382. *
  24383. * @tsl
  24384. * @function
  24385. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24386. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24387. * @param {number} [parameters.resolution=1] - The resolution scale.
  24388. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24389. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24390. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24391. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24392. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24393. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24394. * @returns {ReflectorNode}
  24395. */
  24396. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24397. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24398. /**
  24399. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24400. *
  24401. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24402. *
  24403. * @private
  24404. * @augments BufferGeometry
  24405. */
  24406. class QuadGeometry extends BufferGeometry {
  24407. /**
  24408. * Constructs a new quad geometry.
  24409. *
  24410. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24411. */
  24412. constructor( flipY = false ) {
  24413. super();
  24414. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24415. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24416. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24417. }
  24418. }
  24419. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24420. /**
  24421. * This module is a helper for passes which need to render a full
  24422. * screen effect which is quite common in context of post processing.
  24423. *
  24424. * The intended usage is to reuse a single quad mesh for rendering
  24425. * subsequent passes by just reassigning the `material` reference.
  24426. *
  24427. * Note: This module can only be used with `WebGPURenderer`.
  24428. *
  24429. * @augments Mesh
  24430. */
  24431. class QuadMesh extends Mesh {
  24432. /**
  24433. * Constructs a new quad mesh.
  24434. *
  24435. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24436. */
  24437. constructor( material = null ) {
  24438. super( _geometry, material );
  24439. /**
  24440. * The camera to render the quad mesh with.
  24441. *
  24442. * @type {OrthographicCamera}
  24443. * @readonly
  24444. */
  24445. this.camera = _camera;
  24446. /**
  24447. * This flag can be used for type testing.
  24448. *
  24449. * @type {boolean}
  24450. * @readonly
  24451. * @default true
  24452. */
  24453. this.isQuadMesh = true;
  24454. }
  24455. /**
  24456. * Async version of `render()`.
  24457. *
  24458. * @async
  24459. * @deprecated
  24460. * @param {Renderer} renderer - The renderer.
  24461. * @return {Promise} A Promise that resolves when the render has been finished.
  24462. */
  24463. async renderAsync( renderer ) {
  24464. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  24465. await renderer.init();
  24466. renderer.render( this, _camera );
  24467. }
  24468. /**
  24469. * Renders the quad mesh
  24470. *
  24471. * @param {Renderer} renderer - The renderer.
  24472. */
  24473. render( renderer ) {
  24474. renderer.render( this, _camera );
  24475. }
  24476. }
  24477. const _size$1 = /*@__PURE__*/ new Vector2();
  24478. /**
  24479. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24480. * This module is especially relevant in context of post processing where certain nodes require
  24481. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24482. * on this module, the node system can automatically ensure texture input if required.
  24483. *
  24484. * @augments TextureNode
  24485. */
  24486. class RTTNode extends TextureNode {
  24487. static get type() {
  24488. return 'RTTNode';
  24489. }
  24490. /**
  24491. * Constructs a new RTT node.
  24492. *
  24493. * @param {Node} node - The node to render a texture with.
  24494. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24495. * @param {?number} [height=null] - The height of the internal render target.
  24496. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24497. */
  24498. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24499. const renderTarget = new RenderTarget( width, height, options );
  24500. super( renderTarget.texture, uv$1() );
  24501. /**
  24502. * This flag can be used for type testing.
  24503. *
  24504. * @type {boolean}
  24505. * @readonly
  24506. * @default true
  24507. */
  24508. this.isRTTNode = true;
  24509. /**
  24510. * The node to render a texture with.
  24511. *
  24512. * @type {Node}
  24513. */
  24514. this.node = node;
  24515. /**
  24516. * The width of the internal render target.
  24517. * If not width is applied, the render target is automatically resized.
  24518. *
  24519. * @type {?number}
  24520. * @default null
  24521. */
  24522. this.width = width;
  24523. /**
  24524. * The height of the internal render target.
  24525. *
  24526. * @type {?number}
  24527. * @default null
  24528. */
  24529. this.height = height;
  24530. /**
  24531. * The pixel ratio
  24532. *
  24533. * @type {number}
  24534. * @default 1
  24535. */
  24536. this.pixelRatio = 1;
  24537. /**
  24538. * The render target
  24539. *
  24540. * @type {RenderTarget}
  24541. */
  24542. this.renderTarget = renderTarget;
  24543. /**
  24544. * Whether the texture requires an update or not.
  24545. *
  24546. * @type {boolean}
  24547. * @default true
  24548. */
  24549. this.textureNeedsUpdate = true;
  24550. /**
  24551. * Whether the texture should automatically be updated or not.
  24552. *
  24553. * @type {boolean}
  24554. * @default true
  24555. */
  24556. this.autoUpdate = true;
  24557. /**
  24558. * The node which is used with the quad mesh for RTT.
  24559. *
  24560. * @private
  24561. * @type {Node}
  24562. * @default null
  24563. */
  24564. this._rttNode = null;
  24565. /**
  24566. * The internal quad mesh for RTT.
  24567. *
  24568. * @private
  24569. * @type {QuadMesh}
  24570. */
  24571. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24572. /**
  24573. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24574. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24575. *
  24576. * @type {string}
  24577. * @default 'render'
  24578. */
  24579. this.updateBeforeType = NodeUpdateType.RENDER;
  24580. }
  24581. /**
  24582. * Whether the internal render target should automatically be resized or not.
  24583. *
  24584. * @type {boolean}
  24585. * @readonly
  24586. * @default true
  24587. */
  24588. get autoResize() {
  24589. return this.width === null;
  24590. }
  24591. setup( builder ) {
  24592. this._rttNode = this.node.context( builder.getSharedContext() );
  24593. this._quadMesh.material.name = 'RTT';
  24594. this._quadMesh.material.needsUpdate = true;
  24595. return super.setup( builder );
  24596. }
  24597. /**
  24598. * Sets the size of the internal render target
  24599. *
  24600. * @param {number} width - The width to set.
  24601. * @param {number} height - The width to set.
  24602. */
  24603. setSize( width, height ) {
  24604. this.width = width;
  24605. this.height = height;
  24606. const effectiveWidth = width * this.pixelRatio;
  24607. const effectiveHeight = height * this.pixelRatio;
  24608. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24609. this.textureNeedsUpdate = true;
  24610. }
  24611. /**
  24612. * Sets the pixel ratio. This will also resize the render target.
  24613. *
  24614. * @param {number} pixelRatio - The pixel ratio to set.
  24615. */
  24616. setPixelRatio( pixelRatio ) {
  24617. this.pixelRatio = pixelRatio;
  24618. this.setSize( this.width, this.height );
  24619. }
  24620. updateBefore( { renderer } ) {
  24621. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24622. this.textureNeedsUpdate = false;
  24623. //
  24624. if ( this.autoResize === true ) {
  24625. const pixelRatio = renderer.getPixelRatio();
  24626. const size = renderer.getSize( _size$1 );
  24627. const effectiveWidth = size.width * pixelRatio;
  24628. const effectiveHeight = size.height * pixelRatio;
  24629. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24630. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24631. this.textureNeedsUpdate = true;
  24632. }
  24633. }
  24634. //
  24635. let name = 'RTT';
  24636. if ( this.node.name ) {
  24637. name = this.node.name + ' [ ' + name + ' ]';
  24638. }
  24639. this._quadMesh.material.fragmentNode = this._rttNode;
  24640. this._quadMesh.name = name;
  24641. //
  24642. const currentRenderTarget = renderer.getRenderTarget();
  24643. renderer.setRenderTarget( this.renderTarget );
  24644. this._quadMesh.render( renderer );
  24645. renderer.setRenderTarget( currentRenderTarget );
  24646. }
  24647. clone() {
  24648. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24649. newNode.sampler = this.sampler;
  24650. newNode.referenceNode = this;
  24651. return newNode;
  24652. }
  24653. }
  24654. /**
  24655. * TSL function for creating a RTT node.
  24656. *
  24657. * @tsl
  24658. * @function
  24659. * @param {Node} node - The node to render a texture with.
  24660. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24661. * @param {?number} [height=null] - The height of the internal render target.
  24662. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24663. * @returns {RTTNode}
  24664. */
  24665. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24666. /**
  24667. * TSL function for converting nodes to textures nodes.
  24668. *
  24669. * @tsl
  24670. * @function
  24671. * @param {Node} node - The node to render a texture with.
  24672. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24673. * @param {?number} [height=null] - The height of the internal render target.
  24674. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24675. * @returns {RTTNode}
  24676. */
  24677. const convertToTexture = ( node, ...params ) => {
  24678. if ( node.isSampleNode || node.isTextureNode ) return node;
  24679. if ( node.isPassNode ) return node.getTextureNode();
  24680. return rtt( node, ...params );
  24681. };
  24682. /**
  24683. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24684. * depth value and the camera's inverse projection matrix.
  24685. *
  24686. * @tsl
  24687. * @function
  24688. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24689. * @param {Node<float>} depth - The fragment's depth value.
  24690. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24691. * @return {Node<vec3>} The fragments position in view space.
  24692. */
  24693. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24694. let clipSpacePosition;
  24695. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24696. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24697. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24698. } else {
  24699. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24700. }
  24701. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24702. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24703. } );
  24704. /**
  24705. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24706. * and the camera's projection matrix
  24707. *
  24708. * @tsl
  24709. * @function
  24710. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24711. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24712. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24713. */
  24714. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24715. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24716. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24717. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24718. } );
  24719. /**
  24720. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24721. * target is available or if flat surface normals are required.
  24722. *
  24723. * @tsl
  24724. * @function
  24725. * @param {Node<vec2>} uv - The texture coordinate.
  24726. * @param {DepthTexture} depthTexture - The depth texture.
  24727. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24728. * @return {Node<vec3>} The computed normal vector.
  24729. */
  24730. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24731. const size = textureSize( textureLoad( depthTexture ) );
  24732. const p = ivec2( uv.mul( size ) ).toVar();
  24733. const c0 = textureLoad( depthTexture, p ).toVar();
  24734. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24735. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24736. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24737. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24738. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24739. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24740. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24741. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24742. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24743. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24744. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24745. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24746. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24747. 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 ) ) );
  24748. 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 ) ) );
  24749. return normalize( cross( dpdx, dpdy ) );
  24750. } );
  24751. /**
  24752. * Class representing a node that samples a value using a provided callback function.
  24753. *
  24754. * @extends Node
  24755. */
  24756. class SampleNode extends Node {
  24757. /**
  24758. * Returns the type of the node.
  24759. *
  24760. * @type {string}
  24761. * @readonly
  24762. * @static
  24763. */
  24764. static get type() {
  24765. return 'SampleNode';
  24766. }
  24767. /**
  24768. * Creates an instance of SampleNode.
  24769. *
  24770. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24771. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24772. */
  24773. constructor( callback, uvNode = null ) {
  24774. super();
  24775. this.callback = callback;
  24776. /**
  24777. * Represents the texture coordinates.
  24778. *
  24779. * @type {?Node<vec2|vec3>}
  24780. * @default null
  24781. */
  24782. this.uvNode = uvNode;
  24783. /**
  24784. * This flag can be used for type testing.
  24785. *
  24786. * @type {boolean}
  24787. * @readonly
  24788. * @default true
  24789. */
  24790. this.isSampleNode = true;
  24791. }
  24792. /**
  24793. * Sets up the node by sampling with the default UV accessor.
  24794. *
  24795. * @returns {Node} The result of the callback function when called with the UV node.
  24796. */
  24797. setup() {
  24798. return this.sample( uv$1() );
  24799. }
  24800. /**
  24801. * Calls the callback function with the provided UV node.
  24802. *
  24803. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24804. * @returns {Node} The result of the callback function.
  24805. */
  24806. sample( uv ) {
  24807. return this.callback( uv );
  24808. }
  24809. }
  24810. /**
  24811. * Helper function to create a SampleNode wrapped as a node object.
  24812. *
  24813. * @function
  24814. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24815. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24816. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24817. */
  24818. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24819. /**
  24820. * EventNode is a node that executes a callback during specific update phases.
  24821. *
  24822. * @augments Node
  24823. */
  24824. class EventNode extends Node {
  24825. static get type() {
  24826. return 'EventNode';
  24827. }
  24828. /**
  24829. * Creates an EventNode.
  24830. *
  24831. * @param {string} eventType - The type of event
  24832. * @param {Function} callback - The callback to execute on update.
  24833. */
  24834. constructor( eventType, callback ) {
  24835. super( 'void' );
  24836. this.eventType = eventType;
  24837. this.callback = callback;
  24838. if ( eventType === EventNode.OBJECT ) {
  24839. this.updateType = NodeUpdateType.OBJECT;
  24840. } else if ( eventType === EventNode.MATERIAL ) {
  24841. this.updateType = NodeUpdateType.RENDER;
  24842. }
  24843. }
  24844. update( frame ) {
  24845. this.callback( frame );
  24846. }
  24847. }
  24848. EventNode.OBJECT = 'object';
  24849. EventNode.MATERIAL = 'material';
  24850. /**
  24851. * Helper to create an EventNode and add it to the stack.
  24852. *
  24853. * @param {string} type - The event type.
  24854. * @param {Function} callback - The callback function.
  24855. * @returns {EventNode}
  24856. */
  24857. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24858. /**
  24859. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24860. *
  24861. * 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.
  24862. *
  24863. * @param {Function} callback - The callback function.
  24864. * @returns {EventNode}
  24865. */
  24866. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24867. /**
  24868. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24869. *
  24870. * 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.
  24871. *
  24872. * @param {Function} callback - The callback function.
  24873. * @returns {EventNode}
  24874. */
  24875. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24876. /**
  24877. * This special type of instanced buffer attribute is intended for compute shaders.
  24878. * In earlier three.js versions it was only possible to update attribute data
  24879. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24880. * new material system and renderer it is now possible to use compute shaders
  24881. * to compute the data for an attribute more efficiently on the GPU.
  24882. *
  24883. * The idea is to create an instance of this class and provide it as an input
  24884. * to {@link StorageBufferNode}.
  24885. *
  24886. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24887. *
  24888. * @augments InstancedBufferAttribute
  24889. */
  24890. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24891. /**
  24892. * Constructs a new storage instanced buffer attribute.
  24893. *
  24894. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24895. * The subsequent parameters are then obsolete.
  24896. * @param {number} itemSize - The item size.
  24897. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24898. */
  24899. constructor( count, itemSize, typeClass = Float32Array ) {
  24900. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24901. super( array, itemSize );
  24902. /**
  24903. * This flag can be used for type testing.
  24904. *
  24905. * @type {boolean}
  24906. * @readonly
  24907. * @default true
  24908. */
  24909. this.isStorageInstancedBufferAttribute = true;
  24910. }
  24911. }
  24912. /**
  24913. * This special type of buffer attribute is intended for compute shaders.
  24914. * In earlier three.js versions it was only possible to update attribute data
  24915. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24916. * new material system and renderer it is now possible to use compute shaders
  24917. * to compute the data for an attribute more efficiently on the GPU.
  24918. *
  24919. * The idea is to create an instance of this class and provide it as an input
  24920. * to {@link StorageBufferNode}.
  24921. *
  24922. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24923. *
  24924. * @augments BufferAttribute
  24925. */
  24926. class StorageBufferAttribute extends BufferAttribute {
  24927. /**
  24928. * Constructs a new storage buffer attribute.
  24929. *
  24930. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24931. * The subsequent parameters are then obsolete.
  24932. * @param {number} itemSize - The item size.
  24933. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24934. */
  24935. constructor( count, itemSize, typeClass = Float32Array ) {
  24936. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24937. super( array, itemSize );
  24938. /**
  24939. * This flag can be used for type testing.
  24940. *
  24941. * @type {boolean}
  24942. * @readonly
  24943. * @default true
  24944. */
  24945. this.isStorageBufferAttribute = true;
  24946. }
  24947. }
  24948. /**
  24949. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24950. *
  24951. * @tsl
  24952. * @function
  24953. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24954. * @param {string|Struct} [type='float'] - The data type.
  24955. * @returns {StorageBufferNode}
  24956. */
  24957. const attributeArray = ( count, type = 'float' ) => {
  24958. let itemSize, typedArray;
  24959. if ( type.isStruct === true ) {
  24960. itemSize = type.layout.getLength();
  24961. typedArray = getTypedArrayFromType( 'float' );
  24962. } else {
  24963. itemSize = getLengthFromType( type );
  24964. typedArray = getTypedArrayFromType( type );
  24965. }
  24966. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24967. const node = storage( buffer, type, count );
  24968. return node;
  24969. };
  24970. /**
  24971. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24972. *
  24973. * @tsl
  24974. * @function
  24975. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24976. * @param {string|Struct} [type='float'] - The data type.
  24977. * @returns {StorageBufferNode}
  24978. */
  24979. const instancedArray = ( count, type = 'float' ) => {
  24980. let itemSize, typedArray;
  24981. if ( type.isStruct === true ) {
  24982. itemSize = type.layout.getLength();
  24983. typedArray = getTypedArrayFromType( 'float' );
  24984. } else {
  24985. itemSize = getLengthFromType( type );
  24986. typedArray = getTypedArrayFromType( type );
  24987. }
  24988. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24989. const node = storage( buffer, type, count );
  24990. return node;
  24991. };
  24992. /**
  24993. * A node for representing the uv coordinates of points.
  24994. *
  24995. * Can only be used with a WebGL backend. In WebGPU, point
  24996. * primitives always have the size of one pixel and can thus
  24997. * can't be used as sprite-like objects that display textures.
  24998. *
  24999. * @augments Node
  25000. */
  25001. class PointUVNode extends Node {
  25002. static get type() {
  25003. return 'PointUVNode';
  25004. }
  25005. /**
  25006. * Constructs a new point uv node.
  25007. */
  25008. constructor() {
  25009. super( 'vec2' );
  25010. /**
  25011. * This flag can be used for type testing.
  25012. *
  25013. * @type {boolean}
  25014. * @readonly
  25015. * @default true
  25016. */
  25017. this.isPointUVNode = true;
  25018. }
  25019. generate( /*builder*/ ) {
  25020. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  25021. }
  25022. }
  25023. /**
  25024. * TSL object that represents the uv coordinates of points.
  25025. *
  25026. * @tsl
  25027. * @type {PointUVNode}
  25028. */
  25029. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  25030. const _e1 = /*@__PURE__*/ new Euler();
  25031. const _m1 = /*@__PURE__*/ new Matrix4();
  25032. /**
  25033. * This module allows access to a collection of scene properties. The following predefined TSL objects
  25034. * are available for easier use:
  25035. *
  25036. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  25037. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  25038. * - `backgroundRotation`: A node that represents the scene's background rotation.
  25039. *
  25040. * @augments Node
  25041. */
  25042. class SceneNode extends Node {
  25043. static get type() {
  25044. return 'SceneNode';
  25045. }
  25046. /**
  25047. * Constructs a new scene node.
  25048. *
  25049. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  25050. * @param {?Scene} [scene=null] - A reference to the scene.
  25051. */
  25052. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  25053. super();
  25054. /**
  25055. * The scope defines the type of scene property that is accessed.
  25056. *
  25057. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  25058. */
  25059. this.scope = scope;
  25060. /**
  25061. * A reference to the scene that is going to be accessed.
  25062. *
  25063. * @type {?Scene}
  25064. * @default null
  25065. */
  25066. this.scene = scene;
  25067. }
  25068. /**
  25069. * Depending on the scope, the method returns a different type of node that represents
  25070. * the respective scene property.
  25071. *
  25072. * @param {NodeBuilder} builder - The current node builder.
  25073. * @return {Node} The output node.
  25074. */
  25075. setup( builder ) {
  25076. const scope = this.scope;
  25077. const scene = this.scene !== null ? this.scene : builder.scene;
  25078. let output;
  25079. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  25080. output = reference( 'backgroundBlurriness', 'float', scene );
  25081. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  25082. output = reference( 'backgroundIntensity', 'float', scene );
  25083. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  25084. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25085. const background = scene.background;
  25086. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  25087. _e1.copy( scene.backgroundRotation );
  25088. // accommodate left-handed frame
  25089. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  25090. _m1.makeRotationFromEuler( _e1 );
  25091. } else {
  25092. _m1.identity();
  25093. }
  25094. return _m1;
  25095. } );
  25096. } else {
  25097. error( 'SceneNode: Unknown scope:', scope );
  25098. }
  25099. return output;
  25100. }
  25101. }
  25102. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  25103. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  25104. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  25105. /**
  25106. * TSL object that represents the scene's background blurriness.
  25107. *
  25108. * @tsl
  25109. * @type {SceneNode}
  25110. */
  25111. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  25112. /**
  25113. * TSL object that represents the scene's background intensity.
  25114. *
  25115. * @tsl
  25116. * @type {SceneNode}
  25117. */
  25118. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  25119. /**
  25120. * TSL object that represents the scene's background rotation.
  25121. *
  25122. * @tsl
  25123. * @type {SceneNode}
  25124. */
  25125. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  25126. /**
  25127. * This special version of a texture node can be used to
  25128. * write data into a storage texture with a compute shader.
  25129. *
  25130. * ```js
  25131. * const storageTexture = new THREE.StorageTexture( width, height );
  25132. *
  25133. * const computeTexture = Fn( ( { storageTexture } ) => {
  25134. *
  25135. * const posX = instanceIndex.mod( width );
  25136. * const posY = instanceIndex.div( width );
  25137. * const indexUV = uvec2( posX, posY );
  25138. *
  25139. * // generate RGB values
  25140. *
  25141. * const r = 1;
  25142. * const g = 1;
  25143. * const b = 1;
  25144. *
  25145. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  25146. *
  25147. * } );
  25148. *
  25149. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  25150. * renderer.computeAsync( computeNode );
  25151. * ```
  25152. *
  25153. * This node can only be used with a WebGPU backend.
  25154. *
  25155. * @augments TextureNode
  25156. */
  25157. class StorageTextureNode extends TextureNode {
  25158. static get type() {
  25159. return 'StorageTextureNode';
  25160. }
  25161. /**
  25162. * Constructs a new storage texture node.
  25163. *
  25164. * @param {StorageTexture} value - The storage texture.
  25165. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25166. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25167. */
  25168. constructor( value, uvNode, storeNode = null ) {
  25169. super( value, uvNode );
  25170. /**
  25171. * The value node that should be stored in the texture.
  25172. *
  25173. * @type {?Node}
  25174. * @default null
  25175. */
  25176. this.storeNode = storeNode;
  25177. /**
  25178. * The mip level to write to for storage textures.
  25179. *
  25180. * @type {number}
  25181. * @default 0
  25182. */
  25183. this.mipLevel = 0;
  25184. /**
  25185. * This flag can be used for type testing.
  25186. *
  25187. * @type {boolean}
  25188. * @readonly
  25189. * @default true
  25190. */
  25191. this.isStorageTextureNode = true;
  25192. /**
  25193. * The access type of the texture node.
  25194. *
  25195. * @type {string}
  25196. * @default 'writeOnly'
  25197. */
  25198. this.access = NodeAccess.WRITE_ONLY;
  25199. }
  25200. /**
  25201. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  25202. *
  25203. * @param {NodeBuilder} builder - The current node builder.
  25204. * @return {string} The input type.
  25205. */
  25206. getInputType( /*builder*/ ) {
  25207. return 'storageTexture';
  25208. }
  25209. setup( builder ) {
  25210. super.setup( builder );
  25211. const properties = builder.getNodeProperties( this );
  25212. properties.storeNode = this.storeNode;
  25213. return properties;
  25214. }
  25215. /**
  25216. * Defines the node access.
  25217. *
  25218. * @param {string} value - The node access.
  25219. * @return {StorageTextureNode} A reference to this node.
  25220. */
  25221. setAccess( value ) {
  25222. this.access = value;
  25223. return this;
  25224. }
  25225. /**
  25226. * Sets the mip level to write to.
  25227. *
  25228. * @param {number} level - The mip level.
  25229. * @return {StorageTextureNode} A reference to this node.
  25230. */
  25231. setMipLevel( level ) {
  25232. this.mipLevel = level;
  25233. return this;
  25234. }
  25235. /**
  25236. * Generates the code snippet of the storage node. If no `storeNode`
  25237. * is defined, the texture node is generated as normal texture.
  25238. *
  25239. * @param {NodeBuilder} builder - The current node builder.
  25240. * @param {string} output - The current output.
  25241. * @return {string} The generated code snippet.
  25242. */
  25243. generate( builder, output ) {
  25244. let snippet;
  25245. if ( this.storeNode !== null ) {
  25246. snippet = this.generateStore( builder );
  25247. } else {
  25248. snippet = super.generate( builder, output );
  25249. }
  25250. return snippet;
  25251. }
  25252. /**
  25253. * Convenience method for configuring a read/write node access.
  25254. *
  25255. * @return {StorageTextureNode} A reference to this node.
  25256. */
  25257. toReadWrite() {
  25258. return this.setAccess( NodeAccess.READ_WRITE );
  25259. }
  25260. /**
  25261. * Convenience method for configuring a read-only node access.
  25262. *
  25263. * @return {StorageTextureNode} A reference to this node.
  25264. */
  25265. toReadOnly() {
  25266. return this.setAccess( NodeAccess.READ_ONLY );
  25267. }
  25268. /**
  25269. * Convenience method for configuring a write-only node access.
  25270. *
  25271. * @return {StorageTextureNode} A reference to this node.
  25272. */
  25273. toWriteOnly() {
  25274. return this.setAccess( NodeAccess.WRITE_ONLY );
  25275. }
  25276. /**
  25277. * Generates the code snippet of the storage texture node.
  25278. *
  25279. * @param {NodeBuilder} builder - The current node builder.
  25280. */
  25281. generateStore( builder ) {
  25282. const properties = builder.getNodeProperties( this );
  25283. const { uvNode, storeNode, depthNode } = properties;
  25284. const textureProperty = super.generate( builder, 'property' );
  25285. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  25286. const storeSnippet = storeNode.build( builder, 'vec4' );
  25287. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  25288. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  25289. builder.addLineFlowCode( snippet, this );
  25290. }
  25291. clone() {
  25292. const newNode = super.clone();
  25293. newNode.storeNode = this.storeNode;
  25294. newNode.mipLevel = this.mipLevel;
  25295. return newNode;
  25296. }
  25297. }
  25298. /**
  25299. * TSL function for creating a storage texture node.
  25300. *
  25301. * @tsl
  25302. * @function
  25303. * @param {StorageTexture} value - The storage texture.
  25304. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  25305. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25306. * @returns {StorageTextureNode}
  25307. */
  25308. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  25309. /**
  25310. * TODO: Explain difference to `storageTexture()`.
  25311. *
  25312. * @tsl
  25313. * @function
  25314. * @param {StorageTexture} value - The storage texture.
  25315. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25316. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25317. * @returns {StorageTextureNode}
  25318. */
  25319. const textureStore = ( value, uvNode, storeNode ) => {
  25320. const node = storageTexture( value, uvNode, storeNode );
  25321. if ( storeNode !== null ) node.toStack();
  25322. return node;
  25323. };
  25324. const normal = Fn( ( { texture, uv } ) => {
  25325. const epsilon = 0.0001;
  25326. const ret = vec3().toVar();
  25327. If( uv.x.lessThan( epsilon ), () => {
  25328. ret.assign( vec3( 1, 0, 0 ) );
  25329. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  25330. ret.assign( vec3( 0, 1, 0 ) );
  25331. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  25332. ret.assign( vec3( 0, 0, 1 ) );
  25333. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  25334. ret.assign( vec3( -1, 0, 0 ) );
  25335. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  25336. ret.assign( vec3( 0, -1, 0 ) );
  25337. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  25338. ret.assign( vec3( 0, 0, -1 ) );
  25339. } ).Else( () => {
  25340. const step = 0.01;
  25341. 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 );
  25342. 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 );
  25343. 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 );
  25344. ret.assign( vec3( x, y, z ) );
  25345. } );
  25346. return ret.normalize();
  25347. } );
  25348. /**
  25349. * This type of uniform node represents a 3D texture.
  25350. *
  25351. * @augments TextureNode
  25352. */
  25353. class Texture3DNode extends TextureNode {
  25354. static get type() {
  25355. return 'Texture3DNode';
  25356. }
  25357. /**
  25358. * Constructs a new 3D texture node.
  25359. *
  25360. * @param {Data3DTexture} value - The 3D texture.
  25361. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25362. * @param {?Node<int>} [levelNode=null] - The level node.
  25363. */
  25364. constructor( value, uvNode = null, levelNode = null ) {
  25365. super( value, uvNode, levelNode );
  25366. /**
  25367. * This flag can be used for type testing.
  25368. *
  25369. * @type {boolean}
  25370. * @readonly
  25371. * @default true
  25372. */
  25373. this.isTexture3DNode = true;
  25374. }
  25375. /**
  25376. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  25377. *
  25378. * @param {NodeBuilder} builder - The current node builder.
  25379. * @return {string} The input type.
  25380. */
  25381. getInputType( /*builder*/ ) {
  25382. return 'texture3D';
  25383. }
  25384. /**
  25385. * Returns a default uv node which is in context of 3D textures a three-dimensional
  25386. * uv node.
  25387. *
  25388. * @return {Node<vec3>} The default uv node.
  25389. */
  25390. getDefaultUV() {
  25391. return vec3( 0.5, 0.5, 0.5 );
  25392. }
  25393. /**
  25394. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  25395. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  25396. *
  25397. * @param {boolean} value - The update toggle.
  25398. */
  25399. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  25400. /**
  25401. * Overwrites the default implementation to return the unmodified uv node.
  25402. *
  25403. * @param {NodeBuilder} builder - The current node builder.
  25404. * @param {Node} uvNode - The uv node to setup.
  25405. * @return {Node} The unmodified uv node.
  25406. */
  25407. setupUV( builder, uvNode ) {
  25408. const texture = this.value;
  25409. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25410. if ( this.sampler ) {
  25411. uvNode = uvNode.flipY();
  25412. } else {
  25413. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25414. }
  25415. }
  25416. return uvNode;
  25417. }
  25418. /**
  25419. * Generates the uv code snippet.
  25420. *
  25421. * @param {NodeBuilder} builder - The current node builder.
  25422. * @param {Node} uvNode - The uv node to generate code for.
  25423. * @return {string} The generated code snippet.
  25424. */
  25425. generateUV( builder, uvNode ) {
  25426. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25427. }
  25428. /**
  25429. * Generates the offset code snippet.
  25430. *
  25431. * @param {NodeBuilder} builder - The current node builder.
  25432. * @param {Node} offsetNode - The offset node to generate code for.
  25433. * @return {string} The generated code snippet.
  25434. */
  25435. generateOffset( builder, offsetNode ) {
  25436. return offsetNode.build( builder, 'ivec3' );
  25437. }
  25438. /**
  25439. * TODO.
  25440. *
  25441. * @param {Node<vec3>} uvNode - The uv node .
  25442. * @return {Node<vec3>} TODO.
  25443. */
  25444. normal( uvNode ) {
  25445. return normal( { texture: this, uv: uvNode } );
  25446. }
  25447. }
  25448. /**
  25449. * TSL function for creating a 3D texture node.
  25450. *
  25451. * @tsl
  25452. * @function
  25453. * @param {Data3DTexture} value - The 3D texture.
  25454. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25455. * @param {?Node<int>} [levelNode=null] - The level node.
  25456. * @returns {Texture3DNode}
  25457. */
  25458. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25459. /**
  25460. * A special type of reference node that allows to link values in
  25461. * `userData` fields to node objects.
  25462. * ```js
  25463. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25464. *
  25465. * const material = new THREE.SpriteNodeMaterial();
  25466. * material.rotationNode = userData( 'rotation', 'float' );
  25467. * ```
  25468. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25469. * will automatically be updated when the `rotation` user data field changes.
  25470. *
  25471. * @augments ReferenceNode
  25472. */
  25473. class UserDataNode extends ReferenceNode {
  25474. static get type() {
  25475. return 'UserDataNode';
  25476. }
  25477. /**
  25478. * Constructs a new user data node.
  25479. *
  25480. * @param {string} property - The property name that should be referenced by the node.
  25481. * @param {string} inputType - The node data type of the reference.
  25482. * @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.
  25483. */
  25484. constructor( property, inputType, userData = null ) {
  25485. super( property, inputType, userData );
  25486. /**
  25487. * A reference to the `userData` object. If not provided, the `userData`
  25488. * property of the 3D object that uses the node material is evaluated.
  25489. *
  25490. * @type {?Object}
  25491. * @default null
  25492. */
  25493. this.userData = userData;
  25494. }
  25495. /**
  25496. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25497. * `userData` field.
  25498. *
  25499. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25500. * @return {Object} A reference to the `userData` field.
  25501. */
  25502. updateReference( state ) {
  25503. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25504. return this.reference;
  25505. }
  25506. }
  25507. /**
  25508. * TSL function for creating a user data node.
  25509. *
  25510. * @tsl
  25511. * @function
  25512. * @param {string} name - The property name that should be referenced by the node.
  25513. * @param {string} inputType - The node data type of the reference.
  25514. * @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.
  25515. * @returns {UserDataNode}
  25516. */
  25517. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25518. const _objectData = new WeakMap();
  25519. /**
  25520. * A node for representing motion or velocity vectors. Foundation
  25521. * for advanced post processing effects like motion blur or TRAA.
  25522. *
  25523. * The node keeps track of the model, view and projection matrices
  25524. * of the previous frame and uses them to compute offsets in NDC space.
  25525. * These offsets represent the final velocity.
  25526. *
  25527. * @augments TempNode
  25528. */
  25529. class VelocityNode extends TempNode {
  25530. static get type() {
  25531. return 'VelocityNode';
  25532. }
  25533. /**
  25534. * Constructs a new vertex color node.
  25535. */
  25536. constructor() {
  25537. super( 'vec2' );
  25538. /**
  25539. * The current projection matrix.
  25540. *
  25541. * @type {?Matrix4}
  25542. * @default null
  25543. */
  25544. this.projectionMatrix = null;
  25545. /**
  25546. * Overwritten since velocity nodes are updated per object.
  25547. *
  25548. * @type {string}
  25549. * @default 'object'
  25550. */
  25551. this.updateType = NodeUpdateType.OBJECT;
  25552. /**
  25553. * Overwritten since velocity nodes save data after the update.
  25554. *
  25555. * @type {string}
  25556. * @default 'object'
  25557. */
  25558. this.updateAfterType = NodeUpdateType.OBJECT;
  25559. /**
  25560. * Uniform node representing the previous model matrix in world space.
  25561. *
  25562. * @type {UniformNode<mat4>}
  25563. * @default null
  25564. */
  25565. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25566. /**
  25567. * Uniform node representing the previous projection matrix.
  25568. *
  25569. * @type {UniformNode<mat4>}
  25570. * @default null
  25571. */
  25572. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25573. /**
  25574. * Uniform node representing the previous view matrix.
  25575. *
  25576. * @type {UniformNode<mat4>}
  25577. * @default null
  25578. */
  25579. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25580. }
  25581. /**
  25582. * Sets the given projection matrix.
  25583. *
  25584. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25585. */
  25586. setProjectionMatrix( projectionMatrix ) {
  25587. this.projectionMatrix = projectionMatrix;
  25588. }
  25589. /**
  25590. * Updates velocity specific uniforms.
  25591. *
  25592. * @param {NodeFrame} frame - A reference to the current node frame.
  25593. */
  25594. update( { frameId, camera, object } ) {
  25595. const previousModelMatrix = getPreviousMatrix( object );
  25596. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25597. //
  25598. const cameraData = getData( camera );
  25599. if ( cameraData.frameId !== frameId ) {
  25600. cameraData.frameId = frameId;
  25601. if ( cameraData.previousProjectionMatrix === undefined ) {
  25602. cameraData.previousProjectionMatrix = new Matrix4();
  25603. cameraData.previousCameraViewMatrix = new Matrix4();
  25604. cameraData.currentProjectionMatrix = new Matrix4();
  25605. cameraData.currentCameraViewMatrix = new Matrix4();
  25606. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25607. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25608. } else {
  25609. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25610. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25611. }
  25612. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25613. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25614. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25615. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25616. }
  25617. }
  25618. /**
  25619. * Overwritten to updated velocity specific uniforms.
  25620. *
  25621. * @param {NodeFrame} frame - A reference to the current node frame.
  25622. */
  25623. updateAfter( { object } ) {
  25624. getPreviousMatrix( object ).copy( object.matrixWorld );
  25625. }
  25626. /**
  25627. * Implements the velocity computation based on the previous and current vertex data.
  25628. *
  25629. * @param {NodeBuilder} builder - A reference to the current node builder.
  25630. * @return {Node<vec2>} The motion vector.
  25631. */
  25632. setup( /*builder*/ ) {
  25633. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25634. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25635. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25636. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25637. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25638. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25639. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25640. return velocity;
  25641. }
  25642. }
  25643. function getData( object ) {
  25644. let objectData = _objectData.get( object );
  25645. if ( objectData === undefined ) {
  25646. objectData = {};
  25647. _objectData.set( object, objectData );
  25648. }
  25649. return objectData;
  25650. }
  25651. function getPreviousMatrix( object, index = 0 ) {
  25652. const objectData = getData( object );
  25653. let matrix = objectData[ index ];
  25654. if ( matrix === undefined ) {
  25655. objectData[ index ] = matrix = new Matrix4();
  25656. objectData[ index ].copy( object.matrixWorld );
  25657. }
  25658. return matrix;
  25659. }
  25660. /**
  25661. * TSL object that represents the velocity of a render pass.
  25662. *
  25663. * @tsl
  25664. * @type {VelocityNode}
  25665. */
  25666. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25667. /**
  25668. * Computes a grayscale value for the given RGB color value.
  25669. *
  25670. * @tsl
  25671. * @function
  25672. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25673. * @return {Node<vec3>} The grayscale color.
  25674. */
  25675. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25676. return luminance( color.rgb );
  25677. } );
  25678. /**
  25679. * Super-saturates or desaturates the given RGB color.
  25680. *
  25681. * @tsl
  25682. * @function
  25683. * @param {Node<vec3>} color - The input color.
  25684. * @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.
  25685. * @return {Node<vec3>} The saturated color.
  25686. */
  25687. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25688. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25689. } );
  25690. /**
  25691. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25692. * in a more natural and visually appealing image with enhanced color depth
  25693. * compared to {@link ColorAdjustment#saturation}.
  25694. *
  25695. * @tsl
  25696. * @function
  25697. * @param {Node<vec3>} color - The input color.
  25698. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25699. * @return {Node<vec3>} The updated color.
  25700. */
  25701. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25702. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25703. const mx = color.r.max( color.g.max( color.b ) );
  25704. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25705. return mix( color.rgb, mx, amt );
  25706. } );
  25707. /**
  25708. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25709. *
  25710. * @tsl
  25711. * @function
  25712. * @param {Node<vec3>} color - The input color.
  25713. * @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.
  25714. * @return {Node<vec3>} The updated color.
  25715. */
  25716. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25717. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25718. const cosAngle = adjustment.cos();
  25719. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25720. } );
  25721. /**
  25722. * Computes the luminance for the given RGB color value.
  25723. *
  25724. * @tsl
  25725. * @function
  25726. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25727. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25728. * @return {Node<float>} The luminance.
  25729. */
  25730. const luminance = (
  25731. color,
  25732. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25733. ) => dot( color, luminanceCoefficients );
  25734. /**
  25735. * Color Decision List (CDL) v1.2
  25736. *
  25737. * Compact representation of color grading information, defined by slope, offset, power, and
  25738. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25739. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25740. *
  25741. * @tsl
  25742. * @function
  25743. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25744. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25745. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25746. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25747. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25748. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25749. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25750. *
  25751. * References:
  25752. * - ASC CDL v1.2
  25753. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25754. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25755. */
  25756. const cdl = /*@__PURE__*/ Fn( ( [
  25757. color,
  25758. slope = vec3( 1 ),
  25759. offset = vec3( 0 ),
  25760. power = vec3( 1 ),
  25761. saturation = float( 1 ),
  25762. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25763. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25764. ] ) => {
  25765. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25766. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25767. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25768. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25769. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25770. const pv = v.pow( power ).toVar();
  25771. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25772. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25773. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25774. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25775. return vec4( v.rgb, color.a );
  25776. } );
  25777. /**
  25778. * Represents a posterize effect which reduces the number of colors
  25779. * in an image, resulting in a more blocky and stylized appearance.
  25780. *
  25781. * @augments TempNode
  25782. */
  25783. class PosterizeNode extends TempNode {
  25784. static get type() {
  25785. return 'PosterizeNode';
  25786. }
  25787. /**
  25788. * Constructs a new posterize node.
  25789. *
  25790. * @param {Node} sourceNode - The input color.
  25791. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25792. */
  25793. constructor( sourceNode, stepsNode ) {
  25794. super();
  25795. /**
  25796. * The input color.
  25797. *
  25798. * @type {Node}
  25799. */
  25800. this.sourceNode = sourceNode;
  25801. /**
  25802. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25803. *
  25804. * @type {Node}
  25805. */
  25806. this.stepsNode = stepsNode;
  25807. }
  25808. setup() {
  25809. const { sourceNode, stepsNode } = this;
  25810. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25811. }
  25812. }
  25813. /**
  25814. * TSL function for creating a posterize node.
  25815. *
  25816. * @tsl
  25817. * @function
  25818. * @param {Node} sourceNode - The input color.
  25819. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25820. * @returns {PosterizeNode}
  25821. */
  25822. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25823. const _size = /*@__PURE__*/ new Vector2();
  25824. /**
  25825. * Represents the texture of a pass node.
  25826. *
  25827. * @augments TextureNode
  25828. */
  25829. class PassTextureNode extends TextureNode {
  25830. static get type() {
  25831. return 'PassTextureNode';
  25832. }
  25833. /**
  25834. * Constructs a new pass texture node.
  25835. *
  25836. * @param {PassNode} passNode - The pass node.
  25837. * @param {Texture} texture - The output texture.
  25838. */
  25839. constructor( passNode, texture ) {
  25840. super( texture );
  25841. /**
  25842. * A reference to the pass node.
  25843. *
  25844. * @type {PassNode}
  25845. */
  25846. this.passNode = passNode;
  25847. this.setUpdateMatrix( false );
  25848. }
  25849. setup( builder ) {
  25850. this.passNode.build( builder );
  25851. return super.setup( builder );
  25852. }
  25853. clone() {
  25854. return new this.constructor( this.passNode, this.value );
  25855. }
  25856. }
  25857. /**
  25858. * An extension of `PassTextureNode` which allows to manage more than one
  25859. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25860. *
  25861. * @augments PassTextureNode
  25862. */
  25863. class PassMultipleTextureNode extends PassTextureNode {
  25864. static get type() {
  25865. return 'PassMultipleTextureNode';
  25866. }
  25867. /**
  25868. * Constructs a new pass texture node.
  25869. *
  25870. * @param {PassNode} passNode - The pass node.
  25871. * @param {string} textureName - The output texture name.
  25872. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25873. */
  25874. constructor( passNode, textureName, previousTexture = false ) {
  25875. // null is passed to the super call since this class does not
  25876. // use an external texture for rendering pass data into. Instead
  25877. // the texture is managed by the pass node itself
  25878. super( passNode, null );
  25879. /**
  25880. * The output texture name.
  25881. *
  25882. * @type {string}
  25883. */
  25884. this.textureName = textureName;
  25885. /**
  25886. * Whether previous frame data should be used or not.
  25887. *
  25888. * @type {boolean}
  25889. */
  25890. this.previousTexture = previousTexture;
  25891. }
  25892. /**
  25893. * Updates the texture reference of this node.
  25894. */
  25895. updateTexture() {
  25896. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25897. }
  25898. setup( builder ) {
  25899. this.updateTexture();
  25900. return super.setup( builder );
  25901. }
  25902. clone() {
  25903. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25904. newNode.uvNode = this.uvNode;
  25905. newNode.levelNode = this.levelNode;
  25906. newNode.biasNode = this.biasNode;
  25907. newNode.sampler = this.sampler;
  25908. newNode.depthNode = this.depthNode;
  25909. newNode.compareNode = this.compareNode;
  25910. newNode.gradNode = this.gradNode;
  25911. newNode.offsetNode = this.offsetNode;
  25912. return newNode;
  25913. }
  25914. }
  25915. /**
  25916. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25917. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25918. * via MRT for further processing.
  25919. *
  25920. * ```js
  25921. * const postProcessing = new PostProcessing( renderer );
  25922. *
  25923. * const scenePass = pass( scene, camera );
  25924. *
  25925. * postProcessing.outputNode = scenePass;
  25926. * ```
  25927. *
  25928. * @augments TempNode
  25929. */
  25930. class PassNode extends TempNode {
  25931. static get type() {
  25932. return 'PassNode';
  25933. }
  25934. /**
  25935. * Constructs a new pass node.
  25936. *
  25937. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25938. * @param {Scene} scene - A reference to the scene.
  25939. * @param {Camera} camera - A reference to the camera.
  25940. * @param {Object} options - Options for the internal render target.
  25941. */
  25942. constructor( scope, scene, camera, options = {} ) {
  25943. super( 'vec4' );
  25944. /**
  25945. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25946. *
  25947. * @type {('color'|'depth')}
  25948. */
  25949. this.scope = scope;
  25950. /**
  25951. * A reference to the scene.
  25952. *
  25953. * @type {Scene}
  25954. */
  25955. this.scene = scene;
  25956. /**
  25957. * A reference to the camera.
  25958. *
  25959. * @type {Camera}
  25960. */
  25961. this.camera = camera;
  25962. /**
  25963. * Options for the internal render target.
  25964. *
  25965. * @type {Object}
  25966. */
  25967. this.options = options;
  25968. /**
  25969. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25970. *
  25971. * @private
  25972. * @type {number}
  25973. * @default 1
  25974. */
  25975. this._pixelRatio = 1;
  25976. /**
  25977. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25978. * @private
  25979. * @type {number}
  25980. * @default 1
  25981. */
  25982. this._width = 1;
  25983. /**
  25984. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25985. * @private
  25986. * @type {number}
  25987. * @default 1
  25988. */
  25989. this._height = 1;
  25990. const depthTexture = new DepthTexture();
  25991. depthTexture.isRenderTargetTexture = true;
  25992. //depthTexture.type = FloatType;
  25993. depthTexture.name = 'depth';
  25994. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25995. renderTarget.texture.name = 'output';
  25996. renderTarget.depthTexture = depthTexture;
  25997. /**
  25998. * The pass's render target.
  25999. *
  26000. * @type {RenderTarget}
  26001. */
  26002. this.renderTarget = renderTarget;
  26003. /**
  26004. * A dictionary holding the internal result textures.
  26005. *
  26006. * @private
  26007. * @type {Object<string, Texture>}
  26008. */
  26009. this._textures = {
  26010. output: renderTarget.texture,
  26011. depth: depthTexture
  26012. };
  26013. /**
  26014. * A dictionary holding the internal texture nodes.
  26015. *
  26016. * @private
  26017. * @type {Object<string, TextureNode>}
  26018. */
  26019. this._textureNodes = {};
  26020. /**
  26021. * A dictionary holding the internal depth nodes.
  26022. *
  26023. * @private
  26024. * @type {Object}
  26025. */
  26026. this._linearDepthNodes = {};
  26027. /**
  26028. * A dictionary holding the internal viewZ nodes.
  26029. *
  26030. * @private
  26031. * @type {Object}
  26032. */
  26033. this._viewZNodes = {};
  26034. /**
  26035. * A dictionary holding the texture data of the previous frame.
  26036. * Used for computing velocity/motion vectors.
  26037. *
  26038. * @private
  26039. * @type {Object<string, Texture>}
  26040. */
  26041. this._previousTextures = {};
  26042. /**
  26043. * A dictionary holding the texture nodes of the previous frame.
  26044. * Used for computing velocity/motion vectors.
  26045. *
  26046. * @private
  26047. * @type {Object<string, TextureNode>}
  26048. */
  26049. this._previousTextureNodes = {};
  26050. /**
  26051. * The `near` property of the camera as a uniform.
  26052. *
  26053. * @private
  26054. * @type {UniformNode}
  26055. */
  26056. this._cameraNear = uniform( 0 );
  26057. /**
  26058. * The `far` property of the camera as a uniform.
  26059. *
  26060. * @private
  26061. * @type {UniformNode}
  26062. */
  26063. this._cameraFar = uniform( 0 );
  26064. /**
  26065. * A MRT node configuring the MRT settings.
  26066. *
  26067. * @private
  26068. * @type {?MRTNode}
  26069. * @default null
  26070. */
  26071. this._mrt = null;
  26072. /**
  26073. * Layer object for configuring the camera that is used
  26074. * to produce the pass.
  26075. *
  26076. * @private
  26077. * @type {?Layers}
  26078. * @default null
  26079. */
  26080. this._layers = null;
  26081. /**
  26082. * Scales the resolution of the internal render target.
  26083. *
  26084. * @private
  26085. * @type {number}
  26086. * @default 1
  26087. */
  26088. this._resolutionScale = 1;
  26089. /**
  26090. * Custom viewport definition.
  26091. *
  26092. * @private
  26093. * @type {?Vector4}
  26094. * @default null
  26095. */
  26096. this._viewport = null;
  26097. /**
  26098. * Custom scissor definition.
  26099. *
  26100. * @private
  26101. * @type {?Vector4}
  26102. * @default null
  26103. */
  26104. this._scissor = null;
  26105. /**
  26106. * This flag can be used for type testing.
  26107. *
  26108. * @type {boolean}
  26109. * @readonly
  26110. * @default true
  26111. */
  26112. this.isPassNode = true;
  26113. /**
  26114. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  26115. * scene once per frame in its {@link PassNode#updateBefore} method.
  26116. *
  26117. * @type {string}
  26118. * @default 'frame'
  26119. */
  26120. this.updateBeforeType = NodeUpdateType.FRAME;
  26121. /**
  26122. * This flag is used for global cache.
  26123. *
  26124. * @type {boolean}
  26125. * @default true
  26126. */
  26127. this.global = true;
  26128. }
  26129. /**
  26130. * Sets the resolution scale for the pass.
  26131. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  26132. *
  26133. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  26134. * @return {PassNode} A reference to this pass.
  26135. */
  26136. setResolutionScale( resolutionScale ) {
  26137. this._resolutionScale = resolutionScale;
  26138. return this;
  26139. }
  26140. /**
  26141. * Gets the current resolution scale of the pass.
  26142. *
  26143. * @return {number} The current resolution scale. A value of `1` means full resolution.
  26144. */
  26145. getResolutionScale() {
  26146. return this._resolutionScale;
  26147. }
  26148. /**
  26149. * Sets the resolution for the pass.
  26150. * The resolution is a factor that is multiplied with the renderer's width and height.
  26151. *
  26152. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  26153. * @return {PassNode} A reference to this pass.
  26154. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  26155. */
  26156. setResolution( resolution ) { // @deprecated, r181
  26157. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  26158. return this.setResolutionScale( resolution );
  26159. }
  26160. /**
  26161. * Gets the current resolution of the pass.
  26162. *
  26163. * @return {number} The current resolution. A value of `1` means full resolution.
  26164. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  26165. */
  26166. getResolution() { // @deprecated, r181
  26167. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  26168. return this.getResolutionScale();
  26169. }
  26170. /**
  26171. * Sets the layer configuration that should be used when rendering the pass.
  26172. *
  26173. * @param {Layers} layers - The layers object to set.
  26174. * @return {PassNode} A reference to this pass.
  26175. */
  26176. setLayers( layers ) {
  26177. this._layers = layers;
  26178. return this;
  26179. }
  26180. /**
  26181. * Gets the current layer configuration of the pass.
  26182. *
  26183. * @return {?Layers} .
  26184. */
  26185. getLayers() {
  26186. return this._layers;
  26187. }
  26188. /**
  26189. * Sets the given MRT node to setup MRT for this pass.
  26190. *
  26191. * @param {MRTNode} mrt - The MRT object.
  26192. * @return {PassNode} A reference to this pass.
  26193. */
  26194. setMRT( mrt ) {
  26195. this._mrt = mrt;
  26196. return this;
  26197. }
  26198. /**
  26199. * Returns the current MRT node.
  26200. *
  26201. * @return {MRTNode} The current MRT node.
  26202. */
  26203. getMRT() {
  26204. return this._mrt;
  26205. }
  26206. /**
  26207. * Returns the texture for the given output name.
  26208. *
  26209. * @param {string} name - The output name to get the texture for.
  26210. * @return {Texture} The texture.
  26211. */
  26212. getTexture( name ) {
  26213. let texture = this._textures[ name ];
  26214. if ( texture === undefined ) {
  26215. const refTexture = this.renderTarget.texture;
  26216. texture = refTexture.clone();
  26217. texture.name = name;
  26218. this._textures[ name ] = texture;
  26219. this.renderTarget.textures.push( texture );
  26220. }
  26221. return texture;
  26222. }
  26223. /**
  26224. * Returns the texture holding the data of the previous frame for the given output name.
  26225. *
  26226. * @param {string} name - The output name to get the texture for.
  26227. * @return {Texture} The texture holding the data of the previous frame.
  26228. */
  26229. getPreviousTexture( name ) {
  26230. let texture = this._previousTextures[ name ];
  26231. if ( texture === undefined ) {
  26232. texture = this.getTexture( name ).clone();
  26233. this._previousTextures[ name ] = texture;
  26234. }
  26235. return texture;
  26236. }
  26237. /**
  26238. * Switches current and previous textures for the given output name.
  26239. *
  26240. * @param {string} name - The output name.
  26241. */
  26242. toggleTexture( name ) {
  26243. const prevTexture = this._previousTextures[ name ];
  26244. if ( prevTexture !== undefined ) {
  26245. const texture = this._textures[ name ];
  26246. const index = this.renderTarget.textures.indexOf( texture );
  26247. this.renderTarget.textures[ index ] = prevTexture;
  26248. this._textures[ name ] = prevTexture;
  26249. this._previousTextures[ name ] = texture;
  26250. this._textureNodes[ name ].updateTexture();
  26251. this._previousTextureNodes[ name ].updateTexture();
  26252. }
  26253. }
  26254. /**
  26255. * Returns the texture node for the given output name.
  26256. *
  26257. * @param {string} [name='output'] - The output name to get the texture node for.
  26258. * @return {TextureNode} The texture node.
  26259. */
  26260. getTextureNode( name = 'output' ) {
  26261. let textureNode = this._textureNodes[ name ];
  26262. if ( textureNode === undefined ) {
  26263. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  26264. textureNode.updateTexture();
  26265. this._textureNodes[ name ] = textureNode;
  26266. }
  26267. return textureNode;
  26268. }
  26269. /**
  26270. * Returns the previous texture node for the given output name.
  26271. *
  26272. * @param {string} [name='output'] - The output name to get the previous texture node for.
  26273. * @return {TextureNode} The previous texture node.
  26274. */
  26275. getPreviousTextureNode( name = 'output' ) {
  26276. let textureNode = this._previousTextureNodes[ name ];
  26277. if ( textureNode === undefined ) {
  26278. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  26279. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  26280. textureNode.updateTexture();
  26281. this._previousTextureNodes[ name ] = textureNode;
  26282. }
  26283. return textureNode;
  26284. }
  26285. /**
  26286. * Returns a viewZ node of this pass.
  26287. *
  26288. * @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.
  26289. * @return {Node} The viewZ node.
  26290. */
  26291. getViewZNode( name = 'depth' ) {
  26292. let viewZNode = this._viewZNodes[ name ];
  26293. if ( viewZNode === undefined ) {
  26294. const cameraNear = this._cameraNear;
  26295. const cameraFar = this._cameraFar;
  26296. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  26297. }
  26298. return viewZNode;
  26299. }
  26300. /**
  26301. * Returns a linear depth node of this pass.
  26302. *
  26303. * @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.
  26304. * @return {Node} The linear depth node.
  26305. */
  26306. getLinearDepthNode( name = 'depth' ) {
  26307. let linearDepthNode = this._linearDepthNodes[ name ];
  26308. if ( linearDepthNode === undefined ) {
  26309. const cameraNear = this._cameraNear;
  26310. const cameraFar = this._cameraFar;
  26311. const viewZNode = this.getViewZNode( name );
  26312. // TODO: just if ( builder.camera.isPerspectiveCamera )
  26313. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  26314. }
  26315. return linearDepthNode;
  26316. }
  26317. /**
  26318. * Precompiles the pass.
  26319. *
  26320. * Note that this method must be called after the pass configuration is complete.
  26321. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  26322. *
  26323. * @async
  26324. * @param {Renderer} renderer - The renderer.
  26325. * @return {Promise} A Promise that resolves when the compile has been finished.
  26326. * @see {@link Renderer#compileAsync}
  26327. */
  26328. async compileAsync( renderer ) {
  26329. const currentRenderTarget = renderer.getRenderTarget();
  26330. const currentMRT = renderer.getMRT();
  26331. renderer.setRenderTarget( this.renderTarget );
  26332. renderer.setMRT( this._mrt );
  26333. await renderer.compileAsync( this.scene, this.camera );
  26334. renderer.setRenderTarget( currentRenderTarget );
  26335. renderer.setMRT( currentMRT );
  26336. }
  26337. setup( { renderer } ) {
  26338. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  26339. this.renderTarget.texture.type = renderer.getColorBufferType();
  26340. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  26341. }
  26342. updateBefore( frame ) {
  26343. const { renderer } = frame;
  26344. const { scene } = this;
  26345. let camera;
  26346. let pixelRatio;
  26347. const outputRenderTarget = renderer.getOutputRenderTarget();
  26348. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  26349. pixelRatio = 1;
  26350. camera = renderer.xr.getCamera();
  26351. renderer.xr.updateCamera( camera );
  26352. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  26353. } else {
  26354. camera = this.camera;
  26355. pixelRatio = renderer.getPixelRatio();
  26356. renderer.getSize( _size );
  26357. }
  26358. this._pixelRatio = pixelRatio;
  26359. this.setSize( _size.width, _size.height );
  26360. const currentRenderTarget = renderer.getRenderTarget();
  26361. const currentMRT = renderer.getMRT();
  26362. const currentAutoClear = renderer.autoClear;
  26363. const currentMask = camera.layers.mask;
  26364. this._cameraNear.value = camera.near;
  26365. this._cameraFar.value = camera.far;
  26366. if ( this._layers !== null ) {
  26367. camera.layers.mask = this._layers.mask;
  26368. }
  26369. for ( const name in this._previousTextures ) {
  26370. this.toggleTexture( name );
  26371. }
  26372. renderer.setRenderTarget( this.renderTarget );
  26373. renderer.setMRT( this._mrt );
  26374. renderer.autoClear = true;
  26375. const currentSceneName = scene.name;
  26376. scene.name = this.name ? this.name : scene.name;
  26377. renderer.render( scene, camera );
  26378. scene.name = currentSceneName;
  26379. renderer.setRenderTarget( currentRenderTarget );
  26380. renderer.setMRT( currentMRT );
  26381. renderer.autoClear = currentAutoClear;
  26382. camera.layers.mask = currentMask;
  26383. }
  26384. /**
  26385. * Sets the size of the pass's render target. Honors the pixel ratio.
  26386. *
  26387. * @param {number} width - The width to set.
  26388. * @param {number} height - The height to set.
  26389. */
  26390. setSize( width, height ) {
  26391. this._width = width;
  26392. this._height = height;
  26393. const effectiveWidth = this._width * this._pixelRatio * this._resolutionScale;
  26394. const effectiveHeight = this._height * this._pixelRatio * this._resolutionScale;
  26395. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26396. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  26397. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  26398. }
  26399. /**
  26400. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  26401. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26402. * with `null` as the single argument.
  26403. *
  26404. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  26405. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  26406. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  26407. * @param {number} width - The width of the scissor box in logical pixel unit.
  26408. * @param {number} height - The height of the scissor box in logical pixel unit.
  26409. */
  26410. setScissor( x, y, width, height ) {
  26411. if ( x === null ) {
  26412. this._scissor = null;
  26413. } else {
  26414. if ( this._scissor === null ) this._scissor = new Vector4();
  26415. if ( x.isVector4 ) {
  26416. this._scissor.copy( x );
  26417. } else {
  26418. this._scissor.set( x, y, width, height );
  26419. }
  26420. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26421. }
  26422. }
  26423. /**
  26424. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  26425. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26426. * with `null` as the single argument.
  26427. *
  26428. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26429. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26430. * @param {number} width - The width of the viewport in logical pixel unit.
  26431. * @param {number} height - The height of the viewport in logical pixel unit.
  26432. */
  26433. setViewport( x, y, width, height ) {
  26434. if ( x === null ) {
  26435. this._viewport = null;
  26436. } else {
  26437. if ( this._viewport === null ) this._viewport = new Vector4();
  26438. if ( x.isVector4 ) {
  26439. this._viewport.copy( x );
  26440. } else {
  26441. this._viewport.set( x, y, width, height );
  26442. }
  26443. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26444. }
  26445. }
  26446. /**
  26447. * Sets the pixel ratio the pass's render target and updates the size.
  26448. *
  26449. * @param {number} pixelRatio - The pixel ratio to set.
  26450. */
  26451. setPixelRatio( pixelRatio ) {
  26452. this._pixelRatio = pixelRatio;
  26453. this.setSize( this._width, this._height );
  26454. }
  26455. /**
  26456. * Frees internal resources. Should be called when the node is no longer in use.
  26457. */
  26458. dispose() {
  26459. this.renderTarget.dispose();
  26460. }
  26461. }
  26462. /**
  26463. * @static
  26464. * @type {'color'}
  26465. * @default 'color'
  26466. */
  26467. PassNode.COLOR = 'color';
  26468. /**
  26469. * @static
  26470. * @type {'depth'}
  26471. * @default 'depth'
  26472. */
  26473. PassNode.DEPTH = 'depth';
  26474. /**
  26475. * TSL function for creating a pass node.
  26476. *
  26477. * @tsl
  26478. * @function
  26479. * @param {Scene} scene - A reference to the scene.
  26480. * @param {Camera} camera - A reference to the camera.
  26481. * @param {Object} options - Options for the internal render target.
  26482. * @returns {PassNode}
  26483. */
  26484. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26485. /**
  26486. * TSL function for creating a pass texture node.
  26487. *
  26488. * @tsl
  26489. * @function
  26490. * @param {PassNode} pass - The pass node.
  26491. * @param {Texture} texture - The output texture.
  26492. * @returns {PassTextureNode}
  26493. */
  26494. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26495. /**
  26496. * TSL function for creating a depth pass node.
  26497. *
  26498. * @tsl
  26499. * @function
  26500. * @param {Scene} scene - A reference to the scene.
  26501. * @param {Camera} camera - A reference to the camera.
  26502. * @param {Object} options - Options for the internal render target.
  26503. * @returns {PassNode}
  26504. */
  26505. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26506. /**
  26507. * Represents a render pass for producing a toon outline effect on compatible objects.
  26508. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26509. * will receive the outline.
  26510. *
  26511. * ```js
  26512. * const postProcessing = new PostProcessing( renderer );
  26513. *
  26514. * const scenePass = toonOutlinePass( scene, camera );
  26515. *
  26516. * postProcessing.outputNode = scenePass;
  26517. * ```
  26518. * @augments PassNode
  26519. */
  26520. class ToonOutlinePassNode extends PassNode {
  26521. static get type() {
  26522. return 'ToonOutlinePassNode';
  26523. }
  26524. /**
  26525. * Constructs a new outline pass node.
  26526. *
  26527. * @param {Scene} scene - A reference to the scene.
  26528. * @param {Camera} camera - A reference to the camera.
  26529. * @param {Node} colorNode - Defines the outline's color.
  26530. * @param {Node} thicknessNode - Defines the outline's thickness.
  26531. * @param {Node} alphaNode - Defines the outline's alpha.
  26532. */
  26533. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26534. super( PassNode.COLOR, scene, camera );
  26535. /**
  26536. * Defines the outline's color.
  26537. *
  26538. * @type {Node}
  26539. */
  26540. this.colorNode = colorNode;
  26541. /**
  26542. * Defines the outline's thickness.
  26543. *
  26544. * @type {Node}
  26545. */
  26546. this.thicknessNode = thicknessNode;
  26547. /**
  26548. * Defines the outline's alpha.
  26549. *
  26550. * @type {Node}
  26551. */
  26552. this.alphaNode = alphaNode;
  26553. /**
  26554. * An internal material cache.
  26555. *
  26556. * @private
  26557. * @type {WeakMap<Material, NodeMaterial>}
  26558. */
  26559. this._materialCache = new WeakMap();
  26560. /**
  26561. * The name of this pass.
  26562. *
  26563. * @type {string}
  26564. * @default 'Outline Pass'
  26565. */
  26566. this.name = 'Outline Pass';
  26567. }
  26568. updateBefore( frame ) {
  26569. const { renderer } = frame;
  26570. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26571. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26572. // only render outline for supported materials
  26573. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26574. if ( material.wireframe === false ) {
  26575. const outlineMaterial = this._getOutlineMaterial( material );
  26576. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26577. }
  26578. }
  26579. // default
  26580. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26581. } );
  26582. super.updateBefore( frame );
  26583. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26584. }
  26585. /**
  26586. * Creates the material used for outline rendering.
  26587. *
  26588. * @private
  26589. * @return {NodeMaterial} The outline material.
  26590. */
  26591. _createMaterial() {
  26592. const material = new NodeMaterial();
  26593. material.isMeshToonOutlineMaterial = true;
  26594. material.name = 'Toon_Outline';
  26595. material.side = BackSide;
  26596. // vertex node
  26597. const outlineNormal = normalLocal.negate();
  26598. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26599. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26600. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26601. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26602. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26603. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26604. // color node
  26605. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26606. return material;
  26607. }
  26608. /**
  26609. * For the given toon material, this method returns a corresponding
  26610. * outline material.
  26611. *
  26612. * @private
  26613. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26614. * @return {NodeMaterial} The outline material.
  26615. */
  26616. _getOutlineMaterial( originalMaterial ) {
  26617. let outlineMaterial = this._materialCache.get( originalMaterial );
  26618. if ( outlineMaterial === undefined ) {
  26619. outlineMaterial = this._createMaterial();
  26620. this._materialCache.set( originalMaterial, outlineMaterial );
  26621. }
  26622. return outlineMaterial;
  26623. }
  26624. }
  26625. /**
  26626. * TSL function for creating a toon outline pass node.
  26627. *
  26628. * @tsl
  26629. * @function
  26630. * @param {Scene} scene - A reference to the scene.
  26631. * @param {Camera} camera - A reference to the camera.
  26632. * @param {Color} color - Defines the outline's color.
  26633. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26634. * @param {number} [alpha=1] - Defines the outline's alpha.
  26635. * @returns {ToonOutlinePassNode}
  26636. */
  26637. 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 ) ) );
  26638. /**
  26639. * Linear tone mapping, exposure only.
  26640. *
  26641. * @tsl
  26642. * @function
  26643. * @param {Node<vec3>} color - The color that should be tone mapped.
  26644. * @param {Node<float>} exposure - The exposure.
  26645. * @return {Node<vec3>} The tone mapped color.
  26646. */
  26647. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26648. return color.mul( exposure ).clamp();
  26649. } ).setLayout( {
  26650. name: 'linearToneMapping',
  26651. type: 'vec3',
  26652. inputs: [
  26653. { name: 'color', type: 'vec3' },
  26654. { name: 'exposure', type: 'float' }
  26655. ]
  26656. } );
  26657. /**
  26658. * Reinhard tone mapping.
  26659. *
  26660. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26661. *
  26662. * @tsl
  26663. * @function
  26664. * @param {Node<vec3>} color - The color that should be tone mapped.
  26665. * @param {Node<float>} exposure - The exposure.
  26666. * @return {Node<vec3>} The tone mapped color.
  26667. */
  26668. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26669. color = color.mul( exposure );
  26670. return color.div( color.add( 1.0 ) ).clamp();
  26671. } ).setLayout( {
  26672. name: 'reinhardToneMapping',
  26673. type: 'vec3',
  26674. inputs: [
  26675. { name: 'color', type: 'vec3' },
  26676. { name: 'exposure', type: 'float' }
  26677. ]
  26678. } );
  26679. /**
  26680. * Cineon tone mapping.
  26681. *
  26682. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26683. *
  26684. * @tsl
  26685. * @function
  26686. * @param {Node<vec3>} color - The color that should be tone mapped.
  26687. * @param {Node<float>} exposure - The exposure.
  26688. * @return {Node<vec3>} The tone mapped color.
  26689. */
  26690. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26691. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26692. color = color.mul( exposure );
  26693. color = color.sub( 0.004 ).max( 0.0 );
  26694. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26695. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26696. return a.div( b ).pow( 2.2 );
  26697. } ).setLayout( {
  26698. name: 'cineonToneMapping',
  26699. type: 'vec3',
  26700. inputs: [
  26701. { name: 'color', type: 'vec3' },
  26702. { name: 'exposure', type: 'float' }
  26703. ]
  26704. } );
  26705. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26706. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26707. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26708. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26709. return a.div( b );
  26710. } );
  26711. /**
  26712. * ACESFilmic tone mapping.
  26713. *
  26714. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26715. *
  26716. * @tsl
  26717. * @function
  26718. * @param {Node<vec3>} color - The color that should be tone mapped.
  26719. * @param {Node<float>} exposure - The exposure.
  26720. * @return {Node<vec3>} The tone mapped color.
  26721. */
  26722. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26723. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26724. const ACESInputMat = mat3(
  26725. 0.59719, 0.35458, 0.04823,
  26726. 0.07600, 0.90834, 0.01566,
  26727. 0.02840, 0.13383, 0.83777
  26728. );
  26729. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26730. const ACESOutputMat = mat3(
  26731. 1.60475, -0.53108, -0.07367,
  26732. -0.10208, 1.10813, -605e-5,
  26733. -327e-5, -0.07276, 1.07602
  26734. );
  26735. color = color.mul( exposure ).div( 0.6 );
  26736. color = ACESInputMat.mul( color );
  26737. // Apply RRT and ODT
  26738. color = RRTAndODTFit( color );
  26739. color = ACESOutputMat.mul( color );
  26740. // Clamp to [0, 1]
  26741. return color.clamp();
  26742. } ).setLayout( {
  26743. name: 'acesFilmicToneMapping',
  26744. type: 'vec3',
  26745. inputs: [
  26746. { name: 'color', type: 'vec3' },
  26747. { name: 'exposure', type: 'float' }
  26748. ]
  26749. } );
  26750. 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 ) );
  26751. 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 ) );
  26752. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26753. const x = vec3( x_immutable ).toVar();
  26754. const x2 = vec3( x.mul( x ) ).toVar();
  26755. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26756. 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 ) ) ) );
  26757. } );
  26758. /**
  26759. * AgX tone mapping.
  26760. *
  26761. * @tsl
  26762. * @function
  26763. * @param {Node<vec3>} color - The color that should be tone mapped.
  26764. * @param {Node<float>} exposure - The exposure.
  26765. * @return {Node<vec3>} The tone mapped color.
  26766. */
  26767. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26768. const colortone = vec3( color ).toVar();
  26769. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26770. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26771. const AgxMinEv = float( -12.47393 );
  26772. const AgxMaxEv = float( 4.026069 );
  26773. colortone.mulAssign( exposure );
  26774. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26775. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26776. colortone.assign( max$1( colortone, 1e-10 ) );
  26777. colortone.assign( log2( colortone ) );
  26778. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26779. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26780. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26781. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26782. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26783. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26784. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26785. return colortone;
  26786. } ).setLayout( {
  26787. name: 'agxToneMapping',
  26788. type: 'vec3',
  26789. inputs: [
  26790. { name: 'color', type: 'vec3' },
  26791. { name: 'exposure', type: 'float' }
  26792. ]
  26793. } );
  26794. /**
  26795. * Neutral tone mapping.
  26796. *
  26797. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26798. *
  26799. * @tsl
  26800. * @function
  26801. * @param {Node<vec3>} color - The color that should be tone mapped.
  26802. * @param {Node<float>} exposure - The exposure.
  26803. * @return {Node<vec3>} The tone mapped color.
  26804. */
  26805. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26806. const StartCompression = float( 0.8 - 0.04 );
  26807. const Desaturation = float( 0.15 );
  26808. color = color.mul( exposure );
  26809. const x = min$1( color.r, min$1( color.g, color.b ) );
  26810. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26811. color.subAssign( offset );
  26812. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26813. If( peak.lessThan( StartCompression ), () => {
  26814. return color;
  26815. } );
  26816. const d = sub( 1, StartCompression );
  26817. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26818. color.mulAssign( newPeak.div( peak ) );
  26819. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26820. return mix( color, vec3( newPeak ), g );
  26821. } ).setLayout( {
  26822. name: 'neutralToneMapping',
  26823. type: 'vec3',
  26824. inputs: [
  26825. { name: 'color', type: 'vec3' },
  26826. { name: 'exposure', type: 'float' }
  26827. ]
  26828. } );
  26829. /**
  26830. * This class represents native code sections. It is the base
  26831. * class for modules like {@link FunctionNode} which allows to implement
  26832. * functions with native shader languages.
  26833. *
  26834. * @augments Node
  26835. */
  26836. class CodeNode extends Node {
  26837. static get type() {
  26838. return 'CodeNode';
  26839. }
  26840. /**
  26841. * Constructs a new code node.
  26842. *
  26843. * @param {string} [code=''] - The native code.
  26844. * @param {Array<Node>} [includes=[]] - An array of includes.
  26845. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26846. */
  26847. constructor( code = '', includes = [], language = '' ) {
  26848. super( 'code' );
  26849. /**
  26850. * This flag can be used for type testing.
  26851. *
  26852. * @type {boolean}
  26853. * @readonly
  26854. * @default true
  26855. */
  26856. this.isCodeNode = true;
  26857. /**
  26858. * This flag is used for global cache.
  26859. *
  26860. * @type {boolean}
  26861. * @default true
  26862. */
  26863. this.global = true;
  26864. /**
  26865. * The native code.
  26866. *
  26867. * @type {string}
  26868. * @default ''
  26869. */
  26870. this.code = code;
  26871. /**
  26872. * An array of includes
  26873. *
  26874. * @type {Array<Node>}
  26875. * @default []
  26876. */
  26877. this.includes = includes;
  26878. /**
  26879. * The used language.
  26880. *
  26881. * @type {('js'|'wgsl'|'glsl')}
  26882. * @default ''
  26883. */
  26884. this.language = language;
  26885. }
  26886. /**
  26887. * Sets the includes of this code node.
  26888. *
  26889. * @param {Array<Node>} includes - The includes to set.
  26890. * @return {CodeNode} A reference to this node.
  26891. */
  26892. setIncludes( includes ) {
  26893. this.includes = includes;
  26894. return this;
  26895. }
  26896. /**
  26897. * Returns the includes of this code node.
  26898. *
  26899. * @param {NodeBuilder} builder - The current node builder.
  26900. * @return {Array<Node>} The includes.
  26901. */
  26902. getIncludes( /*builder*/ ) {
  26903. return this.includes;
  26904. }
  26905. generate( builder ) {
  26906. const includes = this.getIncludes( builder );
  26907. for ( const include of includes ) {
  26908. include.build( builder );
  26909. }
  26910. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26911. nodeCode.code = this.code;
  26912. return nodeCode.code;
  26913. }
  26914. serialize( data ) {
  26915. super.serialize( data );
  26916. data.code = this.code;
  26917. data.language = this.language;
  26918. }
  26919. deserialize( data ) {
  26920. super.deserialize( data );
  26921. this.code = data.code;
  26922. this.language = data.language;
  26923. }
  26924. }
  26925. /**
  26926. * TSL function for creating a code node.
  26927. *
  26928. * @tsl
  26929. * @function
  26930. * @param {string} [code] - The native code.
  26931. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26932. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26933. * @returns {CodeNode}
  26934. */
  26935. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26936. /**
  26937. * TSL function for creating a JS code node.
  26938. *
  26939. * @tsl
  26940. * @function
  26941. * @param {string} src - The native code.
  26942. * @param {Array<Node>} includes - An array of includes.
  26943. * @returns {CodeNode}
  26944. */
  26945. const js = ( src, includes ) => code( src, includes, 'js' );
  26946. /**
  26947. * TSL function for creating a WGSL code node.
  26948. *
  26949. * @tsl
  26950. * @function
  26951. * @param {string} src - The native code.
  26952. * @param {Array<Node>} includes - An array of includes.
  26953. * @returns {CodeNode}
  26954. */
  26955. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26956. /**
  26957. * TSL function for creating a GLSL code node.
  26958. *
  26959. * @tsl
  26960. * @function
  26961. * @param {string} src - The native code.
  26962. * @param {Array<Node>} includes - An array of includes.
  26963. * @returns {CodeNode}
  26964. */
  26965. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26966. /**
  26967. * This class represents a native shader function. It can be used to implement
  26968. * certain aspects of a node material with native shader code. There are two predefined
  26969. * TSL functions for easier usage.
  26970. *
  26971. * - `wgslFn`: Creates a WGSL function node.
  26972. * - `glslFn`: Creates a GLSL function node.
  26973. *
  26974. * A basic example with one include looks like so:
  26975. *
  26976. * ```js
  26977. * const desaturateWGSLFn = wgslFn( `
  26978. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26979. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26980. * return vec3<f32>( dot( lum, color ) );
  26981. * }`
  26982. *);
  26983. * const someWGSLFn = wgslFn( `
  26984. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26985. * return desaturate( color );
  26986. * }
  26987. * `, [ desaturateWGSLFn ] );
  26988. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26989. *```
  26990. * @augments CodeNode
  26991. */
  26992. class FunctionNode extends CodeNode {
  26993. static get type() {
  26994. return 'FunctionNode';
  26995. }
  26996. /**
  26997. * Constructs a new function node.
  26998. *
  26999. * @param {string} [code=''] - The native code.
  27000. * @param {Array<Node>} [includes=[]] - An array of includes.
  27001. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27002. */
  27003. constructor( code = '', includes = [], language = '' ) {
  27004. super( code, includes, language );
  27005. }
  27006. /**
  27007. * Returns the type of this function node.
  27008. *
  27009. * @param {NodeBuilder} builder - The current node builder.
  27010. * @return {string} The type.
  27011. */
  27012. getNodeType( builder ) {
  27013. return this.getNodeFunction( builder ).type;
  27014. }
  27015. /**
  27016. * Returns the type of a member of this function node.
  27017. *
  27018. * @param {NodeBuilder} builder - The current node builder.
  27019. * @param {string} name - The name of the member.
  27020. * @return {string} The type of the member.
  27021. */
  27022. getMemberType( builder, name ) {
  27023. const type = this.getNodeType( builder );
  27024. const structType = builder.getStructTypeNode( type );
  27025. return structType.getMemberType( builder, name );
  27026. }
  27027. /**
  27028. * Returns the inputs of this function node.
  27029. *
  27030. * @param {NodeBuilder} builder - The current node builder.
  27031. * @return {Array<NodeFunctionInput>} The inputs.
  27032. */
  27033. getInputs( builder ) {
  27034. return this.getNodeFunction( builder ).inputs;
  27035. }
  27036. /**
  27037. * Returns the node function for this function node.
  27038. *
  27039. * @param {NodeBuilder} builder - The current node builder.
  27040. * @return {NodeFunction} The node function.
  27041. */
  27042. getNodeFunction( builder ) {
  27043. const nodeData = builder.getDataFromNode( this );
  27044. let nodeFunction = nodeData.nodeFunction;
  27045. if ( nodeFunction === undefined ) {
  27046. nodeFunction = builder.parser.parseFunction( this.code );
  27047. nodeData.nodeFunction = nodeFunction;
  27048. }
  27049. return nodeFunction;
  27050. }
  27051. generate( builder, output ) {
  27052. super.generate( builder );
  27053. const nodeFunction = this.getNodeFunction( builder );
  27054. const name = nodeFunction.name;
  27055. const type = nodeFunction.type;
  27056. const nodeCode = builder.getCodeFromNode( this, type );
  27057. if ( name !== '' ) {
  27058. // use a custom property name
  27059. nodeCode.name = name;
  27060. }
  27061. const propertyName = builder.getPropertyName( nodeCode );
  27062. const code = this.getNodeFunction( builder ).getCode( propertyName );
  27063. nodeCode.code = code + '\n';
  27064. if ( output === 'property' ) {
  27065. return propertyName;
  27066. } else {
  27067. return builder.format( `${ propertyName }()`, type, output );
  27068. }
  27069. }
  27070. }
  27071. const nativeFn = ( code, includes = [], language = '' ) => {
  27072. for ( let i = 0; i < includes.length; i ++ ) {
  27073. const include = includes[ i ];
  27074. // TSL Function: glslFn, wgslFn
  27075. if ( typeof include === 'function' ) {
  27076. includes[ i ] = include.functionNode;
  27077. }
  27078. }
  27079. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  27080. const fn = ( ...params ) => functionNode.call( ...params );
  27081. fn.functionNode = functionNode;
  27082. return fn;
  27083. };
  27084. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  27085. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  27086. /**
  27087. * `ScriptableNode` uses this class to manage script inputs and outputs.
  27088. *
  27089. * @augments Node
  27090. */
  27091. class ScriptableValueNode extends Node {
  27092. static get type() {
  27093. return 'ScriptableValueNode';
  27094. }
  27095. /**
  27096. * Constructs a new scriptable node.
  27097. *
  27098. * @param {any} [value=null] - The value.
  27099. */
  27100. constructor( value = null ) {
  27101. super();
  27102. /**
  27103. * A reference to the value.
  27104. *
  27105. * @private
  27106. * @default null
  27107. */
  27108. this._value = value;
  27109. /**
  27110. * Depending on the type of `_value`, this property might cache parsed data.
  27111. *
  27112. * @private
  27113. * @default null
  27114. */
  27115. this._cache = null;
  27116. /**
  27117. * If this node represents an input, this property represents the input type.
  27118. *
  27119. * @type {?string}
  27120. * @default null
  27121. */
  27122. this.inputType = null;
  27123. /**
  27124. * If this node represents an output, this property represents the output type.
  27125. *
  27126. * @type {?string}
  27127. * @default null
  27128. */
  27129. this.outputType = null;
  27130. /**
  27131. * An event dispatcher for managing events.
  27132. *
  27133. * @type {EventDispatcher}
  27134. */
  27135. this.events = new EventDispatcher();
  27136. /**
  27137. * This flag can be used for type testing.
  27138. *
  27139. * @type {boolean}
  27140. * @readonly
  27141. * @default true
  27142. */
  27143. this.isScriptableValueNode = true;
  27144. }
  27145. /**
  27146. * Whether this node represents an output or not.
  27147. *
  27148. * @type {boolean}
  27149. * @readonly
  27150. * @default true
  27151. */
  27152. get isScriptableOutputNode() {
  27153. return this.outputType !== null;
  27154. }
  27155. set value( val ) {
  27156. if ( this._value === val ) return;
  27157. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  27158. URL.revokeObjectURL( this._cache );
  27159. this._cache = null;
  27160. }
  27161. this._value = val;
  27162. this.events.dispatchEvent( { type: 'change' } );
  27163. this.refresh();
  27164. }
  27165. /**
  27166. * The node's value.
  27167. *
  27168. * @type {any}
  27169. */
  27170. get value() {
  27171. return this._value;
  27172. }
  27173. /**
  27174. * Dispatches the `refresh` event.
  27175. */
  27176. refresh() {
  27177. this.events.dispatchEvent( { type: 'refresh' } );
  27178. }
  27179. /**
  27180. * The `value` property usually represents a node or even binary data in form of array buffers.
  27181. * In this case, this method tries to return the actual value behind the complex type.
  27182. *
  27183. * @return {any} The value.
  27184. */
  27185. getValue() {
  27186. const value = this.value;
  27187. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  27188. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  27189. } else if ( value && value.value !== null && value.value !== undefined && (
  27190. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  27191. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  27192. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  27193. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  27194. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  27195. ( this.inputType === 'Color' && value.value.isColor ) ||
  27196. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  27197. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  27198. ) ) {
  27199. return value.value;
  27200. }
  27201. return this._cache || value;
  27202. }
  27203. /**
  27204. * Overwritten since the node type is inferred from the value.
  27205. *
  27206. * @param {NodeBuilder} builder - The current node builder.
  27207. * @return {string} The node type.
  27208. */
  27209. getNodeType( builder ) {
  27210. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  27211. }
  27212. setup() {
  27213. return this.value && this.value.isNode ? this.value : float();
  27214. }
  27215. serialize( data ) {
  27216. super.serialize( data );
  27217. if ( this.value !== null ) {
  27218. if ( this.inputType === 'ArrayBuffer' ) {
  27219. data.value = arrayBufferToBase64( this.value );
  27220. } else {
  27221. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  27222. }
  27223. } else {
  27224. data.value = null;
  27225. }
  27226. data.inputType = this.inputType;
  27227. data.outputType = this.outputType;
  27228. }
  27229. deserialize( data ) {
  27230. super.deserialize( data );
  27231. let value = null;
  27232. if ( data.value !== null ) {
  27233. if ( data.inputType === 'ArrayBuffer' ) {
  27234. value = base64ToArrayBuffer( data.value );
  27235. } else if ( data.inputType === 'Texture' ) {
  27236. value = data.meta.textures[ data.value ];
  27237. } else {
  27238. value = data.meta.nodes[ data.value ] || null;
  27239. }
  27240. }
  27241. this.value = value;
  27242. this.inputType = data.inputType;
  27243. this.outputType = data.outputType;
  27244. }
  27245. }
  27246. /**
  27247. * TSL function for creating a scriptable value node.
  27248. *
  27249. * @tsl
  27250. * @function
  27251. * @param {any} [value] - The value.
  27252. * @returns {ScriptableValueNode}
  27253. */
  27254. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  27255. /**
  27256. * A Map-like data structure for managing resources of scriptable nodes.
  27257. *
  27258. * @augments Map
  27259. */
  27260. class Resources extends Map {
  27261. get( key, callback = null, ...params ) {
  27262. if ( this.has( key ) ) return super.get( key );
  27263. if ( callback !== null ) {
  27264. const value = callback( ...params );
  27265. this.set( key, value );
  27266. return value;
  27267. }
  27268. }
  27269. }
  27270. class Parameters {
  27271. constructor( scriptableNode ) {
  27272. this.scriptableNode = scriptableNode;
  27273. }
  27274. get parameters() {
  27275. return this.scriptableNode.parameters;
  27276. }
  27277. get layout() {
  27278. return this.scriptableNode.getLayout();
  27279. }
  27280. getInputLayout( id ) {
  27281. return this.scriptableNode.getInputLayout( id );
  27282. }
  27283. get( name ) {
  27284. const param = this.parameters[ name ];
  27285. const value = param ? param.getValue() : null;
  27286. return value;
  27287. }
  27288. }
  27289. /**
  27290. * Defines the resources (e.g. namespaces) of scriptable nodes.
  27291. *
  27292. * @type {Resources}
  27293. */
  27294. const ScriptableNodeResources = new Resources();
  27295. /**
  27296. * This type of node allows to implement nodes with custom scripts. The script
  27297. * section is represented as an instance of `CodeNode` written with JavaScript.
  27298. * The script itself must adhere to a specific structure.
  27299. *
  27300. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  27301. * - layout: The layout object defines the script's interface (inputs and outputs).
  27302. *
  27303. * ```js
  27304. * ScriptableNodeResources.set( 'TSL', TSL );
  27305. *
  27306. * const scriptableNode = scriptable( js( `
  27307. * layout = {
  27308. * outputType: 'node',
  27309. * elements: [
  27310. * { name: 'source', inputType: 'node' },
  27311. * ]
  27312. * };
  27313. *
  27314. * const { mul, oscSine } = TSL;
  27315. *
  27316. * function main() {
  27317. * const source = parameters.get( 'source' ) || float();
  27318. * return mul( source, oscSine() ) );
  27319. * }
  27320. *
  27321. * ` ) );
  27322. *
  27323. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  27324. *
  27325. * const material = new THREE.MeshBasicNodeMaterial();
  27326. * material.colorNode = scriptableNode;
  27327. * ```
  27328. *
  27329. * @augments Node
  27330. */
  27331. class ScriptableNode extends Node {
  27332. static get type() {
  27333. return 'ScriptableNode';
  27334. }
  27335. /**
  27336. * Constructs a new scriptable node.
  27337. *
  27338. * @param {?CodeNode} [codeNode=null] - The code node.
  27339. * @param {Object} [parameters={}] - The parameters definition.
  27340. */
  27341. constructor( codeNode = null, parameters = {} ) {
  27342. super();
  27343. /**
  27344. * The code node.
  27345. *
  27346. * @type {?CodeNode}
  27347. * @default null
  27348. */
  27349. this.codeNode = codeNode;
  27350. /**
  27351. * The parameters definition.
  27352. *
  27353. * @type {Object}
  27354. * @default {}
  27355. */
  27356. this.parameters = parameters;
  27357. this._local = new Resources();
  27358. this._output = scriptableValue( null );
  27359. this._outputs = {};
  27360. this._source = this.source;
  27361. this._method = null;
  27362. this._object = null;
  27363. this._value = null;
  27364. this._needsOutputUpdate = true;
  27365. this.onRefresh = this.onRefresh.bind( this );
  27366. /**
  27367. * This flag can be used for type testing.
  27368. *
  27369. * @type {boolean}
  27370. * @readonly
  27371. * @default true
  27372. */
  27373. this.isScriptableNode = true;
  27374. }
  27375. /**
  27376. * The source code of the scriptable node.
  27377. *
  27378. * @type {string}
  27379. */
  27380. get source() {
  27381. return this.codeNode ? this.codeNode.code : '';
  27382. }
  27383. /**
  27384. * Sets the reference of a local script variable.
  27385. *
  27386. * @param {string} name - The variable name.
  27387. * @param {Object} value - The reference to set.
  27388. * @return {Resources} The resource map
  27389. */
  27390. setLocal( name, value ) {
  27391. return this._local.set( name, value );
  27392. }
  27393. /**
  27394. * Gets the value of a local script variable.
  27395. *
  27396. * @param {string} name - The variable name.
  27397. * @return {Object} The value.
  27398. */
  27399. getLocal( name ) {
  27400. return this._local.get( name );
  27401. }
  27402. /**
  27403. * Event listener for the `refresh` event.
  27404. */
  27405. onRefresh() {
  27406. this._refresh();
  27407. }
  27408. /**
  27409. * Returns an input from the layout with the given id/name.
  27410. *
  27411. * @param {string} id - The id/name of the input.
  27412. * @return {Object} The element entry.
  27413. */
  27414. getInputLayout( id ) {
  27415. for ( const element of this.getLayout() ) {
  27416. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  27417. return element;
  27418. }
  27419. }
  27420. }
  27421. /**
  27422. * Returns an output from the layout with the given id/name.
  27423. *
  27424. * @param {string} id - The id/name of the output.
  27425. * @return {Object} The element entry.
  27426. */
  27427. getOutputLayout( id ) {
  27428. for ( const element of this.getLayout() ) {
  27429. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  27430. return element;
  27431. }
  27432. }
  27433. }
  27434. /**
  27435. * Defines a script output for the given name and value.
  27436. *
  27437. * @param {string} name - The name of the output.
  27438. * @param {Node} value - The node value.
  27439. * @return {ScriptableNode} A reference to this node.
  27440. */
  27441. setOutput( name, value ) {
  27442. const outputs = this._outputs;
  27443. if ( outputs[ name ] === undefined ) {
  27444. outputs[ name ] = scriptableValue( value );
  27445. } else {
  27446. outputs[ name ].value = value;
  27447. }
  27448. return this;
  27449. }
  27450. /**
  27451. * Returns a script output for the given name.
  27452. *
  27453. * @param {string} name - The name of the output.
  27454. * @return {ScriptableValueNode} The node value.
  27455. */
  27456. getOutput( name ) {
  27457. return this._outputs[ name ];
  27458. }
  27459. /**
  27460. * Returns a parameter for the given name
  27461. *
  27462. * @param {string} name - The name of the parameter.
  27463. * @return {ScriptableValueNode} The node value.
  27464. */
  27465. getParameter( name ) {
  27466. return this.parameters[ name ];
  27467. }
  27468. /**
  27469. * Sets a value for the given parameter name.
  27470. *
  27471. * @param {string} name - The parameter name.
  27472. * @param {any} value - The parameter value.
  27473. * @return {ScriptableNode} A reference to this node.
  27474. */
  27475. setParameter( name, value ) {
  27476. const parameters = this.parameters;
  27477. if ( value && value.isScriptableNode ) {
  27478. this.deleteParameter( name );
  27479. parameters[ name ] = value;
  27480. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27481. } else if ( value && value.isScriptableValueNode ) {
  27482. this.deleteParameter( name );
  27483. parameters[ name ] = value;
  27484. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27485. } else if ( parameters[ name ] === undefined ) {
  27486. parameters[ name ] = scriptableValue( value );
  27487. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27488. } else {
  27489. parameters[ name ].value = value;
  27490. }
  27491. return this;
  27492. }
  27493. /**
  27494. * Returns the value of this node which is the value of
  27495. * the default output.
  27496. *
  27497. * @return {Node} The value.
  27498. */
  27499. getValue() {
  27500. return this.getDefaultOutput().getValue();
  27501. }
  27502. /**
  27503. * Deletes a parameter from the script.
  27504. *
  27505. * @param {string} name - The parameter to remove.
  27506. * @return {ScriptableNode} A reference to this node.
  27507. */
  27508. deleteParameter( name ) {
  27509. let valueNode = this.parameters[ name ];
  27510. if ( valueNode ) {
  27511. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27512. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27513. }
  27514. return this;
  27515. }
  27516. /**
  27517. * Deletes all parameters from the script.
  27518. *
  27519. * @return {ScriptableNode} A reference to this node.
  27520. */
  27521. clearParameters() {
  27522. for ( const name of Object.keys( this.parameters ) ) {
  27523. this.deleteParameter( name );
  27524. }
  27525. this.needsUpdate = true;
  27526. return this;
  27527. }
  27528. /**
  27529. * Calls a function from the script.
  27530. *
  27531. * @param {string} name - The function name.
  27532. * @param {...any} params - A list of parameters.
  27533. * @return {any} The result of the function call.
  27534. */
  27535. call( name, ...params ) {
  27536. const object = this.getObject();
  27537. const method = object[ name ];
  27538. if ( typeof method === 'function' ) {
  27539. return method( ...params );
  27540. }
  27541. }
  27542. /**
  27543. * Asynchronously calls a function from the script.
  27544. *
  27545. * @param {string} name - The function name.
  27546. * @param {...any} params - A list of parameters.
  27547. * @return {Promise<any>} The result of the function call.
  27548. */
  27549. async callAsync( name, ...params ) {
  27550. const object = this.getObject();
  27551. const method = object[ name ];
  27552. if ( typeof method === 'function' ) {
  27553. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27554. }
  27555. }
  27556. /**
  27557. * Overwritten since the node types is inferred from the script's output.
  27558. *
  27559. * @param {NodeBuilder} builder - The current node builder
  27560. * @return {string} The node type.
  27561. */
  27562. getNodeType( builder ) {
  27563. return this.getDefaultOutputNode().getNodeType( builder );
  27564. }
  27565. /**
  27566. * Refreshes the script node.
  27567. *
  27568. * @param {?string} [output=null] - An optional output.
  27569. */
  27570. refresh( output = null ) {
  27571. if ( output !== null ) {
  27572. this.getOutput( output ).refresh();
  27573. } else {
  27574. this._refresh();
  27575. }
  27576. }
  27577. /**
  27578. * Returns an object representation of the script.
  27579. *
  27580. * @return {Object} The result object.
  27581. */
  27582. getObject() {
  27583. if ( this.needsUpdate ) this.dispose();
  27584. if ( this._object !== null ) return this._object;
  27585. //
  27586. const refresh = () => this.refresh();
  27587. const setOutput = ( id, value ) => this.setOutput( id, value );
  27588. const parameters = new Parameters( this );
  27589. const THREE = ScriptableNodeResources.get( 'THREE' );
  27590. const TSL = ScriptableNodeResources.get( 'TSL' );
  27591. const method = this.getMethod();
  27592. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27593. this._object = method( ...params );
  27594. const layout = this._object.layout;
  27595. if ( layout ) {
  27596. if ( layout.cache === false ) {
  27597. this._local.clear();
  27598. }
  27599. // default output
  27600. this._output.outputType = layout.outputType || null;
  27601. if ( Array.isArray( layout.elements ) ) {
  27602. for ( const element of layout.elements ) {
  27603. const id = element.id || element.name;
  27604. if ( element.inputType ) {
  27605. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27606. this.getParameter( id ).inputType = element.inputType;
  27607. }
  27608. if ( element.outputType ) {
  27609. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27610. this.getOutput( id ).outputType = element.outputType;
  27611. }
  27612. }
  27613. }
  27614. }
  27615. return this._object;
  27616. }
  27617. deserialize( data ) {
  27618. super.deserialize( data );
  27619. for ( const name in this.parameters ) {
  27620. let valueNode = this.parameters[ name ];
  27621. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27622. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27623. }
  27624. }
  27625. /**
  27626. * Returns the layout of the script.
  27627. *
  27628. * @return {Object} The script's layout.
  27629. */
  27630. getLayout() {
  27631. return this.getObject().layout;
  27632. }
  27633. /**
  27634. * Returns default node output of the script.
  27635. *
  27636. * @return {Node} The default node output.
  27637. */
  27638. getDefaultOutputNode() {
  27639. const output = this.getDefaultOutput().value;
  27640. if ( output && output.isNode ) {
  27641. return output;
  27642. }
  27643. return float();
  27644. }
  27645. /**
  27646. * Returns default output of the script.
  27647. *
  27648. * @return {ScriptableValueNode} The default output.
  27649. */
  27650. getDefaultOutput() {
  27651. return this._exec()._output;
  27652. }
  27653. /**
  27654. * Returns a function created from the node's script.
  27655. *
  27656. * @return {Function} The function representing the node's code.
  27657. */
  27658. getMethod() {
  27659. if ( this.needsUpdate ) this.dispose();
  27660. if ( this._method !== null ) return this._method;
  27661. //
  27662. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27663. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27664. const properties = interfaceProps.join( ', ' );
  27665. const declarations = 'var ' + properties + '; var output = {};\n';
  27666. const returns = '\nreturn { ...output, ' + properties + ' };';
  27667. const code = declarations + this.codeNode.code + returns;
  27668. //
  27669. this._method = new Function( ...parametersProps, code );
  27670. return this._method;
  27671. }
  27672. /**
  27673. * Frees all internal resources.
  27674. */
  27675. dispose() {
  27676. if ( this._method === null ) return;
  27677. if ( this._object && typeof this._object.dispose === 'function' ) {
  27678. this._object.dispose();
  27679. }
  27680. this._method = null;
  27681. this._object = null;
  27682. this._source = null;
  27683. this._value = null;
  27684. this._needsOutputUpdate = true;
  27685. this._output.value = null;
  27686. this._outputs = {};
  27687. }
  27688. setup() {
  27689. return this.getDefaultOutputNode();
  27690. }
  27691. getCacheKey( force ) {
  27692. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27693. for ( const param in this.parameters ) {
  27694. values.push( this.parameters[ param ].getCacheKey( force ) );
  27695. }
  27696. return hashArray( values );
  27697. }
  27698. set needsUpdate( value ) {
  27699. if ( value === true ) this.dispose();
  27700. }
  27701. get needsUpdate() {
  27702. return this.source !== this._source;
  27703. }
  27704. /**
  27705. * Executes the `main` function of the script.
  27706. *
  27707. * @private
  27708. * @return {ScriptableNode} A reference to this node.
  27709. */
  27710. _exec() {
  27711. if ( this.codeNode === null ) return this;
  27712. if ( this._needsOutputUpdate === true ) {
  27713. this._value = this.call( 'main' );
  27714. this._needsOutputUpdate = false;
  27715. }
  27716. this._output.value = this._value;
  27717. return this;
  27718. }
  27719. /**
  27720. * Executes the refresh.
  27721. *
  27722. * @private
  27723. */
  27724. _refresh() {
  27725. this.needsUpdate = true;
  27726. this._exec();
  27727. this._output.refresh();
  27728. }
  27729. }
  27730. /**
  27731. * TSL function for creating a scriptable node.
  27732. *
  27733. * @tsl
  27734. * @function
  27735. * @param {CodeNode} [codeNode] - The code node.
  27736. * @param {?Object} [parameters={}] - The parameters definition.
  27737. * @returns {ScriptableNode}
  27738. */
  27739. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27740. /**
  27741. * Returns a node that represents the `z` coordinate in view space
  27742. * for the current fragment. It's a different representation of the
  27743. * default depth value.
  27744. *
  27745. * This value can be part of a computation that defines how the fog
  27746. * density increases when moving away from the camera.
  27747. *
  27748. * @param {NodeBuilder} builder - The current node builder.
  27749. * @return {Node} The viewZ node.
  27750. */
  27751. function getViewZNode( builder ) {
  27752. let viewZ;
  27753. const getViewZ = builder.context.getViewZ;
  27754. if ( getViewZ !== undefined ) {
  27755. viewZ = getViewZ( this );
  27756. }
  27757. return ( viewZ || positionView.z ).negate();
  27758. }
  27759. /**
  27760. * Constructs a new range factor node.
  27761. *
  27762. * @tsl
  27763. * @function
  27764. * @param {Node} near - Defines the near value.
  27765. * @param {Node} far - Defines the far value.
  27766. */
  27767. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27768. const viewZ = getViewZNode( builder );
  27769. return smoothstep( near, far, viewZ );
  27770. } );
  27771. /**
  27772. * Represents an exponential squared fog. This type of fog gives
  27773. * a clear view near the camera and a faster than exponentially
  27774. * densening fog farther from the camera.
  27775. *
  27776. * @tsl
  27777. * @function
  27778. * @param {Node} density - Defines the fog density.
  27779. */
  27780. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27781. const viewZ = getViewZNode( builder );
  27782. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27783. } );
  27784. /**
  27785. * This class can be used to configure a fog for the scene.
  27786. * Nodes of this type are assigned to `Scene.fogNode`.
  27787. *
  27788. * @tsl
  27789. * @function
  27790. * @param {Node} color - Defines the color of the fog.
  27791. * @param {Node} factor - Defines how the fog is factored in the scene.
  27792. */
  27793. const fog = Fn( ( [ color, factor ] ) => {
  27794. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27795. } );
  27796. // Deprecated
  27797. /**
  27798. * @tsl
  27799. * @function
  27800. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27801. *
  27802. * @param {Node} color
  27803. * @param {Node} near
  27804. * @param {Node} far
  27805. * @returns {Function}
  27806. */
  27807. function rangeFog( color, near, far ) { // @deprecated, r171
  27808. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27809. return fog( color, rangeFogFactor( near, far ) );
  27810. }
  27811. /**
  27812. * @tsl
  27813. * @function
  27814. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27815. *
  27816. * @param {Node} color
  27817. * @param {Node} density
  27818. * @returns {Function}
  27819. */
  27820. function densityFog( color, density ) { // @deprecated, r171
  27821. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27822. return fog( color, densityFogFactor( density ) );
  27823. }
  27824. let min = null;
  27825. let max = null;
  27826. /**
  27827. * `RangeNode` generates random instanced attribute data in a defined range.
  27828. * An exemplary use case for this utility node is to generate random per-instance
  27829. * colors:
  27830. * ```js
  27831. * const material = new MeshBasicNodeMaterial();
  27832. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27833. * const mesh = new InstancedMesh( geometry, material, count );
  27834. * ```
  27835. * @augments Node
  27836. */
  27837. class RangeNode extends Node {
  27838. static get type() {
  27839. return 'RangeNode';
  27840. }
  27841. /**
  27842. * Constructs a new range node.
  27843. *
  27844. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27845. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27846. */
  27847. constructor( minNode = float(), maxNode = float() ) {
  27848. super();
  27849. /**
  27850. * A node defining the lower bound of the range.
  27851. *
  27852. * @type {Node<any>}
  27853. * @default float()
  27854. */
  27855. this.minNode = minNode;
  27856. /**
  27857. * A node defining the upper bound of the range.
  27858. *
  27859. * @type {Node<any>}
  27860. * @default float()
  27861. */
  27862. this.maxNode = maxNode;
  27863. }
  27864. /**
  27865. * Returns the vector length which is computed based on the range definition.
  27866. *
  27867. * @param {NodeBuilder} builder - The current node builder.
  27868. * @return {number} The vector length.
  27869. */
  27870. getVectorLength( builder ) {
  27871. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27872. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27873. return minLength > maxLength ? minLength : maxLength;
  27874. }
  27875. /**
  27876. * This method is overwritten since the node type is inferred from range definition.
  27877. *
  27878. * @param {NodeBuilder} builder - The current node builder.
  27879. * @return {string} The node type.
  27880. */
  27881. getNodeType( builder ) {
  27882. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27883. }
  27884. setup( builder ) {
  27885. const object = builder.object;
  27886. let output = null;
  27887. if ( object.count > 1 ) {
  27888. const minValue = this.minNode.value;
  27889. const maxValue = this.maxNode.value;
  27890. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27891. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27892. min = min || new Vector4();
  27893. max = max || new Vector4();
  27894. min.setScalar( 0 );
  27895. max.setScalar( 0 );
  27896. if ( minLength === 1 ) min.setScalar( minValue );
  27897. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27898. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27899. if ( maxLength === 1 ) max.setScalar( maxValue );
  27900. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27901. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27902. const stride = 4;
  27903. const length = stride * object.count;
  27904. const array = new Float32Array( length );
  27905. for ( let i = 0; i < length; i ++ ) {
  27906. const index = i % stride;
  27907. const minElementValue = min.getComponent( index );
  27908. const maxElementValue = max.getComponent( index );
  27909. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27910. }
  27911. const nodeType = this.getNodeType( builder );
  27912. if ( object.count <= 4096 ) {
  27913. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27914. } else {
  27915. // TODO: Improve anonymous buffer attribute creation removing this part
  27916. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27917. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27918. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27919. }
  27920. } else {
  27921. output = float( 0 );
  27922. }
  27923. return output;
  27924. }
  27925. }
  27926. /**
  27927. * TSL function for creating a range node.
  27928. *
  27929. * @tsl
  27930. * @function
  27931. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27932. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27933. * @returns {RangeNode}
  27934. */
  27935. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27936. /**
  27937. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27938. * about the currently running dispatch and/or the device it is running on.
  27939. *
  27940. * This node can only be used with a WebGPU backend.
  27941. *
  27942. * @augments Node
  27943. */
  27944. class ComputeBuiltinNode extends Node {
  27945. static get type() {
  27946. return 'ComputeBuiltinNode';
  27947. }
  27948. /**
  27949. * Constructs a new compute builtin node.
  27950. *
  27951. * @param {string} builtinName - The built-in name.
  27952. * @param {string} nodeType - The node type.
  27953. */
  27954. constructor( builtinName, nodeType ) {
  27955. super( nodeType );
  27956. /**
  27957. * The built-in name.
  27958. *
  27959. * @private
  27960. * @type {string}
  27961. */
  27962. this._builtinName = builtinName;
  27963. }
  27964. /**
  27965. * This method is overwritten since hash is derived from the built-in name.
  27966. *
  27967. * @param {NodeBuilder} builder - The current node builder.
  27968. * @return {string} The hash.
  27969. */
  27970. getHash( builder ) {
  27971. return this.getBuiltinName( builder );
  27972. }
  27973. /**
  27974. * This method is overwritten since the node type is simply derived from `nodeType`..
  27975. *
  27976. * @param {NodeBuilder} builder - The current node builder.
  27977. * @return {string} The node type.
  27978. */
  27979. getNodeType( /*builder*/ ) {
  27980. return this.nodeType;
  27981. }
  27982. /**
  27983. * Sets the builtin name.
  27984. *
  27985. * @param {string} builtinName - The built-in name.
  27986. * @return {ComputeBuiltinNode} A reference to this node.
  27987. */
  27988. setBuiltinName( builtinName ) {
  27989. this._builtinName = builtinName;
  27990. return this;
  27991. }
  27992. /**
  27993. * Returns the builtin name.
  27994. *
  27995. * @param {NodeBuilder} builder - The current node builder.
  27996. * @return {string} The builtin name.
  27997. */
  27998. getBuiltinName( /*builder*/ ) {
  27999. return this._builtinName;
  28000. }
  28001. /**
  28002. * Whether the current node builder has the builtin or not.
  28003. *
  28004. * @param {NodeBuilder} builder - The current node builder.
  28005. * @return {boolean} Whether the builder has the builtin or not.
  28006. */
  28007. hasBuiltin( builder ) {
  28008. return builder.hasBuiltin( this._builtinName );
  28009. }
  28010. generate( builder, output ) {
  28011. const builtinName = this.getBuiltinName( builder );
  28012. const nodeType = this.getNodeType( builder );
  28013. if ( builder.shaderStage === 'compute' ) {
  28014. return builder.format( builtinName, nodeType, output );
  28015. } else {
  28016. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  28017. return builder.generateConst( nodeType );
  28018. }
  28019. }
  28020. serialize( data ) {
  28021. super.serialize( data );
  28022. data.global = this.global;
  28023. data._builtinName = this._builtinName;
  28024. }
  28025. deserialize( data ) {
  28026. super.deserialize( data );
  28027. this.global = data.global;
  28028. this._builtinName = data._builtinName;
  28029. }
  28030. }
  28031. /**
  28032. * TSL function for creating a compute builtin node.
  28033. *
  28034. * @tsl
  28035. * @function
  28036. * @param {string} name - The built-in name.
  28037. * @param {string} nodeType - The node type.
  28038. * @returns {ComputeBuiltinNode}
  28039. */
  28040. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  28041. /**
  28042. * Represents the number of workgroups dispatched by the compute shader.
  28043. * ```js
  28044. * // Run 512 invocations/threads with a workgroup size of 128.
  28045. * const computeFn = Fn(() => {
  28046. *
  28047. * // numWorkgroups.x = 4
  28048. * storageBuffer.element(0).assign(numWorkgroups.x)
  28049. *
  28050. * })().compute(512, [128]);
  28051. *
  28052. * // Run 512 invocations/threads with the default workgroup size of 64.
  28053. * const computeFn = Fn(() => {
  28054. *
  28055. * // numWorkgroups.x = 8
  28056. * storageBuffer.element(0).assign(numWorkgroups.x)
  28057. *
  28058. * })().compute(512);
  28059. * ```
  28060. *
  28061. * @tsl
  28062. * @type {ComputeBuiltinNode<uvec3>}
  28063. */
  28064. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  28065. /**
  28066. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  28067. * ```js
  28068. * // Execute 12 compute threads with a workgroup size of 3.
  28069. * const computeFn = Fn( () => {
  28070. *
  28071. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  28072. *
  28073. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  28074. *
  28075. * } ).Else( () => {
  28076. *
  28077. * storageBuffer.element( instanceIndex ).assign( 0 );
  28078. *
  28079. * } );
  28080. *
  28081. * } )().compute( 12, [ 3 ] );
  28082. *
  28083. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  28084. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  28085. * ```
  28086. *
  28087. * @tsl
  28088. * @type {ComputeBuiltinNode<uvec3>}
  28089. */
  28090. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  28091. /**
  28092. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  28093. *
  28094. * @tsl
  28095. * @type {ComputeBuiltinNode<uvec3>}
  28096. */
  28097. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  28098. /**
  28099. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  28100. *
  28101. * @tsl
  28102. * @type {ComputeBuiltinNode<uvec3>}
  28103. */
  28104. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  28105. /**
  28106. * A device dependent variable that exposes the size of the current invocation's subgroup.
  28107. *
  28108. * @tsl
  28109. * @type {ComputeBuiltinNode<uint>}
  28110. */
  28111. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  28112. /**
  28113. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  28114. *
  28115. * This node can only be used with a WebGPU backend.
  28116. *
  28117. * @augments Node
  28118. */
  28119. class BarrierNode extends Node {
  28120. /**
  28121. * Constructs a new barrier node.
  28122. *
  28123. * @param {string} scope - The scope defines the behavior of the node.
  28124. */
  28125. constructor( scope ) {
  28126. super();
  28127. this.scope = scope;
  28128. }
  28129. generate( builder ) {
  28130. const { scope } = this;
  28131. const { renderer } = builder;
  28132. if ( renderer.backend.isWebGLBackend === true ) {
  28133. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  28134. } else {
  28135. builder.addLineFlowCode( `${scope}Barrier()`, this );
  28136. }
  28137. }
  28138. }
  28139. /**
  28140. * TSL function for creating a barrier node.
  28141. *
  28142. * @tsl
  28143. * @function
  28144. * @param {string} scope - The scope defines the behavior of the node..
  28145. * @returns {BarrierNode}
  28146. */
  28147. const barrier = nodeProxy( BarrierNode );
  28148. /**
  28149. * TSL function for creating a workgroup barrier. All compute shader
  28150. * invocations must wait for each invocation within a workgroup to
  28151. * complete before the barrier can be surpassed.
  28152. *
  28153. * @tsl
  28154. * @function
  28155. * @returns {BarrierNode}
  28156. */
  28157. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  28158. /**
  28159. * TSL function for creating a storage barrier. All invocations must
  28160. * wait for each access to variables within the 'storage' address space
  28161. * to complete before the barrier can be passed.
  28162. *
  28163. * @tsl
  28164. * @function
  28165. * @returns {BarrierNode}
  28166. */
  28167. const storageBarrier = () => barrier( 'storage' ).toStack();
  28168. /**
  28169. * TSL function for creating a texture barrier. All invocations must
  28170. * wait for each access to variables within the 'texture' address space
  28171. * to complete before the barrier can be passed.
  28172. *
  28173. * @tsl
  28174. * @function
  28175. * @returns {BarrierNode}
  28176. */
  28177. const textureBarrier = () => barrier( 'texture' ).toStack();
  28178. /**
  28179. * Represents an element of a 'workgroup' scoped buffer.
  28180. *
  28181. * @augments ArrayElementNode
  28182. */
  28183. class WorkgroupInfoElementNode extends ArrayElementNode {
  28184. /**
  28185. * Constructs a new workgroup info element node.
  28186. *
  28187. * @param {Node} workgroupInfoNode - The workgroup info node.
  28188. * @param {Node} indexNode - The index node that defines the element access.
  28189. */
  28190. constructor( workgroupInfoNode, indexNode ) {
  28191. super( workgroupInfoNode, indexNode );
  28192. /**
  28193. * This flag can be used for type testing.
  28194. *
  28195. * @type {boolean}
  28196. * @readonly
  28197. * @default true
  28198. */
  28199. this.isWorkgroupInfoElementNode = true;
  28200. }
  28201. generate( builder, output ) {
  28202. let snippet;
  28203. const isAssignContext = builder.context.assign;
  28204. snippet = super.generate( builder );
  28205. if ( isAssignContext !== true ) {
  28206. const type = this.getNodeType( builder );
  28207. snippet = builder.format( snippet, type, output );
  28208. }
  28209. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  28210. return snippet;
  28211. }
  28212. }
  28213. /**
  28214. * A node allowing the user to create a 'workgroup' scoped buffer within the
  28215. * context of a compute shader. Typically, workgroup scoped buffers are
  28216. * created to hold data that is transferred from a global storage scope into
  28217. * a local workgroup scope. For invocations within a workgroup, data
  28218. * access speeds on 'workgroup' scoped buffers can be significantly faster
  28219. * than similar access operations on globally accessible storage buffers.
  28220. *
  28221. * This node can only be used with a WebGPU backend.
  28222. *
  28223. * @augments Node
  28224. */
  28225. class WorkgroupInfoNode extends Node {
  28226. /**
  28227. * Constructs a new buffer scoped to type scope.
  28228. *
  28229. * @param {string} scope - TODO.
  28230. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  28231. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  28232. */
  28233. constructor( scope, bufferType, bufferCount = 0 ) {
  28234. super( bufferType );
  28235. /**
  28236. * The buffer type.
  28237. *
  28238. * @type {string}
  28239. */
  28240. this.bufferType = bufferType;
  28241. /**
  28242. * The buffer count.
  28243. *
  28244. * @type {number}
  28245. * @default 0
  28246. */
  28247. this.bufferCount = bufferCount;
  28248. /**
  28249. * This flag can be used for type testing.
  28250. *
  28251. * @type {boolean}
  28252. * @readonly
  28253. * @default true
  28254. */
  28255. this.isWorkgroupInfoNode = true;
  28256. /**
  28257. * The data type of the array buffer.
  28258. *
  28259. * @type {string}
  28260. */
  28261. this.elementType = bufferType;
  28262. /**
  28263. * TODO.
  28264. *
  28265. * @type {string}
  28266. */
  28267. this.scope = scope;
  28268. /**
  28269. * The name of the workgroup scoped buffer.
  28270. *
  28271. * @type {string}
  28272. * @default ''
  28273. */
  28274. this.name = '';
  28275. }
  28276. /**
  28277. * Sets the name of this node.
  28278. *
  28279. * @param {string} name - The name to set.
  28280. * @return {WorkgroupInfoNode} A reference to this node.
  28281. */
  28282. setName( name ) {
  28283. this.name = name;
  28284. return this;
  28285. }
  28286. /**
  28287. * Sets the name/label of this node.
  28288. *
  28289. * @deprecated
  28290. * @param {string} name - The name to set.
  28291. * @return {WorkgroupInfoNode} A reference to this node.
  28292. */
  28293. label( name ) {
  28294. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  28295. return this.setName( name );
  28296. }
  28297. /**
  28298. * Sets the scope of this node.
  28299. *
  28300. * @param {string} scope - The scope to set.
  28301. * @return {WorkgroupInfoNode} A reference to this node.
  28302. */
  28303. setScope( scope ) {
  28304. this.scope = scope;
  28305. return this;
  28306. }
  28307. /**
  28308. * The data type of the array buffer.
  28309. *
  28310. * @return {string} The element type.
  28311. */
  28312. getElementType() {
  28313. return this.elementType;
  28314. }
  28315. /**
  28316. * Overwrites the default implementation since the input type
  28317. * is inferred from the scope.
  28318. *
  28319. * @param {NodeBuilder} builder - The current node builder.
  28320. * @return {string} The input type.
  28321. */
  28322. getInputType( /*builder*/ ) {
  28323. return `${this.scope}Array`;
  28324. }
  28325. /**
  28326. * This method can be used to access elements via an index node.
  28327. *
  28328. * @param {IndexNode} indexNode - indexNode.
  28329. * @return {WorkgroupInfoElementNode} A reference to an element.
  28330. */
  28331. element( indexNode ) {
  28332. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  28333. }
  28334. generate( builder ) {
  28335. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  28336. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  28337. }
  28338. }
  28339. /**
  28340. * TSL function for creating a workgroup info node.
  28341. * Creates a new 'workgroup' scoped array buffer.
  28342. *
  28343. * @tsl
  28344. * @function
  28345. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  28346. * @param {number} [count=0] - The number of elements in the buffer.
  28347. * @returns {WorkgroupInfoNode}
  28348. */
  28349. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  28350. /**
  28351. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  28352. * within a shader. In an atomic function, any modification to an atomic variable will
  28353. * occur as an indivisible step with a defined order relative to other modifications.
  28354. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  28355. * atomic operations will not interfere with each other.
  28356. *
  28357. * This node can only be used with a WebGPU backend.
  28358. *
  28359. * @augments Node
  28360. */
  28361. class AtomicFunctionNode extends Node {
  28362. static get type() {
  28363. return 'AtomicFunctionNode';
  28364. }
  28365. /**
  28366. * Constructs a new atomic function node.
  28367. *
  28368. * @param {string} method - The signature of the atomic function to construct.
  28369. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28370. * @param {Node} valueNode - The value that mutates the atomic variable.
  28371. */
  28372. constructor( method, pointerNode, valueNode ) {
  28373. super( 'uint' );
  28374. /**
  28375. * The signature of the atomic function to construct.
  28376. *
  28377. * @type {string}
  28378. */
  28379. this.method = method;
  28380. /**
  28381. * An atomic variable or element of an atomic buffer.
  28382. *
  28383. * @type {Node}
  28384. */
  28385. this.pointerNode = pointerNode;
  28386. /**
  28387. * A value that modifies the atomic variable.
  28388. *
  28389. * @type {Node}
  28390. */
  28391. this.valueNode = valueNode;
  28392. /**
  28393. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  28394. *
  28395. * @type {boolean}
  28396. * @default true
  28397. */
  28398. this.parents = true;
  28399. }
  28400. /**
  28401. * Overwrites the default implementation to return the type of
  28402. * the pointer node.
  28403. *
  28404. * @param {NodeBuilder} builder - The current node builder.
  28405. * @return {string} The input type.
  28406. */
  28407. getInputType( builder ) {
  28408. return this.pointerNode.getNodeType( builder );
  28409. }
  28410. /**
  28411. * Overwritten since the node type is inferred from the input type.
  28412. *
  28413. * @param {NodeBuilder} builder - The current node builder.
  28414. * @return {string} The node type.
  28415. */
  28416. getNodeType( builder ) {
  28417. return this.getInputType( builder );
  28418. }
  28419. generate( builder ) {
  28420. const properties = builder.getNodeProperties( this );
  28421. const parents = properties.parents;
  28422. const method = this.method;
  28423. const type = this.getNodeType( builder );
  28424. const inputType = this.getInputType( builder );
  28425. const a = this.pointerNode;
  28426. const b = this.valueNode;
  28427. const params = [];
  28428. params.push( `&${ a.build( builder, inputType ) }` );
  28429. if ( b !== null ) {
  28430. params.push( b.build( builder, inputType ) );
  28431. }
  28432. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  28433. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  28434. if ( isVoid ) {
  28435. builder.addLineFlowCode( methodSnippet, this );
  28436. } else {
  28437. if ( properties.constNode === undefined ) {
  28438. properties.constNode = expression( methodSnippet, type ).toConst();
  28439. }
  28440. return properties.constNode.build( builder );
  28441. }
  28442. }
  28443. }
  28444. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28445. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28446. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28447. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28448. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28449. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28450. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28451. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28452. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28453. /**
  28454. * TSL function for creating an atomic function node.
  28455. *
  28456. * @tsl
  28457. * @function
  28458. * @param {string} method - The signature of the atomic function to construct.
  28459. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28460. * @param {Node} valueNode - The value that mutates the atomic variable.
  28461. * @returns {AtomicFunctionNode}
  28462. */
  28463. const atomicNode = nodeProxy( AtomicFunctionNode );
  28464. /**
  28465. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28466. *
  28467. * @tsl
  28468. * @function
  28469. * @param {string} method - The signature of the atomic function to construct.
  28470. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28471. * @param {Node} valueNode - The value that mutates the atomic variable.
  28472. * @returns {AtomicFunctionNode}
  28473. */
  28474. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28475. return atomicNode( method, pointerNode, valueNode ).toStack();
  28476. };
  28477. /**
  28478. * Loads the value stored in the atomic variable.
  28479. *
  28480. * @tsl
  28481. * @function
  28482. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28483. * @returns {AtomicFunctionNode}
  28484. */
  28485. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28486. /**
  28487. * Stores a value in the atomic variable.
  28488. *
  28489. * @tsl
  28490. * @function
  28491. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28492. * @param {Node} valueNode - The value that mutates the atomic variable.
  28493. * @returns {AtomicFunctionNode}
  28494. */
  28495. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  28496. /**
  28497. * Increments the value stored in the atomic variable.
  28498. *
  28499. * @tsl
  28500. * @function
  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 atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28506. /**
  28507. * Decrements the value stored in the atomic variable.
  28508. *
  28509. * @tsl
  28510. * @function
  28511. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28512. * @param {Node} valueNode - The value that mutates the atomic variable.
  28513. * @returns {AtomicFunctionNode}
  28514. */
  28515. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28516. /**
  28517. * Stores in an atomic variable the maximum between its current value and a parameter.
  28518. *
  28519. * @tsl
  28520. * @function
  28521. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28522. * @param {Node} valueNode - The value that mutates the atomic variable.
  28523. * @returns {AtomicFunctionNode}
  28524. */
  28525. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28526. /**
  28527. * Stores in an atomic variable the minimum between its current value and a parameter.
  28528. *
  28529. * @tsl
  28530. * @function
  28531. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28532. * @param {Node} valueNode - The value that mutates the atomic variable.
  28533. * @returns {AtomicFunctionNode}
  28534. */
  28535. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28536. /**
  28537. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28538. *
  28539. * @tsl
  28540. * @function
  28541. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28542. * @param {Node} valueNode - The value that mutates the atomic variable.
  28543. * @returns {AtomicFunctionNode}
  28544. */
  28545. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28546. /**
  28547. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28548. *
  28549. * @tsl
  28550. * @function
  28551. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28552. * @param {Node} valueNode - The value that mutates the atomic variable.
  28553. * @returns {AtomicFunctionNode}
  28554. */
  28555. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28556. /**
  28557. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28558. *
  28559. * @tsl
  28560. * @function
  28561. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28562. * @param {Node} valueNode - The value that mutates the atomic variable.
  28563. * @returns {AtomicFunctionNode}
  28564. */
  28565. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28566. /**
  28567. * This class represents a set of built in WGSL shader functions that sync
  28568. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28569. * or fragment shader invocations within a workgroup. Typically, these functions
  28570. * will synchronously execute an operation using data from all active invocations
  28571. * within the subgroup, then broadcast that result to all active invocations. In
  28572. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28573. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28574. *
  28575. * @augments TempNode
  28576. */
  28577. class SubgroupFunctionNode extends TempNode {
  28578. static get type() {
  28579. return 'SubgroupFunctionNode';
  28580. }
  28581. /**
  28582. * Constructs a new function node.
  28583. *
  28584. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28585. * @param {Node} [aNode=null] - The method's first argument.
  28586. * @param {Node} [bNode=null] - The method's second argument.
  28587. */
  28588. constructor( method, aNode = null, bNode = null ) {
  28589. super();
  28590. /**
  28591. * The subgroup/wave intrinsic method to construct.
  28592. *
  28593. * @type {String}
  28594. */
  28595. this.method = method;
  28596. /**
  28597. * The method's first argument.
  28598. *
  28599. * @type {Node}
  28600. */
  28601. this.aNode = aNode;
  28602. /**
  28603. * The method's second argument.
  28604. *
  28605. * @type {Node}
  28606. */
  28607. this.bNode = bNode;
  28608. }
  28609. getInputType( builder ) {
  28610. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28611. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28612. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28613. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28614. if ( aLen > bLen ) {
  28615. return aType;
  28616. } else {
  28617. return bType;
  28618. }
  28619. }
  28620. getNodeType( builder ) {
  28621. const method = this.method;
  28622. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28623. return 'bool';
  28624. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28625. return 'uvec4';
  28626. } else {
  28627. return this.getInputType( builder );
  28628. }
  28629. }
  28630. generate( builder, output ) {
  28631. const method = this.method;
  28632. const type = this.getNodeType( builder );
  28633. const inputType = this.getInputType( builder );
  28634. const a = this.aNode;
  28635. const b = this.bNode;
  28636. const params = [];
  28637. if (
  28638. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28639. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28640. method === SubgroupFunctionNode.QUAD_BROADCAST
  28641. ) {
  28642. const bType = b.getNodeType( builder );
  28643. params.push(
  28644. a.build( builder, type ),
  28645. b.build( builder, bType === 'float' ? 'int' : type )
  28646. );
  28647. } else if (
  28648. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28649. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28650. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28651. ) {
  28652. params.push(
  28653. a.build( builder, type ),
  28654. b.build( builder, 'uint' )
  28655. );
  28656. } else {
  28657. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28658. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28659. }
  28660. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28661. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28662. }
  28663. serialize( data ) {
  28664. super.serialize( data );
  28665. data.method = this.method;
  28666. }
  28667. deserialize( data ) {
  28668. super.deserialize( data );
  28669. this.method = data.method;
  28670. }
  28671. }
  28672. // 0 inputs
  28673. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28674. // 1 input
  28675. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28676. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28677. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28678. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28679. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28680. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28681. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28682. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28683. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28684. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28685. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28686. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28687. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28688. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28689. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28690. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28691. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28692. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28693. // 2 inputs
  28694. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28695. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28696. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28697. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28698. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28699. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28700. /**
  28701. * Returns true if this invocation has the lowest subgroup_invocation_id
  28702. * among active invocations in the subgroup.
  28703. *
  28704. * @tsl
  28705. * @method
  28706. * @return {bool} The result of the computation.
  28707. */
  28708. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28709. /**
  28710. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28711. * is 1 if pred is true for that active invocation and 0 otherwise.
  28712. *
  28713. * @tsl
  28714. * @method
  28715. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28716. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28717. */
  28718. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28719. /**
  28720. * A reduction that adds e among all active invocations and returns that result.
  28721. *
  28722. * @tsl
  28723. * @method
  28724. * @param {number} e - The value provided to the reduction by the current invocation.
  28725. * @return {number} The accumulated result of the reduction operation.
  28726. */
  28727. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28728. /**
  28729. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28730. *
  28731. * @tsl
  28732. * @method
  28733. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28734. * @return {number} The accumulated result of the inclusive scan operation.
  28735. */
  28736. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28737. /**
  28738. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28739. *
  28740. * @tsl
  28741. * @method
  28742. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28743. * @return {number} The accumulated result of the exclusive scan operation.
  28744. */
  28745. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28746. /**
  28747. * A reduction that multiplies e among all active invocations and returns that result.
  28748. *
  28749. * @tsl
  28750. * @method
  28751. * @param {number} e - The value provided to the reduction by the current invocation.
  28752. * @return {number} The accumulated result of the reduction operation.
  28753. */
  28754. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28755. /**
  28756. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28757. *
  28758. * @tsl
  28759. * @method
  28760. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28761. * @return {number} The accumulated result of the inclusive scan operation.
  28762. */
  28763. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28764. /**
  28765. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28766. *
  28767. * @tsl
  28768. * @method
  28769. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28770. * @return {number} The accumulated result of the exclusive scan operation.
  28771. */
  28772. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28773. /**
  28774. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  28775. *
  28776. * @tsl
  28777. * @method
  28778. * @param {number} e - The value provided to the reduction by the current invocation.
  28779. * @return {number} The result of the reduction operation.
  28780. */
  28781. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  28782. /**
  28783. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  28784. *
  28785. * @tsl
  28786. * @method
  28787. * @param {number} e - The value provided to the reduction by the current invocation.
  28788. * @return {number} The result of the reduction operation.
  28789. */
  28790. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  28791. /**
  28792. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  28793. *
  28794. * @tsl
  28795. * @method
  28796. * @param {number} e - The value provided to the reduction by the current invocation.
  28797. * @return {number} The result of the reduction operation.
  28798. */
  28799. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  28800. /**
  28801. * A reduction that performs a min of e among all active invocations and returns that result.
  28802. *
  28803. * @tsl
  28804. * @method
  28805. * @param {number} e - The value provided to the reduction by the current invocation.
  28806. * @return {number} The result of the reduction operation.
  28807. */
  28808. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28809. /**
  28810. * A reduction that performs a max of e among all active invocations and returns that result.
  28811. *
  28812. * @tsl
  28813. * @method
  28814. * @param {number} e - The value provided to the reduction by the current invocation.
  28815. * @return {number} The result of the reduction operation.
  28816. */
  28817. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28818. /**
  28819. * Returns true if e is true for all active invocations in the subgroup.
  28820. *
  28821. * @tsl
  28822. * @method
  28823. * @return {bool} The result of the computation.
  28824. */
  28825. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28826. /**
  28827. * Returns true if e is true for any active invocation in the subgroup
  28828. *
  28829. * @tsl
  28830. * @method
  28831. * @return {bool} The result of the computation.
  28832. */
  28833. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28834. /**
  28835. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28836. *
  28837. * @tsl
  28838. * @method
  28839. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28840. * @param {number} id - The subgroup invocation to broadcast from.
  28841. * @return {number} The broadcast value.
  28842. */
  28843. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28844. /**
  28845. * Swaps e between invocations in the quad in the X direction.
  28846. *
  28847. * @tsl
  28848. * @method
  28849. * @param {number} e - The value to swap from the current invocation.
  28850. * @return {number} The value received from the swap operation.
  28851. */
  28852. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28853. /**
  28854. * Swaps e between invocations in the quad in the Y direction.
  28855. *
  28856. * @tsl
  28857. * @method
  28858. * @param {number} e - The value to swap from the current invocation.
  28859. * @return {number} The value received from the swap operation.
  28860. */
  28861. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28862. /**
  28863. * Swaps e between invocations in the quad diagonally.
  28864. *
  28865. * @tsl
  28866. * @method
  28867. * @param {number} e - The value to swap from the current invocation.
  28868. * @return {number} The value received from the swap operation.
  28869. */
  28870. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28871. /**
  28872. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28873. *
  28874. * @tsl
  28875. * @method
  28876. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28877. * @param {number} id - The subgroup invocation to broadcast from.
  28878. * @return {number} The broadcast value.
  28879. */
  28880. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28881. /**
  28882. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28883. *
  28884. * @tsl
  28885. * @method
  28886. * @param {number} v - The value to return from subgroup invocation id^mask.
  28887. * @param {number} id - The subgroup invocation which returns the value v.
  28888. * @return {number} The broadcast value.
  28889. */
  28890. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28891. /**
  28892. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28893. *
  28894. * @tsl
  28895. * @method
  28896. * @param {number} v - The value to return from subgroup invocation id^mask.
  28897. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28898. * @return {number} The broadcast value.
  28899. */
  28900. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28901. /**
  28902. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28903. *
  28904. * @tsl
  28905. * @method
  28906. * @param {number} v - The value to return from subgroup invocation id^mask.
  28907. * @param {number} delta - A value that offsets the current in.
  28908. * @return {number} The broadcast value.
  28909. */
  28910. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28911. /**
  28912. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28913. *
  28914. * @tsl
  28915. * @method
  28916. * @param {number} v - The value to return from subgroup invocation id^mask.
  28917. * @param {number} delta - A value that offsets the current subgroup invocation.
  28918. * @return {number} The broadcast value.
  28919. */
  28920. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28921. /**
  28922. * Broadcasts e from the quad invocation with id equal to id.
  28923. *
  28924. * @tsl
  28925. * @method
  28926. * @param {number} e - The value to broadcast.
  28927. * @return {number} The broadcast value.
  28928. */
  28929. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28930. let uniformsLib;
  28931. function getLightData( light ) {
  28932. uniformsLib = uniformsLib || new WeakMap();
  28933. let uniforms = uniformsLib.get( light );
  28934. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28935. return uniforms;
  28936. }
  28937. /**
  28938. * TSL function for getting a shadow matrix uniform node for the given light.
  28939. *
  28940. * @tsl
  28941. * @function
  28942. * @param {Light} light -The light source.
  28943. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28944. */
  28945. function lightShadowMatrix( light ) {
  28946. const data = getLightData( light );
  28947. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28948. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  28949. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  28950. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28951. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  28952. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  28953. light.shadow.camera.updateProjectionMatrix();
  28954. }
  28955. light.shadow.updateMatrices( light );
  28956. }
  28957. return light.shadow.matrix;
  28958. } ) );
  28959. }
  28960. /**
  28961. * TSL function for getting projected uv coordinates for the given light.
  28962. * Relevant when using maps with spot lights.
  28963. *
  28964. * @tsl
  28965. * @function
  28966. * @param {Light} light -The light source.
  28967. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28968. * @returns {Node<vec3>} The projected uvs.
  28969. */
  28970. function lightProjectionUV( light, position = positionWorld ) {
  28971. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28972. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28973. return projectionUV;
  28974. }
  28975. /**
  28976. * TSL function for getting the position in world space for the given light.
  28977. *
  28978. * @tsl
  28979. * @function
  28980. * @param {Light} light -The light source.
  28981. * @returns {UniformNode<vec3>} The light's position in world space.
  28982. */
  28983. function lightPosition( light ) {
  28984. const data = getLightData( light );
  28985. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28986. }
  28987. /**
  28988. * TSL function for getting the light target position in world space for the given light.
  28989. *
  28990. * @tsl
  28991. * @function
  28992. * @param {Light} light -The light source.
  28993. * @returns {UniformNode<vec3>} The light target position in world space.
  28994. */
  28995. function lightTargetPosition( light ) {
  28996. const data = getLightData( light );
  28997. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  28998. }
  28999. /**
  29000. * TSL function for getting the position in view space for the given light.
  29001. *
  29002. * @tsl
  29003. * @function
  29004. * @param {Light} light - The light source.
  29005. * @returns {UniformNode<vec3>} The light's position in view space.
  29006. */
  29007. function lightViewPosition( light ) {
  29008. const data = getLightData( light );
  29009. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  29010. self.value = self.value || new Vector3();
  29011. self.value.setFromMatrixPosition( light.matrixWorld );
  29012. self.value.applyMatrix4( camera.matrixWorldInverse );
  29013. } ) );
  29014. }
  29015. /**
  29016. * TSL function for getting the light target direction for the given light.
  29017. *
  29018. * @tsl
  29019. * @function
  29020. * @param {Light} light -The light source.
  29021. * @returns {Node<vec3>} The light's target direction.
  29022. */
  29023. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  29024. const sortLights = ( lights ) => {
  29025. return lights.sort( ( a, b ) => a.id - b.id );
  29026. };
  29027. const getLightNodeById = ( id, lightNodes ) => {
  29028. for ( const lightNode of lightNodes ) {
  29029. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  29030. return lightNode;
  29031. }
  29032. }
  29033. return null;
  29034. };
  29035. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  29036. const _hashData = [];
  29037. /**
  29038. * This node represents the scene's lighting and manages the lighting model's life cycle
  29039. * for the current build 3D object. It is responsible for computing the total outgoing
  29040. * light in a given lighting context.
  29041. *
  29042. * @augments Node
  29043. */
  29044. class LightsNode extends Node {
  29045. static get type() {
  29046. return 'LightsNode';
  29047. }
  29048. /**
  29049. * Constructs a new lights node.
  29050. */
  29051. constructor() {
  29052. super( 'vec3' );
  29053. /**
  29054. * A node representing the total diffuse light.
  29055. *
  29056. * @type {Node<vec3>}
  29057. */
  29058. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  29059. /**
  29060. * A node representing the total specular light.
  29061. *
  29062. * @type {Node<vec3>}
  29063. */
  29064. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  29065. /**
  29066. * A node representing the outgoing light.
  29067. *
  29068. * @type {Node<vec3>}
  29069. */
  29070. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  29071. /**
  29072. * An array representing the lights in the scene.
  29073. *
  29074. * @private
  29075. * @type {Array<Light>}
  29076. */
  29077. this._lights = [];
  29078. /**
  29079. * For each light in the scene, this node will create a
  29080. * corresponding light node.
  29081. *
  29082. * @private
  29083. * @type {?Array<LightingNode>}
  29084. * @default null
  29085. */
  29086. this._lightNodes = null;
  29087. /**
  29088. * A hash for identifying the current light nodes setup.
  29089. *
  29090. * @private
  29091. * @type {?string}
  29092. * @default null
  29093. */
  29094. this._lightNodesHash = null;
  29095. /**
  29096. * `LightsNode` sets this property to `true` by default.
  29097. *
  29098. * @type {boolean}
  29099. * @default true
  29100. */
  29101. this.global = true;
  29102. }
  29103. /**
  29104. * Overwrites the default {@link Node#customCacheKey} implementation by including
  29105. * light data into the cache key.
  29106. *
  29107. * @return {number} The custom cache key.
  29108. */
  29109. customCacheKey() {
  29110. const lights = this._lights;
  29111. for ( let i = 0; i < lights.length; i ++ ) {
  29112. const light = lights[ i ];
  29113. _hashData.push( light.id );
  29114. _hashData.push( light.castShadow ? 1 : 0 );
  29115. if ( light.isSpotLight === true ) {
  29116. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  29117. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  29118. _hashData.push( hashMap, hashColorNode );
  29119. }
  29120. }
  29121. const cacheKey = hashArray( _hashData );
  29122. _hashData.length = 0;
  29123. return cacheKey;
  29124. }
  29125. /**
  29126. * Computes a hash value for identifying the current light nodes setup.
  29127. *
  29128. * @param {NodeBuilder} builder - A reference to the current node builder.
  29129. * @return {string} The computed hash.
  29130. */
  29131. getHash( builder ) {
  29132. if ( this._lightNodesHash === null ) {
  29133. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29134. const hash = [];
  29135. for ( const lightNode of this._lightNodes ) {
  29136. hash.push( lightNode.getHash() );
  29137. }
  29138. this._lightNodesHash = 'lights-' + hash.join( ',' );
  29139. }
  29140. return this._lightNodesHash;
  29141. }
  29142. analyze( builder ) {
  29143. const properties = builder.getNodeProperties( this );
  29144. for ( const node of properties.nodes ) {
  29145. node.build( builder );
  29146. }
  29147. properties.outputNode.build( builder );
  29148. }
  29149. /**
  29150. * Creates lighting nodes for each scene light. This makes it possible to further
  29151. * process lights in the node system.
  29152. *
  29153. * @param {NodeBuilder} builder - A reference to the current node builder.
  29154. */
  29155. setupLightsNode( builder ) {
  29156. const lightNodes = [];
  29157. const previousLightNodes = this._lightNodes;
  29158. const lights = sortLights( this._lights );
  29159. const nodeLibrary = builder.renderer.library;
  29160. for ( const light of lights ) {
  29161. if ( light.isNode ) {
  29162. lightNodes.push( nodeObject( light ) );
  29163. } else {
  29164. let lightNode = null;
  29165. if ( previousLightNodes !== null ) {
  29166. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  29167. }
  29168. if ( lightNode === null ) {
  29169. // find the corresponding node type for a given light
  29170. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  29171. if ( lightNodeClass === null ) {
  29172. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  29173. continue;
  29174. }
  29175. let lightNode = null;
  29176. if ( ! _lightsNodeRef.has( light ) ) {
  29177. lightNode = nodeObject( new lightNodeClass( light ) );
  29178. _lightsNodeRef.set( light, lightNode );
  29179. } else {
  29180. lightNode = _lightsNodeRef.get( light );
  29181. }
  29182. lightNodes.push( lightNode );
  29183. }
  29184. }
  29185. }
  29186. this._lightNodes = lightNodes;
  29187. }
  29188. /**
  29189. * Sets up a direct light in the lighting model.
  29190. *
  29191. * @param {Object} builder - The builder object containing the context and stack.
  29192. * @param {Object} lightNode - The light node.
  29193. * @param {Object} lightData - The light object containing color and direction properties.
  29194. */
  29195. setupDirectLight( builder, lightNode, lightData ) {
  29196. const { lightingModel, reflectedLight } = builder.context;
  29197. lightingModel.direct( {
  29198. ...lightData,
  29199. lightNode,
  29200. reflectedLight
  29201. }, builder );
  29202. }
  29203. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  29204. const { lightingModel, reflectedLight } = builder.context;
  29205. lightingModel.directRectArea( {
  29206. ...lightData,
  29207. lightNode,
  29208. reflectedLight
  29209. }, builder );
  29210. }
  29211. /**
  29212. * Setups the internal lights by building all respective
  29213. * light nodes.
  29214. *
  29215. * @param {NodeBuilder} builder - A reference to the current node builder.
  29216. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  29217. */
  29218. setupLights( builder, lightNodes ) {
  29219. for ( const lightNode of lightNodes ) {
  29220. lightNode.build( builder );
  29221. }
  29222. }
  29223. getLightNodes( builder ) {
  29224. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29225. return this._lightNodes;
  29226. }
  29227. /**
  29228. * The implementation makes sure that for each light in the scene
  29229. * there is a corresponding light node. By building the light nodes
  29230. * and evaluating the lighting model the outgoing light is computed.
  29231. *
  29232. * @param {NodeBuilder} builder - A reference to the current node builder.
  29233. * @return {Node<vec3>} A node representing the outgoing light.
  29234. */
  29235. setup( builder ) {
  29236. const currentLightsNode = builder.lightsNode;
  29237. builder.lightsNode = this;
  29238. //
  29239. let outgoingLightNode = this.outgoingLightNode;
  29240. const context = builder.context;
  29241. const lightingModel = context.lightingModel;
  29242. const properties = builder.getNodeProperties( this );
  29243. if ( lightingModel ) {
  29244. const { totalDiffuseNode, totalSpecularNode } = this;
  29245. context.outgoingLight = outgoingLightNode;
  29246. const stack = builder.addStack();
  29247. //
  29248. properties.nodes = stack.nodes;
  29249. //
  29250. lightingModel.start( builder );
  29251. //
  29252. const { backdrop, backdropAlpha } = context;
  29253. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  29254. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  29255. if ( backdrop !== null ) {
  29256. if ( backdropAlpha !== null ) {
  29257. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  29258. } else {
  29259. totalDiffuse = vec3( backdrop );
  29260. }
  29261. context.material.transparent = true;
  29262. }
  29263. totalDiffuseNode.assign( totalDiffuse );
  29264. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  29265. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  29266. //
  29267. lightingModel.finish( builder );
  29268. //
  29269. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  29270. } else {
  29271. properties.nodes = [];
  29272. }
  29273. //
  29274. builder.lightsNode = currentLightsNode;
  29275. return outgoingLightNode;
  29276. }
  29277. /**
  29278. * Configures this node with an array of lights.
  29279. *
  29280. * @param {Array<Light>} lights - An array of lights.
  29281. * @return {LightsNode} A reference to this node.
  29282. */
  29283. setLights( lights ) {
  29284. this._lights = lights;
  29285. this._lightNodes = null;
  29286. this._lightNodesHash = null;
  29287. return this;
  29288. }
  29289. /**
  29290. * Returns an array of the scene's lights.
  29291. *
  29292. * @return {Array<Light>} The scene's lights.
  29293. */
  29294. getLights() {
  29295. return this._lights;
  29296. }
  29297. /**
  29298. * Whether the scene has lights or not.
  29299. *
  29300. * @type {boolean}
  29301. */
  29302. get hasLights() {
  29303. return this._lights.length > 0;
  29304. }
  29305. }
  29306. /**
  29307. * TSL function for creating an instance of `LightsNode` and configuring
  29308. * it with the given array of lights.
  29309. *
  29310. * @tsl
  29311. * @function
  29312. * @param {Array<Light>} lights - An array of lights.
  29313. * @return {LightsNode} The created lights node.
  29314. */
  29315. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  29316. /**
  29317. * Base class for all shadow nodes.
  29318. *
  29319. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  29320. * Lighting nodes might share the same shadow node type or use specific ones depending on
  29321. * their requirements.
  29322. *
  29323. * @augments Node
  29324. */
  29325. class ShadowBaseNode extends Node {
  29326. static get type() {
  29327. return 'ShadowBaseNode';
  29328. }
  29329. /**
  29330. * Constructs a new shadow base node.
  29331. *
  29332. * @param {Light} light - The shadow casting light.
  29333. */
  29334. constructor( light ) {
  29335. super();
  29336. /**
  29337. * The shadow casting light.
  29338. *
  29339. * @type {Light}
  29340. */
  29341. this.light = light;
  29342. /**
  29343. * Overwritten since shadows are updated by default per render.
  29344. *
  29345. * @type {string}
  29346. * @default 'render'
  29347. */
  29348. this.updateBeforeType = NodeUpdateType.RENDER;
  29349. /**
  29350. * This flag can be used for type testing.
  29351. *
  29352. * @type {boolean}
  29353. * @readonly
  29354. * @default true
  29355. */
  29356. this.isShadowBaseNode = true;
  29357. }
  29358. /**
  29359. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  29360. *
  29361. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  29362. */
  29363. setupShadowPosition( { context, material } ) {
  29364. // Use assign inside an Fn()
  29365. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  29366. }
  29367. }
  29368. /**
  29369. * TSL object that represents the vertex position in world space during the shadow pass.
  29370. *
  29371. * @tsl
  29372. * @type {Node<vec3>}
  29373. */
  29374. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  29375. /**
  29376. * Saves the state of the given renderer and stores it into the given state object.
  29377. *
  29378. * If not state object is provided, the function creates one.
  29379. *
  29380. * @private
  29381. * @function
  29382. * @param {Renderer} renderer - The renderer.
  29383. * @param {Object} [state={}] - The state.
  29384. * @return {Object} The state.
  29385. */
  29386. function saveRendererState( renderer, state = {} ) {
  29387. state.toneMapping = renderer.toneMapping;
  29388. state.toneMappingExposure = renderer.toneMappingExposure;
  29389. state.outputColorSpace = renderer.outputColorSpace;
  29390. state.renderTarget = renderer.getRenderTarget();
  29391. state.activeCubeFace = renderer.getActiveCubeFace();
  29392. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  29393. state.renderObjectFunction = renderer.getRenderObjectFunction();
  29394. state.pixelRatio = renderer.getPixelRatio();
  29395. state.mrt = renderer.getMRT();
  29396. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  29397. state.clearAlpha = renderer.getClearAlpha();
  29398. state.autoClear = renderer.autoClear;
  29399. state.scissorTest = renderer.getScissorTest();
  29400. return state;
  29401. }
  29402. /**
  29403. * Saves the state of the given renderer and stores it into the given state object.
  29404. * Besides, the function also resets the state of the renderer to its default values.
  29405. *
  29406. * If not state object is provided, the function creates one.
  29407. *
  29408. * @private
  29409. * @function
  29410. * @param {Renderer} renderer - The renderer.
  29411. * @param {Object} [state={}] - The state.
  29412. * @return {Object} The state.
  29413. */
  29414. function resetRendererState( renderer, state ) {
  29415. state = saveRendererState( renderer, state );
  29416. renderer.setMRT( null );
  29417. renderer.setRenderObjectFunction( null );
  29418. renderer.setClearColor( 0x000000, 1 );
  29419. renderer.autoClear = true;
  29420. return state;
  29421. }
  29422. /**
  29423. * Restores the state of the given renderer from the given state object.
  29424. *
  29425. * @private
  29426. * @function
  29427. * @param {Renderer} renderer - The renderer.
  29428. * @param {Object} state - The state to restore.
  29429. */
  29430. function restoreRendererState( renderer, state ) {
  29431. renderer.toneMapping = state.toneMapping;
  29432. renderer.toneMappingExposure = state.toneMappingExposure;
  29433. renderer.outputColorSpace = state.outputColorSpace;
  29434. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  29435. renderer.setRenderObjectFunction( state.renderObjectFunction );
  29436. renderer.setPixelRatio( state.pixelRatio );
  29437. renderer.setMRT( state.mrt );
  29438. renderer.setClearColor( state.clearColor, state.clearAlpha );
  29439. renderer.autoClear = state.autoClear;
  29440. renderer.setScissorTest( state.scissorTest );
  29441. }
  29442. /**
  29443. * Saves the state of the given scene and stores it into the given state object.
  29444. *
  29445. * If not state object is provided, the function creates one.
  29446. *
  29447. * @private
  29448. * @function
  29449. * @param {Scene} scene - The scene.
  29450. * @param {Object} [state={}] - The state.
  29451. * @return {Object} The state.
  29452. */
  29453. function saveSceneState( scene, state = {} ) {
  29454. state.background = scene.background;
  29455. state.backgroundNode = scene.backgroundNode;
  29456. state.overrideMaterial = scene.overrideMaterial;
  29457. return state;
  29458. }
  29459. /**
  29460. * Saves the state of the given scene and stores it into the given state object.
  29461. * Besides, the function also resets the state of the scene to its default values.
  29462. *
  29463. * If not state object is provided, the function creates one.
  29464. *
  29465. * @private
  29466. * @function
  29467. * @param {Scene} scene - The scene.
  29468. * @param {Object} [state={}] - The state.
  29469. * @return {Object} The state.
  29470. */
  29471. function resetSceneState( scene, state ) {
  29472. state = saveSceneState( scene, state );
  29473. scene.background = null;
  29474. scene.backgroundNode = null;
  29475. scene.overrideMaterial = null;
  29476. return state;
  29477. }
  29478. /**
  29479. * Restores the state of the given scene from the given state object.
  29480. *
  29481. * @private
  29482. * @function
  29483. * @param {Scene} scene - The scene.
  29484. * @param {Object} state - The state to restore.
  29485. */
  29486. function restoreSceneState( scene, state ) {
  29487. scene.background = state.background;
  29488. scene.backgroundNode = state.backgroundNode;
  29489. scene.overrideMaterial = state.overrideMaterial;
  29490. }
  29491. /**
  29492. * Saves the state of the given renderer and scene and stores it into the given state object.
  29493. *
  29494. * If not state object is provided, the function creates one.
  29495. *
  29496. * @private
  29497. * @function
  29498. * @param {Renderer} renderer - The renderer.
  29499. * @param {Scene} scene - The scene.
  29500. * @param {Object} [state={}] - The state.
  29501. * @return {Object} The state.
  29502. */
  29503. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  29504. state = saveRendererState( renderer, state );
  29505. state = saveSceneState( scene, state );
  29506. return state;
  29507. }
  29508. /**
  29509. * Saves the state of the given renderer and scene and stores it into the given state object.
  29510. * Besides, the function also resets the state of the renderer and scene to its default values.
  29511. *
  29512. * If not state object is provided, the function creates one.
  29513. *
  29514. * @private
  29515. * @function
  29516. * @param {Renderer} renderer - The renderer.
  29517. * @param {Scene} scene - The scene.
  29518. * @param {Object} [state={}] - The state.
  29519. * @return {Object} The state.
  29520. */
  29521. function resetRendererAndSceneState( renderer, scene, state ) {
  29522. state = resetRendererState( renderer, state );
  29523. state = resetSceneState( scene, state );
  29524. return state;
  29525. }
  29526. /**
  29527. * Restores the state of the given renderer and scene from the given state object.
  29528. *
  29529. * @private
  29530. * @function
  29531. * @param {Renderer} renderer - The renderer.
  29532. * @param {Scene} scene - The scene.
  29533. * @param {Object} state - The state to restore.
  29534. */
  29535. function restoreRendererAndSceneState( renderer, scene, state ) {
  29536. restoreRendererState( renderer, state );
  29537. restoreSceneState( scene, state );
  29538. }
  29539. var RendererUtils = /*#__PURE__*/Object.freeze({
  29540. __proto__: null,
  29541. resetRendererAndSceneState: resetRendererAndSceneState,
  29542. resetRendererState: resetRendererState,
  29543. resetSceneState: resetSceneState,
  29544. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29545. restoreRendererState: restoreRendererState,
  29546. restoreSceneState: restoreSceneState,
  29547. saveRendererAndSceneState: saveRendererAndSceneState,
  29548. saveRendererState: saveRendererState,
  29549. saveSceneState: saveSceneState
  29550. });
  29551. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29552. /**
  29553. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29554. * with a binary `[0,1]` result.
  29555. *
  29556. * @method
  29557. * @param {Object} inputs - The input parameter object.
  29558. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29559. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29560. * @return {Node<float>} The filtering result.
  29561. */
  29562. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29563. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29564. if ( depthTexture.isArrayTexture ) {
  29565. basic = basic.depth( depthLayer );
  29566. }
  29567. return basic.compare( shadowCoord.z );
  29568. } );
  29569. /**
  29570. * A shadow filtering function performing PCF filtering.
  29571. *
  29572. * @method
  29573. * @param {Object} inputs - The input parameter object.
  29574. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29575. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29576. * @param {LightShadow} inputs.shadow - The light shadow.
  29577. * @return {Node<float>} The filtering result.
  29578. */
  29579. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29580. const depthCompare = ( uv, compare ) => {
  29581. let depth = texture( depthTexture, uv );
  29582. if ( depthTexture.isArrayTexture ) {
  29583. depth = depth.depth( depthLayer );
  29584. }
  29585. return depth.compare( compare );
  29586. };
  29587. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29588. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29589. const texelSize = vec2( 1 ).div( mapSize );
  29590. const dx0 = texelSize.x.negate().mul( radius );
  29591. const dy0 = texelSize.y.negate().mul( radius );
  29592. const dx1 = texelSize.x.mul( radius );
  29593. const dy1 = texelSize.y.mul( radius );
  29594. const dx2 = dx0.div( 2 );
  29595. const dy2 = dy0.div( 2 );
  29596. const dx3 = dx1.div( 2 );
  29597. const dy3 = dy1.div( 2 );
  29598. return add(
  29599. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29600. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29601. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29602. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29603. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29604. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29605. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29606. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29607. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29608. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29609. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29610. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29611. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29612. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29613. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29614. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29615. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29616. ).mul( 1 / 17 );
  29617. } );
  29618. /**
  29619. * A shadow filtering function performing PCF soft filtering.
  29620. *
  29621. * @method
  29622. * @param {Object} inputs - The input parameter object.
  29623. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29624. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29625. * @param {LightShadow} inputs.shadow - The light shadow.
  29626. * @return {Node<float>} The filtering result.
  29627. */
  29628. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29629. const depthCompare = ( uv, compare ) => {
  29630. let depth = texture( depthTexture, uv );
  29631. if ( depthTexture.isArrayTexture ) {
  29632. depth = depth.depth( depthLayer );
  29633. }
  29634. return depth.compare( compare );
  29635. };
  29636. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29637. const texelSize = vec2( 1 ).div( mapSize );
  29638. const dx = texelSize.x;
  29639. const dy = texelSize.y;
  29640. const uv = shadowCoord.xy;
  29641. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29642. uv.subAssign( f.mul( texelSize ) );
  29643. return add(
  29644. depthCompare( uv, shadowCoord.z ),
  29645. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29646. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29647. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29648. mix(
  29649. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29650. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29651. f.x
  29652. ),
  29653. mix(
  29654. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29655. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29656. f.x
  29657. ),
  29658. mix(
  29659. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29660. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29661. f.y
  29662. ),
  29663. mix(
  29664. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29665. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29666. f.y
  29667. ),
  29668. mix(
  29669. mix(
  29670. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29671. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29672. f.x
  29673. ),
  29674. mix(
  29675. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29676. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29677. f.x
  29678. ),
  29679. f.y
  29680. )
  29681. ).mul( 1 / 9 );
  29682. } );
  29683. /**
  29684. * A shadow filtering function performing VSM filtering.
  29685. *
  29686. * @method
  29687. * @param {Object} inputs - The input parameter object.
  29688. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29689. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29690. * @return {Node<float>} The filtering result.
  29691. */
  29692. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29693. const occlusion = float( 1 ).toVar();
  29694. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29695. if ( depthTexture.isArrayTexture ) {
  29696. distribution = distribution.depth( depthLayer );
  29697. }
  29698. distribution = distribution.rg;
  29699. const hardShadow = step( shadowCoord.z, distribution.x );
  29700. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29701. const distance = shadowCoord.z.sub( distribution.x );
  29702. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29703. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29704. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29705. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29706. } );
  29707. return occlusion;
  29708. } );
  29709. //
  29710. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29711. let dist = positionWorld.sub( position ).length();
  29712. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29713. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29714. return dist;
  29715. } );
  29716. const linearShadowDistance = ( light ) => {
  29717. const camera = light.shadow.camera;
  29718. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29719. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29720. const referencePosition = objectPosition( light );
  29721. return linearDistance( referencePosition, nearDistance, farDistance );
  29722. };
  29723. /**
  29724. * Retrieves or creates a shadow material for the given light source.
  29725. *
  29726. * This function checks if a shadow material already exists for the provided light.
  29727. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29728. * in the `shadowMaterialLib` for future use.
  29729. *
  29730. * @tsl
  29731. * @function
  29732. * @param {Light} light - The light source for which the shadow material is needed.
  29733. * If the light is a point light, a depth node is calculated
  29734. * using the linear shadow distance.
  29735. * @returns {NodeMaterial} The shadow material associated with the given light.
  29736. */
  29737. const getShadowMaterial = ( light ) => {
  29738. let material = shadowMaterialLib.get( light );
  29739. if ( material === undefined ) {
  29740. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29741. material = new NodeMaterial();
  29742. material.colorNode = vec4( 0, 0, 0, 1 );
  29743. material.depthNode = depthNode;
  29744. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29745. material.name = 'ShadowMaterial';
  29746. material.fog = false;
  29747. shadowMaterialLib.set( light, material );
  29748. }
  29749. return material;
  29750. };
  29751. //
  29752. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29753. const _shadowRenderObjectKeys = [];
  29754. /**
  29755. * Creates a function to render shadow objects in a scene.
  29756. *
  29757. * @tsl
  29758. * @function
  29759. * @param {Renderer} renderer - The renderer.
  29760. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29761. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29762. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29763. * @return {Function} A function that renders shadow objects.
  29764. *
  29765. * The returned function has the following parameters:
  29766. * @param {Object3D} object - The 3D object to render.
  29767. * @param {Scene} scene - The scene containing the object.
  29768. * @param {Camera} _camera - The camera used for rendering.
  29769. * @param {BufferGeometry} geometry - The geometry of the object.
  29770. * @param {Material} material - The material of the object.
  29771. * @param {Group} group - The group the object belongs to.
  29772. * @param {...any} params - Additional parameters for rendering.
  29773. */
  29774. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  29775. _shadowRenderObjectKeys[ 0 ] = renderer;
  29776. _shadowRenderObjectKeys[ 1 ] = shadow;
  29777. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  29778. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  29779. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  29780. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  29781. if ( useVelocity ) {
  29782. getDataFromObject( object ).useVelocity = true;
  29783. }
  29784. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29785. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  29786. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29787. }
  29788. };
  29789. renderObjectFunction.shadowType = shadowType;
  29790. renderObjectFunction.useVelocity = useVelocity;
  29791. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  29792. }
  29793. _shadowRenderObjectKeys[ 0 ] = null;
  29794. _shadowRenderObjectKeys[ 1 ] = null;
  29795. return renderObjectFunction;
  29796. };
  29797. /**
  29798. * Represents the shader code for the first VSM render pass.
  29799. *
  29800. * @method
  29801. * @param {Object} inputs - The input parameter object.
  29802. * @param {Node<float>} inputs.samples - The number of samples
  29803. * @param {Node<float>} inputs.radius - The radius.
  29804. * @param {Node<float>} inputs.size - The size.
  29805. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  29806. * @return {Node<vec2>} The VSM output.
  29807. */
  29808. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29809. const mean = float( 0 ).toVar( 'meanVertical' );
  29810. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  29811. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29812. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29813. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29814. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29815. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  29816. if ( shadowPass.value.isArrayTexture ) {
  29817. depth = depth.depth( depthLayer );
  29818. }
  29819. depth = depth.x;
  29820. mean.addAssign( depth );
  29821. squaredMean.addAssign( depth.mul( depth ) );
  29822. } );
  29823. mean.divAssign( samples );
  29824. squaredMean.divAssign( samples );
  29825. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29826. return vec2( mean, std_dev );
  29827. } );
  29828. /**
  29829. * Represents the shader code for the second VSM render pass.
  29830. *
  29831. * @method
  29832. * @param {Object} inputs - The input parameter object.
  29833. * @param {Node<float>} inputs.samples - The number of samples
  29834. * @param {Node<float>} inputs.radius - The radius.
  29835. * @param {Node<float>} inputs.size - The size.
  29836. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  29837. * @return {Node<vec2>} The VSM output.
  29838. */
  29839. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29840. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29841. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29842. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29843. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29844. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29845. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29846. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29847. if ( shadowPass.value.isArrayTexture ) {
  29848. distribution = distribution.depth( depthLayer );
  29849. }
  29850. mean.addAssign( distribution.x );
  29851. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29852. } );
  29853. mean.divAssign( samples );
  29854. squaredMean.divAssign( samples );
  29855. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29856. return vec2( mean, std_dev );
  29857. } );
  29858. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29859. //
  29860. let _rendererState;
  29861. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29862. /**
  29863. * Represents the default shadow implementation for lighting nodes.
  29864. *
  29865. * @augments ShadowBaseNode
  29866. */
  29867. class ShadowNode extends ShadowBaseNode {
  29868. static get type() {
  29869. return 'ShadowNode';
  29870. }
  29871. /**
  29872. * Constructs a new shadow node.
  29873. *
  29874. * @param {Light} light - The shadow casting light.
  29875. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29876. */
  29877. constructor( light, shadow = null ) {
  29878. super( light );
  29879. /**
  29880. * The light shadow which defines the properties light's
  29881. * shadow.
  29882. *
  29883. * @type {?LightShadow}
  29884. * @default null
  29885. */
  29886. this.shadow = shadow || light.shadow;
  29887. /**
  29888. * A reference to the shadow map which is a render target.
  29889. *
  29890. * @type {?RenderTarget}
  29891. * @default null
  29892. */
  29893. this.shadowMap = null;
  29894. /**
  29895. * Only relevant for VSM shadows. Render target for the
  29896. * first VSM render pass.
  29897. *
  29898. * @type {?RenderTarget}
  29899. * @default null
  29900. */
  29901. this.vsmShadowMapVertical = null;
  29902. /**
  29903. * Only relevant for VSM shadows. Render target for the
  29904. * second VSM render pass.
  29905. *
  29906. * @type {?RenderTarget}
  29907. * @default null
  29908. */
  29909. this.vsmShadowMapHorizontal = null;
  29910. /**
  29911. * Only relevant for VSM shadows. Node material which
  29912. * is used to render the first VSM pass.
  29913. *
  29914. * @type {?NodeMaterial}
  29915. * @default null
  29916. */
  29917. this.vsmMaterialVertical = null;
  29918. /**
  29919. * Only relevant for VSM shadows. Node material which
  29920. * is used to render the second VSM pass.
  29921. *
  29922. * @type {?NodeMaterial}
  29923. * @default null
  29924. */
  29925. this.vsmMaterialHorizontal = null;
  29926. /**
  29927. * A reference to the output node which defines the
  29928. * final result of this shadow node.
  29929. *
  29930. * @type {?Node}
  29931. * @private
  29932. * @default null
  29933. */
  29934. this._node = null;
  29935. this._cameraFrameId = new WeakMap();
  29936. /**
  29937. * This flag can be used for type testing.
  29938. *
  29939. * @type {boolean}
  29940. * @readonly
  29941. * @default true
  29942. */
  29943. this.isShadowNode = true;
  29944. /**
  29945. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29946. *
  29947. * @type {number}
  29948. * @readonly
  29949. * @default true
  29950. */
  29951. this.depthLayer = 0;
  29952. }
  29953. /**
  29954. * Setups the shadow filtering.
  29955. *
  29956. * @param {NodeBuilder} builder - A reference to the current node builder.
  29957. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29958. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29959. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29960. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29961. * @param {LightShadow} inputs.shadow - The light shadow.
  29962. * @return {Node<float>} The result node of the shadow filtering.
  29963. */
  29964. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29965. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29966. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29967. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29968. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29969. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29970. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29971. return frustumTest.select( shadowNode, float( 1 ) );
  29972. }
  29973. /**
  29974. * Setups the shadow coordinates.
  29975. *
  29976. * @param {NodeBuilder} builder - A reference to the current node builder.
  29977. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29978. * @return {Node<vec3>} The shadow coordinates.
  29979. */
  29980. setupShadowCoord( builder, shadowPosition ) {
  29981. const { shadow } = this;
  29982. const { renderer } = builder;
  29983. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29984. let shadowCoord = shadowPosition;
  29985. let coordZ;
  29986. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29987. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29988. coordZ = shadowCoord.z;
  29989. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29990. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29991. }
  29992. } else {
  29993. const w = shadowCoord.w;
  29994. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29995. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  29996. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  29997. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  29998. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  29999. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  30000. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  30001. }
  30002. shadowCoord = vec3(
  30003. shadowCoord.x,
  30004. shadowCoord.y.oneMinus(), // follow webgpu standards
  30005. coordZ.add( bias )
  30006. );
  30007. return shadowCoord;
  30008. }
  30009. /**
  30010. * Returns the shadow filtering function for the given shadow type.
  30011. *
  30012. * @param {number} type - The shadow type.
  30013. * @return {Function} The filtering function.
  30014. */
  30015. getShadowFilterFn( type ) {
  30016. return _shadowFilterLib[ type ];
  30017. }
  30018. setupRenderTarget( shadow, builder ) {
  30019. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  30020. depthTexture.name = 'ShadowDepthTexture';
  30021. depthTexture.compareFunction = LessCompare;
  30022. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  30023. shadowMap.texture.name = 'ShadowMap';
  30024. shadowMap.texture.type = shadow.mapType;
  30025. shadowMap.depthTexture = depthTexture;
  30026. return { shadowMap, depthTexture };
  30027. }
  30028. /**
  30029. * Setups the shadow output node.
  30030. *
  30031. * @param {NodeBuilder} builder - A reference to the current node builder.
  30032. * @return {Node<vec3>} The shadow output node.
  30033. */
  30034. setupShadow( builder ) {
  30035. const { renderer, camera } = builder;
  30036. const { light, shadow } = this;
  30037. const shadowMapType = renderer.shadowMap.type;
  30038. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  30039. shadow.camera.coordinateSystem = camera.coordinateSystem;
  30040. shadow.camera.updateProjectionMatrix();
  30041. // VSM
  30042. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30043. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  30044. if ( shadowMap.depth > 1 ) {
  30045. if ( ! shadowMap._vsmShadowMapVertical ) {
  30046. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30047. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  30048. }
  30049. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  30050. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  30051. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30052. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  30053. }
  30054. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  30055. } else {
  30056. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30057. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30058. }
  30059. let shadowPassVertical = texture( depthTexture );
  30060. if ( depthTexture.isArrayTexture ) {
  30061. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  30062. }
  30063. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  30064. if ( depthTexture.isArrayTexture ) {
  30065. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  30066. }
  30067. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  30068. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30069. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30070. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  30071. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30072. material.name = 'VSMVertical';
  30073. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  30074. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30075. material.name = 'VSMHorizontal';
  30076. }
  30077. //
  30078. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  30079. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  30080. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  30081. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  30082. //
  30083. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  30084. if ( filterFn === null ) {
  30085. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  30086. }
  30087. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  30088. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  30089. let shadowColor = texture( shadowMap.texture, shadowCoord );
  30090. if ( depthTexture.isArrayTexture ) {
  30091. shadowColor = shadowColor.depth( this.depthLayer );
  30092. }
  30093. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  30094. this.shadowMap = shadowMap;
  30095. this.shadow.map = shadowMap;
  30096. // Shadow Output + Inspector
  30097. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  30098. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  30099. return texture( this.shadowMap.texture );
  30100. } ).toInspector( `${ inspectName } / Depth`, () => {
  30101. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  30102. } );
  30103. }
  30104. /**
  30105. * The implementation performs the setup of the output node. An output is only
  30106. * produces if shadow mapping is globally enabled in the renderer.
  30107. *
  30108. * @param {NodeBuilder} builder - A reference to the current node builder.
  30109. * @return {ShaderCallNodeInternal} The output node.
  30110. */
  30111. setup( builder ) {
  30112. if ( builder.renderer.shadowMap.enabled === false ) return;
  30113. return Fn( () => {
  30114. let node = this._node;
  30115. this.setupShadowPosition( builder );
  30116. if ( node === null ) {
  30117. this._node = node = this.setupShadow( builder );
  30118. }
  30119. if ( builder.material.shadowNode ) { // @deprecated, r171
  30120. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  30121. }
  30122. if ( builder.material.receivedShadowNode ) {
  30123. node = builder.material.receivedShadowNode( node );
  30124. }
  30125. return node;
  30126. } )();
  30127. }
  30128. /**
  30129. * Renders the shadow. The logic of this function could be included
  30130. * into {@link ShadowNode#updateShadow} however more specialized shadow
  30131. * nodes might require a custom shadow map rendering. By having a
  30132. * dedicated method, it's easier to overwrite the default behavior.
  30133. *
  30134. * @param {NodeFrame} frame - A reference to the current node frame.
  30135. */
  30136. renderShadow( frame ) {
  30137. const { shadow, shadowMap, light } = this;
  30138. const { renderer, scene } = frame;
  30139. shadow.updateMatrices( light );
  30140. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  30141. const currentSceneName = scene.name;
  30142. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  30143. renderer.render( scene, shadow.camera );
  30144. scene.name = currentSceneName;
  30145. }
  30146. /**
  30147. * Updates the shadow.
  30148. *
  30149. * @param {NodeFrame} frame - A reference to the current node frame.
  30150. */
  30151. updateShadow( frame ) {
  30152. const { shadowMap, light, shadow } = this;
  30153. const { renderer, scene, camera } = frame;
  30154. const shadowType = renderer.shadowMap.type;
  30155. const depthVersion = shadowMap.depthTexture.version;
  30156. this._depthVersionCached = depthVersion;
  30157. const _shadowCameraLayer = shadow.camera.layers.mask;
  30158. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  30159. shadow.camera.layers.mask = camera.layers.mask;
  30160. }
  30161. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  30162. const currentMRT = renderer.getMRT();
  30163. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  30164. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  30165. scene.overrideMaterial = getShadowMaterial( light );
  30166. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  30167. renderer.setClearColor( 0x000000, 0 );
  30168. renderer.setRenderTarget( shadowMap );
  30169. this.renderShadow( frame );
  30170. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  30171. // vsm blur pass
  30172. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30173. this.vsmPass( renderer );
  30174. }
  30175. shadow.camera.layers.mask = _shadowCameraLayer;
  30176. restoreRendererAndSceneState( renderer, scene, _rendererState );
  30177. }
  30178. /**
  30179. * For VSM additional render passes are required.
  30180. *
  30181. * @param {Renderer} renderer - A reference to the current renderer.
  30182. */
  30183. vsmPass( renderer ) {
  30184. const { shadow } = this;
  30185. const depth = this.shadowMap.depth;
  30186. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30187. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30188. renderer.setRenderTarget( this.vsmShadowMapVertical );
  30189. _quadMesh.material = this.vsmMaterialVertical;
  30190. _quadMesh.render( renderer );
  30191. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  30192. _quadMesh.material = this.vsmMaterialHorizontal;
  30193. _quadMesh.render( renderer );
  30194. }
  30195. /**
  30196. * Frees the internal resources of this shadow node.
  30197. */
  30198. dispose() {
  30199. this.shadowMap.dispose();
  30200. this.shadowMap = null;
  30201. if ( this.vsmShadowMapVertical !== null ) {
  30202. this.vsmShadowMapVertical.dispose();
  30203. this.vsmShadowMapVertical = null;
  30204. this.vsmMaterialVertical.dispose();
  30205. this.vsmMaterialVertical = null;
  30206. }
  30207. if ( this.vsmShadowMapHorizontal !== null ) {
  30208. this.vsmShadowMapHorizontal.dispose();
  30209. this.vsmShadowMapHorizontal = null;
  30210. this.vsmMaterialHorizontal.dispose();
  30211. this.vsmMaterialHorizontal = null;
  30212. }
  30213. super.dispose();
  30214. }
  30215. /**
  30216. * The implementation performs the update of the shadow map if necessary.
  30217. *
  30218. * @param {NodeFrame} frame - A reference to the current node frame.
  30219. */
  30220. updateBefore( frame ) {
  30221. const { shadow } = this;
  30222. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  30223. if ( needsUpdate ) {
  30224. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  30225. needsUpdate = false;
  30226. }
  30227. this._cameraFrameId[ frame.camera ] = frame.frameId;
  30228. }
  30229. if ( needsUpdate ) {
  30230. this.updateShadow( frame );
  30231. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  30232. shadow.needsUpdate = false;
  30233. }
  30234. }
  30235. }
  30236. }
  30237. /**
  30238. * TSL function for creating an instance of `ShadowNode`.
  30239. *
  30240. * @tsl
  30241. * @function
  30242. * @param {Light} light - The shadow casting light.
  30243. * @param {?LightShadow} [shadow] - The light shadow.
  30244. * @return {ShadowNode} The created shadow node.
  30245. */
  30246. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  30247. const _clearColor$1 = /*@__PURE__*/ new Color();
  30248. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  30249. // vector suitable for 2D texture mapping. This code uses the following layout for the
  30250. // 2D texture:
  30251. //
  30252. // xzXZ
  30253. // y Y
  30254. //
  30255. // Y - Positive y direction
  30256. // y - Negative y direction
  30257. // X - Positive x direction
  30258. // x - Negative x direction
  30259. // Z - Positive z direction
  30260. // z - Negative z direction
  30261. //
  30262. // Source and test bed:
  30263. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  30264. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  30265. const v = pos.toVar();
  30266. // Number of texels to avoid at the edge of each square
  30267. const absV = abs( v );
  30268. // Intersect unit cube
  30269. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  30270. absV.mulAssign( scaleToCube );
  30271. // Apply scale to avoid seams
  30272. // two texels less per square (one texel will do for NEAREST)
  30273. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  30274. // Unwrap
  30275. // space: -1 ... 1 range for each square
  30276. //
  30277. // #X## dim := ( 4 , 2 )
  30278. // # # center := ( 1 , 1 )
  30279. const planar = vec2( v.xy ).toVar();
  30280. const almostATexel = texelSizeY.mul( 1.5 );
  30281. const almostOne = almostATexel.oneMinus();
  30282. If( absV.z.greaterThanEqual( almostOne ), () => {
  30283. If( v.z.greaterThan( 0.0 ), () => {
  30284. planar.x.assign( sub( 4.0, v.x ) );
  30285. } );
  30286. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  30287. const signX = sign( v.x );
  30288. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  30289. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  30290. const signY = sign( v.y );
  30291. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  30292. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  30293. } );
  30294. // Transform to UV space
  30295. // scale := 0.5 / dim
  30296. // translate := ( center + 0.5 ) / dim
  30297. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  30298. } ).setLayout( {
  30299. name: 'cubeToUV',
  30300. type: 'vec2',
  30301. inputs: [
  30302. { name: 'pos', type: 'vec3' },
  30303. { name: 'texelSizeY', type: 'float' }
  30304. ]
  30305. } );
  30306. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  30307. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  30308. } );
  30309. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  30310. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30311. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  30312. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  30313. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  30314. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  30315. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  30316. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  30317. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  30318. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  30319. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  30320. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  30321. .mul( 1.0 / 9.0 );
  30322. } );
  30323. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  30324. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  30325. // the vector from the light to the world-space position of the fragment.
  30326. const lightToPosition = shadowCoord.xyz.toVar();
  30327. const lightToPositionLength = lightToPosition.length();
  30328. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  30329. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  30330. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30331. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  30332. const result = float( 1.0 ).toVar();
  30333. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  30334. // dp = normalized distance from light to fragment position
  30335. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  30336. dp.addAssign( bias );
  30337. // bd3D = base direction 3D
  30338. const bd3D = lightToPosition.normalize();
  30339. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  30340. // percentage-closer filtering
  30341. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  30342. } );
  30343. return result;
  30344. } );
  30345. const _viewport = /*@__PURE__*/ new Vector4();
  30346. const _viewportSize = /*@__PURE__*/ new Vector2();
  30347. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  30348. /**
  30349. * Represents the shadow implementation for point light nodes.
  30350. *
  30351. * @augments ShadowNode
  30352. */
  30353. class PointShadowNode extends ShadowNode {
  30354. static get type() {
  30355. return 'PointShadowNode';
  30356. }
  30357. /**
  30358. * Constructs a new point shadow node.
  30359. *
  30360. * @param {PointLight} light - The shadow casting point light.
  30361. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30362. */
  30363. constructor( light, shadow = null ) {
  30364. super( light, shadow );
  30365. }
  30366. /**
  30367. * Overwrites the default implementation to return point light shadow specific
  30368. * filtering functions.
  30369. *
  30370. * @param {number} type - The shadow type.
  30371. * @return {Function} The filtering function.
  30372. */
  30373. getShadowFilterFn( type ) {
  30374. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  30375. }
  30376. /**
  30377. * Overwrites the default implementation so the unaltered shadow position is used.
  30378. *
  30379. * @param {NodeBuilder} builder - A reference to the current node builder.
  30380. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30381. * @return {Node<vec3>} The shadow coordinates.
  30382. */
  30383. setupShadowCoord( builder, shadowPosition ) {
  30384. return shadowPosition;
  30385. }
  30386. /**
  30387. * Overwrites the default implementation to only use point light specific
  30388. * shadow filter functions.
  30389. *
  30390. * @param {NodeBuilder} builder - A reference to the current node builder.
  30391. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30392. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30393. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  30394. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30395. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30396. * @param {LightShadow} inputs.shadow - The light shadow.
  30397. * @return {Node<float>} The result node of the shadow filtering.
  30398. */
  30399. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  30400. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  30401. }
  30402. /**
  30403. * Overwrites the default implementation with point light specific
  30404. * rendering code.
  30405. *
  30406. * @param {NodeFrame} frame - A reference to the current node frame.
  30407. */
  30408. renderShadow( frame ) {
  30409. const { shadow, shadowMap, light } = this;
  30410. const { renderer, scene } = frame;
  30411. const shadowFrameExtents = shadow.getFrameExtents();
  30412. _shadowMapSize.copy( shadow.mapSize );
  30413. _shadowMapSize.multiply( shadowFrameExtents );
  30414. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  30415. _viewportSize.copy( shadow.mapSize );
  30416. //
  30417. const previousAutoClear = renderer.autoClear;
  30418. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  30419. const previousClearAlpha = renderer.getClearAlpha();
  30420. renderer.autoClear = false;
  30421. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  30422. renderer.clear();
  30423. const viewportCount = shadow.getViewportCount();
  30424. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  30425. const viewport = shadow.getViewport( vp );
  30426. const x = _viewportSize.x * viewport.x;
  30427. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  30428. _viewport.set(
  30429. x,
  30430. y,
  30431. _viewportSize.x * viewport.z,
  30432. _viewportSize.y * viewport.w
  30433. );
  30434. shadowMap.viewport.copy( _viewport );
  30435. shadow.updateMatrices( light, vp );
  30436. const currentSceneName = scene.name;
  30437. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  30438. renderer.render( scene, shadow.camera );
  30439. scene.name = currentSceneName;
  30440. }
  30441. //
  30442. renderer.autoClear = previousAutoClear;
  30443. renderer.setClearColor( previousClearColor, previousClearAlpha );
  30444. }
  30445. }
  30446. /**
  30447. * TSL function for creating an instance of `PointShadowNode`.
  30448. *
  30449. * @tsl
  30450. * @function
  30451. * @param {PointLight} light - The shadow casting point light.
  30452. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30453. * @return {PointShadowNode} The created point shadow node.
  30454. */
  30455. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  30456. /**
  30457. * Base class for analytic light nodes.
  30458. *
  30459. * @augments LightingNode
  30460. */
  30461. class AnalyticLightNode extends LightingNode {
  30462. static get type() {
  30463. return 'AnalyticLightNode';
  30464. }
  30465. /**
  30466. * Constructs a new analytic light node.
  30467. *
  30468. * @param {?Light} [light=null] - The light source.
  30469. */
  30470. constructor( light = null ) {
  30471. super();
  30472. /**
  30473. * The light source.
  30474. *
  30475. * @type {?Light}
  30476. * @default null
  30477. */
  30478. this.light = light;
  30479. /**
  30480. * The light's color value.
  30481. *
  30482. * @type {Color}
  30483. */
  30484. this.color = new Color();
  30485. /**
  30486. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  30487. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  30488. *
  30489. * @type {Node}
  30490. */
  30491. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  30492. /**
  30493. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  30494. * The final color node is represented by a different node when using shadows.
  30495. *
  30496. * @type {?Node}
  30497. * @default null
  30498. */
  30499. this.baseColorNode = null;
  30500. /**
  30501. * Represents the light's shadow.
  30502. *
  30503. * @type {?ShadowNode}
  30504. * @default null
  30505. */
  30506. this.shadowNode = null;
  30507. /**
  30508. * Represents the light's shadow color.
  30509. *
  30510. * @type {?Node}
  30511. * @default null
  30512. */
  30513. this.shadowColorNode = null;
  30514. /**
  30515. * This flag can be used for type testing.
  30516. *
  30517. * @type {boolean}
  30518. * @readonly
  30519. * @default true
  30520. */
  30521. this.isAnalyticLightNode = true;
  30522. /**
  30523. * Overwritten since analytic light nodes are updated
  30524. * once per frame.
  30525. *
  30526. * @type {string}
  30527. * @default 'frame'
  30528. */
  30529. this.updateType = NodeUpdateType.FRAME;
  30530. }
  30531. getHash() {
  30532. return this.light.uuid;
  30533. }
  30534. /**
  30535. * Returns a node representing a direction vector which points from the current
  30536. * position in view space to the light's position in view space.
  30537. *
  30538. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30539. * @return {Node<vec3>} The light vector node.
  30540. */
  30541. getLightVector( builder ) {
  30542. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  30543. }
  30544. /**
  30545. * Sets up the direct lighting for the analytic light node.
  30546. *
  30547. * @abstract
  30548. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30549. * @return {Object|undefined} The direct light data (color and direction).
  30550. */
  30551. setupDirect( /*builder*/ ) { }
  30552. /**
  30553. * Sets up the direct rect area lighting for the analytic light node.
  30554. *
  30555. * @abstract
  30556. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30557. * @return {Object|undefined} The direct rect area light data.
  30558. */
  30559. setupDirectRectArea( /*builder*/ ) { }
  30560. /**
  30561. * Setups the shadow node for this light. The method exists so concrete light classes
  30562. * can setup different types of shadow nodes.
  30563. *
  30564. * @return {ShadowNode} The created shadow node.
  30565. */
  30566. setupShadowNode() {
  30567. return shadow( this.light );
  30568. }
  30569. /**
  30570. * Setups the shadow for this light. This method is only executed if the light
  30571. * cast shadows and the current build object receives shadows. It incorporates
  30572. * shadows into the lighting computation.
  30573. *
  30574. * @param {NodeBuilder} builder - The current node builder.
  30575. */
  30576. setupShadow( builder ) {
  30577. const { renderer } = builder;
  30578. if ( renderer.shadowMap.enabled === false ) return;
  30579. let shadowColorNode = this.shadowColorNode;
  30580. if ( shadowColorNode === null ) {
  30581. const customShadowNode = this.light.shadow.shadowNode;
  30582. let shadowNode;
  30583. if ( customShadowNode !== undefined ) {
  30584. shadowNode = nodeObject( customShadowNode );
  30585. } else {
  30586. shadowNode = this.setupShadowNode();
  30587. }
  30588. this.shadowNode = shadowNode;
  30589. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30590. this.baseColorNode = this.colorNode;
  30591. }
  30592. //
  30593. this.colorNode = shadowColorNode;
  30594. }
  30595. /**
  30596. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30597. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30598. * invocate the respective interface methods.
  30599. *
  30600. * @param {NodeBuilder} builder - The current node builder.
  30601. */
  30602. setup( builder ) {
  30603. this.colorNode = this.baseColorNode || this.colorNode;
  30604. if ( this.light.castShadow ) {
  30605. if ( builder.object.receiveShadow ) {
  30606. this.setupShadow( builder );
  30607. }
  30608. } else if ( this.shadowNode !== null ) {
  30609. this.shadowNode.dispose();
  30610. this.shadowNode = null;
  30611. this.shadowColorNode = null;
  30612. }
  30613. const directLightData = this.setupDirect( builder );
  30614. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30615. if ( directLightData ) {
  30616. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30617. }
  30618. if ( directRectAreaLightData ) {
  30619. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30620. }
  30621. }
  30622. /**
  30623. * The update method is used to update light uniforms per frame.
  30624. * Potentially overwritten in concrete light nodes to update light
  30625. * specific uniforms.
  30626. *
  30627. * @param {NodeFrame} frame - A reference to the current node frame.
  30628. */
  30629. update( /*frame*/ ) {
  30630. const { light } = this;
  30631. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30632. }
  30633. }
  30634. /**
  30635. * Represents a `discard` shader operation in TSL.
  30636. *
  30637. * @method
  30638. * @param {Object} inputs - The input parameter object.
  30639. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30640. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30641. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30642. * @return {Node<float>} The distance falloff.
  30643. */
  30644. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30645. // based upon Frostbite 3 Moving to Physically-based Rendering
  30646. // page 32, equation 26: E[window1]
  30647. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30648. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30649. return cutoffDistance.greaterThan( 0 ).select(
  30650. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30651. distanceFalloff
  30652. );
  30653. } ); // validated
  30654. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30655. const lightDirection = lightVector.normalize();
  30656. const lightDistance = lightVector.length();
  30657. const attenuation = getDistanceAttenuation( {
  30658. lightDistance,
  30659. cutoffDistance,
  30660. decayExponent
  30661. } );
  30662. const lightColor = color.mul( attenuation );
  30663. return { lightDirection, lightColor };
  30664. };
  30665. /**
  30666. * Module for representing point lights as nodes.
  30667. *
  30668. * @augments AnalyticLightNode
  30669. */
  30670. class PointLightNode extends AnalyticLightNode {
  30671. static get type() {
  30672. return 'PointLightNode';
  30673. }
  30674. /**
  30675. * Constructs a new point light node.
  30676. *
  30677. * @param {?PointLight} [light=null] - The point light source.
  30678. */
  30679. constructor( light = null ) {
  30680. super( light );
  30681. /**
  30682. * Uniform node representing the cutoff distance.
  30683. *
  30684. * @type {UniformNode<float>}
  30685. */
  30686. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30687. /**
  30688. * Uniform node representing the decay exponent.
  30689. *
  30690. * @type {UniformNode<float>}
  30691. */
  30692. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30693. }
  30694. /**
  30695. * Overwritten to updated point light specific uniforms.
  30696. *
  30697. * @param {NodeFrame} frame - A reference to the current node frame.
  30698. */
  30699. update( frame ) {
  30700. const { light } = this;
  30701. super.update( frame );
  30702. this.cutoffDistanceNode.value = light.distance;
  30703. this.decayExponentNode.value = light.decay;
  30704. }
  30705. /**
  30706. * Overwritten to setup point light specific shadow.
  30707. *
  30708. * @return {PointShadowNode}
  30709. */
  30710. setupShadowNode() {
  30711. return pointShadow( this.light );
  30712. }
  30713. setupDirect( builder ) {
  30714. return directPointLight( {
  30715. color: this.colorNode,
  30716. lightVector: this.getLightVector( builder ),
  30717. cutoffDistance: this.cutoffDistanceNode,
  30718. decayExponent: this.decayExponentNode
  30719. } );
  30720. }
  30721. }
  30722. /**
  30723. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30724. *
  30725. * @tsl
  30726. * @function
  30727. * @param {Node<vec2>} coord - The uv coordinates.
  30728. * @return {Node<float>} The result data.
  30729. */
  30730. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30731. const uv = coord.mul( 2.0 );
  30732. const cx = uv.x.floor();
  30733. const cy = uv.y.floor();
  30734. const result = cx.add( cy ).mod( 2.0 );
  30735. return result.sign();
  30736. } );
  30737. /**
  30738. * Generates a circle based on the uv coordinates.
  30739. *
  30740. * @tsl
  30741. * @function
  30742. * @param {Node<vec2>} coord - The uv to generate the circle.
  30743. * @return {Node<float>} The circle shape.
  30744. */
  30745. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  30746. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  30747. let alpha;
  30748. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  30749. const dlen = float( len2.fwidth() ).toVar();
  30750. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  30751. } else {
  30752. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  30753. }
  30754. return alpha;
  30755. } );
  30756. // Three.js Transpiler
  30757. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  30758. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  30759. const f = float( f_immutable ).toVar();
  30760. const t = float( t_immutable ).toVar();
  30761. const b = bool( b_immutable ).toVar();
  30762. return select( b, t, f );
  30763. } ).setLayout( {
  30764. name: 'mx_select',
  30765. type: 'float',
  30766. inputs: [
  30767. { name: 'b', type: 'bool' },
  30768. { name: 't', type: 'float' },
  30769. { name: 'f', type: 'float' }
  30770. ]
  30771. } );
  30772. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  30773. const b = bool( b_immutable ).toVar();
  30774. const val = float( val_immutable ).toVar();
  30775. return select( b, val.negate(), val );
  30776. } ).setLayout( {
  30777. name: 'mx_negate_if',
  30778. type: 'float',
  30779. inputs: [
  30780. { name: 'val', type: 'float' },
  30781. { name: 'b', type: 'bool' }
  30782. ]
  30783. } );
  30784. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30785. const x = float( x_immutable ).toVar();
  30786. return int( floor( x ) );
  30787. } ).setLayout( {
  30788. name: 'mx_floor',
  30789. type: 'int',
  30790. inputs: [
  30791. { name: 'x', type: 'float' }
  30792. ]
  30793. } );
  30794. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  30795. const x = float( x_immutable ).toVar();
  30796. i.assign( mx_floor( x ) );
  30797. return x.sub( float( i ) );
  30798. } );
  30799. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30800. const t = float( t_immutable ).toVar();
  30801. const s = float( s_immutable ).toVar();
  30802. const v3 = float( v3_immutable ).toVar();
  30803. const v2 = float( v2_immutable ).toVar();
  30804. const v1 = float( v1_immutable ).toVar();
  30805. const v0 = float( v0_immutable ).toVar();
  30806. const s1 = float( sub( 1.0, s ) ).toVar();
  30807. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30808. } ).setLayout( {
  30809. name: 'mx_bilerp_0',
  30810. type: 'float',
  30811. inputs: [
  30812. { name: 'v0', type: 'float' },
  30813. { name: 'v1', type: 'float' },
  30814. { name: 'v2', type: 'float' },
  30815. { name: 'v3', type: 'float' },
  30816. { name: 's', type: 'float' },
  30817. { name: 't', type: 'float' }
  30818. ]
  30819. } );
  30820. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30821. const t = float( t_immutable ).toVar();
  30822. const s = float( s_immutable ).toVar();
  30823. const v3 = vec3( v3_immutable ).toVar();
  30824. const v2 = vec3( v2_immutable ).toVar();
  30825. const v1 = vec3( v1_immutable ).toVar();
  30826. const v0 = vec3( v0_immutable ).toVar();
  30827. const s1 = float( sub( 1.0, s ) ).toVar();
  30828. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30829. } ).setLayout( {
  30830. name: 'mx_bilerp_1',
  30831. type: 'vec3',
  30832. inputs: [
  30833. { name: 'v0', type: 'vec3' },
  30834. { name: 'v1', type: 'vec3' },
  30835. { name: 'v2', type: 'vec3' },
  30836. { name: 'v3', type: 'vec3' },
  30837. { name: 's', type: 'float' },
  30838. { name: 't', type: 'float' }
  30839. ]
  30840. } );
  30841. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  30842. 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 ] ) => {
  30843. const r = float( r_immutable ).toVar();
  30844. const t = float( t_immutable ).toVar();
  30845. const s = float( s_immutable ).toVar();
  30846. const v7 = float( v7_immutable ).toVar();
  30847. const v6 = float( v6_immutable ).toVar();
  30848. const v5 = float( v5_immutable ).toVar();
  30849. const v4 = float( v4_immutable ).toVar();
  30850. const v3 = float( v3_immutable ).toVar();
  30851. const v2 = float( v2_immutable ).toVar();
  30852. const v1 = float( v1_immutable ).toVar();
  30853. const v0 = float( v0_immutable ).toVar();
  30854. const s1 = float( sub( 1.0, s ) ).toVar();
  30855. const t1 = float( sub( 1.0, t ) ).toVar();
  30856. const r1 = float( sub( 1.0, r ) ).toVar();
  30857. 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 ) ) ) ) ) );
  30858. } ).setLayout( {
  30859. name: 'mx_trilerp_0',
  30860. type: 'float',
  30861. inputs: [
  30862. { name: 'v0', type: 'float' },
  30863. { name: 'v1', type: 'float' },
  30864. { name: 'v2', type: 'float' },
  30865. { name: 'v3', type: 'float' },
  30866. { name: 'v4', type: 'float' },
  30867. { name: 'v5', type: 'float' },
  30868. { name: 'v6', type: 'float' },
  30869. { name: 'v7', type: 'float' },
  30870. { name: 's', type: 'float' },
  30871. { name: 't', type: 'float' },
  30872. { name: 'r', type: 'float' }
  30873. ]
  30874. } );
  30875. 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 ] ) => {
  30876. const r = float( r_immutable ).toVar();
  30877. const t = float( t_immutable ).toVar();
  30878. const s = float( s_immutable ).toVar();
  30879. const v7 = vec3( v7_immutable ).toVar();
  30880. const v6 = vec3( v6_immutable ).toVar();
  30881. const v5 = vec3( v5_immutable ).toVar();
  30882. const v4 = vec3( v4_immutable ).toVar();
  30883. const v3 = vec3( v3_immutable ).toVar();
  30884. const v2 = vec3( v2_immutable ).toVar();
  30885. const v1 = vec3( v1_immutable ).toVar();
  30886. const v0 = vec3( v0_immutable ).toVar();
  30887. const s1 = float( sub( 1.0, s ) ).toVar();
  30888. const t1 = float( sub( 1.0, t ) ).toVar();
  30889. const r1 = float( sub( 1.0, r ) ).toVar();
  30890. 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 ) ) ) ) ) );
  30891. } ).setLayout( {
  30892. name: 'mx_trilerp_1',
  30893. type: 'vec3',
  30894. inputs: [
  30895. { name: 'v0', type: 'vec3' },
  30896. { name: 'v1', type: 'vec3' },
  30897. { name: 'v2', type: 'vec3' },
  30898. { name: 'v3', type: 'vec3' },
  30899. { name: 'v4', type: 'vec3' },
  30900. { name: 'v5', type: 'vec3' },
  30901. { name: 'v6', type: 'vec3' },
  30902. { name: 'v7', type: 'vec3' },
  30903. { name: 's', type: 'float' },
  30904. { name: 't', type: 'float' },
  30905. { name: 'r', type: 'float' }
  30906. ]
  30907. } );
  30908. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30909. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30910. const y = float( y_immutable ).toVar();
  30911. const x = float( x_immutable ).toVar();
  30912. const hash = uint( hash_immutable ).toVar();
  30913. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30914. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30915. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30916. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30917. } ).setLayout( {
  30918. name: 'mx_gradient_float_0',
  30919. type: 'float',
  30920. inputs: [
  30921. { name: 'hash', type: 'uint' },
  30922. { name: 'x', type: 'float' },
  30923. { name: 'y', type: 'float' }
  30924. ]
  30925. } );
  30926. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30927. const z = float( z_immutable ).toVar();
  30928. const y = float( y_immutable ).toVar();
  30929. const x = float( x_immutable ).toVar();
  30930. const hash = uint( hash_immutable ).toVar();
  30931. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30932. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30933. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30934. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30935. } ).setLayout( {
  30936. name: 'mx_gradient_float_1',
  30937. type: 'float',
  30938. inputs: [
  30939. { name: 'hash', type: 'uint' },
  30940. { name: 'x', type: 'float' },
  30941. { name: 'y', type: 'float' },
  30942. { name: 'z', type: 'float' }
  30943. ]
  30944. } );
  30945. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30946. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30947. const y = float( y_immutable ).toVar();
  30948. const x = float( x_immutable ).toVar();
  30949. const hash = uvec3( hash_immutable ).toVar();
  30950. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30951. } ).setLayout( {
  30952. name: 'mx_gradient_vec3_0',
  30953. type: 'vec3',
  30954. inputs: [
  30955. { name: 'hash', type: 'uvec3' },
  30956. { name: 'x', type: 'float' },
  30957. { name: 'y', type: 'float' }
  30958. ]
  30959. } );
  30960. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30961. const z = float( z_immutable ).toVar();
  30962. const y = float( y_immutable ).toVar();
  30963. const x = float( x_immutable ).toVar();
  30964. const hash = uvec3( hash_immutable ).toVar();
  30965. 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 ) );
  30966. } ).setLayout( {
  30967. name: 'mx_gradient_vec3_1',
  30968. type: 'vec3',
  30969. inputs: [
  30970. { name: 'hash', type: 'uvec3' },
  30971. { name: 'x', type: 'float' },
  30972. { name: 'y', type: 'float' },
  30973. { name: 'z', type: 'float' }
  30974. ]
  30975. } );
  30976. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30977. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30978. const v = float( v_immutable ).toVar();
  30979. return mul( 0.6616, v );
  30980. } ).setLayout( {
  30981. name: 'mx_gradient_scale2d_0',
  30982. type: 'float',
  30983. inputs: [
  30984. { name: 'v', type: 'float' }
  30985. ]
  30986. } );
  30987. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30988. const v = float( v_immutable ).toVar();
  30989. return mul( 0.9820, v );
  30990. } ).setLayout( {
  30991. name: 'mx_gradient_scale3d_0',
  30992. type: 'float',
  30993. inputs: [
  30994. { name: 'v', type: 'float' }
  30995. ]
  30996. } );
  30997. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30998. const v = vec3( v_immutable ).toVar();
  30999. return mul( 0.6616, v );
  31000. } ).setLayout( {
  31001. name: 'mx_gradient_scale2d_1',
  31002. type: 'vec3',
  31003. inputs: [
  31004. { name: 'v', type: 'vec3' }
  31005. ]
  31006. } );
  31007. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  31008. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31009. const v = vec3( v_immutable ).toVar();
  31010. return mul( 0.9820, v );
  31011. } ).setLayout( {
  31012. name: 'mx_gradient_scale3d_1',
  31013. type: 'vec3',
  31014. inputs: [
  31015. { name: 'v', type: 'vec3' }
  31016. ]
  31017. } );
  31018. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  31019. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  31020. const k = int( k_immutable ).toVar();
  31021. const x = uint( x_immutable ).toVar();
  31022. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  31023. } ).setLayout( {
  31024. name: 'mx_rotl32',
  31025. type: 'uint',
  31026. inputs: [
  31027. { name: 'x', type: 'uint' },
  31028. { name: 'k', type: 'int' }
  31029. ]
  31030. } );
  31031. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  31032. a.subAssign( c );
  31033. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  31034. c.addAssign( b );
  31035. b.subAssign( a );
  31036. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  31037. a.addAssign( c );
  31038. c.subAssign( b );
  31039. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  31040. b.addAssign( a );
  31041. a.subAssign( c );
  31042. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  31043. c.addAssign( b );
  31044. b.subAssign( a );
  31045. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  31046. a.addAssign( c );
  31047. c.subAssign( b );
  31048. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  31049. b.addAssign( a );
  31050. } );
  31051. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  31052. const c = uint( c_immutable ).toVar();
  31053. const b = uint( b_immutable ).toVar();
  31054. const a = uint( a_immutable ).toVar();
  31055. c.bitXorAssign( b );
  31056. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  31057. a.bitXorAssign( c );
  31058. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  31059. b.bitXorAssign( a );
  31060. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  31061. c.bitXorAssign( b );
  31062. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  31063. a.bitXorAssign( c );
  31064. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  31065. b.bitXorAssign( a );
  31066. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  31067. c.bitXorAssign( b );
  31068. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  31069. return c;
  31070. } ).setLayout( {
  31071. name: 'mx_bjfinal',
  31072. type: 'uint',
  31073. inputs: [
  31074. { name: 'a', type: 'uint' },
  31075. { name: 'b', type: 'uint' },
  31076. { name: 'c', type: 'uint' }
  31077. ]
  31078. } );
  31079. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  31080. const bits = uint( bits_immutable ).toVar();
  31081. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  31082. } ).setLayout( {
  31083. name: 'mx_bits_to_01',
  31084. type: 'float',
  31085. inputs: [
  31086. { name: 'bits', type: 'uint' }
  31087. ]
  31088. } );
  31089. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  31090. const t = float( t_immutable ).toVar();
  31091. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  31092. } ).setLayout( {
  31093. name: 'mx_fade',
  31094. type: 'float',
  31095. inputs: [
  31096. { name: 't', type: 'float' }
  31097. ]
  31098. } );
  31099. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31100. const x = int( x_immutable ).toVar();
  31101. const len = uint( uint( 1 ) ).toVar();
  31102. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  31103. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  31104. } ).setLayout( {
  31105. name: 'mx_hash_int_0',
  31106. type: 'uint',
  31107. inputs: [
  31108. { name: 'x', type: 'int' }
  31109. ]
  31110. } );
  31111. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31112. const y = int( y_immutable ).toVar();
  31113. const x = int( x_immutable ).toVar();
  31114. const len = uint( uint( 2 ) ).toVar();
  31115. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31116. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31117. a.addAssign( uint( x ) );
  31118. b.addAssign( uint( y ) );
  31119. return mx_bjfinal( a, b, c );
  31120. } ).setLayout( {
  31121. name: 'mx_hash_int_1',
  31122. type: 'uint',
  31123. inputs: [
  31124. { name: 'x', type: 'int' },
  31125. { name: 'y', type: 'int' }
  31126. ]
  31127. } );
  31128. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31129. const z = int( z_immutable ).toVar();
  31130. const y = int( y_immutable ).toVar();
  31131. const x = int( x_immutable ).toVar();
  31132. const len = uint( uint( 3 ) ).toVar();
  31133. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31134. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31135. a.addAssign( uint( x ) );
  31136. b.addAssign( uint( y ) );
  31137. c.addAssign( uint( z ) );
  31138. return mx_bjfinal( a, b, c );
  31139. } ).setLayout( {
  31140. name: 'mx_hash_int_2',
  31141. type: 'uint',
  31142. inputs: [
  31143. { name: 'x', type: 'int' },
  31144. { name: 'y', type: 'int' },
  31145. { name: 'z', type: 'int' }
  31146. ]
  31147. } );
  31148. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  31149. const xx = int( xx_immutable ).toVar();
  31150. const z = int( z_immutable ).toVar();
  31151. const y = int( y_immutable ).toVar();
  31152. const x = int( x_immutable ).toVar();
  31153. const len = uint( uint( 4 ) ).toVar();
  31154. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31155. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31156. a.addAssign( uint( x ) );
  31157. b.addAssign( uint( y ) );
  31158. c.addAssign( uint( z ) );
  31159. mx_bjmix( a, b, c );
  31160. a.addAssign( uint( xx ) );
  31161. return mx_bjfinal( a, b, c );
  31162. } ).setLayout( {
  31163. name: 'mx_hash_int_3',
  31164. type: 'uint',
  31165. inputs: [
  31166. { name: 'x', type: 'int' },
  31167. { name: 'y', type: 'int' },
  31168. { name: 'z', type: 'int' },
  31169. { name: 'xx', type: 'int' }
  31170. ]
  31171. } );
  31172. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  31173. const yy = int( yy_immutable ).toVar();
  31174. const xx = int( xx_immutable ).toVar();
  31175. const z = int( z_immutable ).toVar();
  31176. const y = int( y_immutable ).toVar();
  31177. const x = int( x_immutable ).toVar();
  31178. const len = uint( uint( 5 ) ).toVar();
  31179. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31180. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31181. a.addAssign( uint( x ) );
  31182. b.addAssign( uint( y ) );
  31183. c.addAssign( uint( z ) );
  31184. mx_bjmix( a, b, c );
  31185. a.addAssign( uint( xx ) );
  31186. b.addAssign( uint( yy ) );
  31187. return mx_bjfinal( a, b, c );
  31188. } ).setLayout( {
  31189. name: 'mx_hash_int_4',
  31190. type: 'uint',
  31191. inputs: [
  31192. { name: 'x', type: 'int' },
  31193. { name: 'y', type: 'int' },
  31194. { name: 'z', type: 'int' },
  31195. { name: 'xx', type: 'int' },
  31196. { name: 'yy', type: 'int' }
  31197. ]
  31198. } );
  31199. 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 ] );
  31200. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31201. const y = int( y_immutable ).toVar();
  31202. const x = int( x_immutable ).toVar();
  31203. const h = uint( mx_hash_int( x, y ) ).toVar();
  31204. const result = uvec3().toVar();
  31205. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31206. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31207. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31208. return result;
  31209. } ).setLayout( {
  31210. name: 'mx_hash_vec3_0',
  31211. type: 'uvec3',
  31212. inputs: [
  31213. { name: 'x', type: 'int' },
  31214. { name: 'y', type: 'int' }
  31215. ]
  31216. } );
  31217. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31218. const z = int( z_immutable ).toVar();
  31219. const y = int( y_immutable ).toVar();
  31220. const x = int( x_immutable ).toVar();
  31221. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  31222. const result = uvec3().toVar();
  31223. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31224. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31225. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31226. return result;
  31227. } ).setLayout( {
  31228. name: 'mx_hash_vec3_1',
  31229. type: 'uvec3',
  31230. inputs: [
  31231. { name: 'x', type: 'int' },
  31232. { name: 'y', type: 'int' },
  31233. { name: 'z', type: 'int' }
  31234. ]
  31235. } );
  31236. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  31237. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31238. const p = vec2( p_immutable ).toVar();
  31239. const X = int().toVar(), Y = int().toVar();
  31240. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31241. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31242. const u = float( mx_fade( fx ) ).toVar();
  31243. const v = float( mx_fade( fy ) ).toVar();
  31244. 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();
  31245. return mx_gradient_scale2d( result );
  31246. } ).setLayout( {
  31247. name: 'mx_perlin_noise_float_0',
  31248. type: 'float',
  31249. inputs: [
  31250. { name: 'p', type: 'vec2' }
  31251. ]
  31252. } );
  31253. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31254. const p = vec3( p_immutable ).toVar();
  31255. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31256. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31257. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31258. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31259. const u = float( mx_fade( fx ) ).toVar();
  31260. const v = float( mx_fade( fy ) ).toVar();
  31261. const w = float( mx_fade( fz ) ).toVar();
  31262. 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();
  31263. return mx_gradient_scale3d( result );
  31264. } ).setLayout( {
  31265. name: 'mx_perlin_noise_float_1',
  31266. type: 'float',
  31267. inputs: [
  31268. { name: 'p', type: 'vec3' }
  31269. ]
  31270. } );
  31271. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  31272. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31273. const p = vec2( p_immutable ).toVar();
  31274. const X = int().toVar(), Y = int().toVar();
  31275. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31276. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31277. const u = float( mx_fade( fx ) ).toVar();
  31278. const v = float( mx_fade( fy ) ).toVar();
  31279. 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();
  31280. return mx_gradient_scale2d( result );
  31281. } ).setLayout( {
  31282. name: 'mx_perlin_noise_vec3_0',
  31283. type: 'vec3',
  31284. inputs: [
  31285. { name: 'p', type: 'vec2' }
  31286. ]
  31287. } );
  31288. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31289. const p = vec3( p_immutable ).toVar();
  31290. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31291. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31292. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31293. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31294. const u = float( mx_fade( fx ) ).toVar();
  31295. const v = float( mx_fade( fy ) ).toVar();
  31296. const w = float( mx_fade( fz ) ).toVar();
  31297. 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();
  31298. return mx_gradient_scale3d( result );
  31299. } ).setLayout( {
  31300. name: 'mx_perlin_noise_vec3_1',
  31301. type: 'vec3',
  31302. inputs: [
  31303. { name: 'p', type: 'vec3' }
  31304. ]
  31305. } );
  31306. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  31307. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31308. const p = float( p_immutable ).toVar();
  31309. const ix = int( mx_floor( p ) ).toVar();
  31310. return mx_bits_to_01( mx_hash_int( ix ) );
  31311. } ).setLayout( {
  31312. name: 'mx_cell_noise_float_0',
  31313. type: 'float',
  31314. inputs: [
  31315. { name: 'p', type: 'float' }
  31316. ]
  31317. } );
  31318. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31319. const p = vec2( p_immutable ).toVar();
  31320. const ix = int( mx_floor( p.x ) ).toVar();
  31321. const iy = int( mx_floor( p.y ) ).toVar();
  31322. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  31323. } ).setLayout( {
  31324. name: 'mx_cell_noise_float_1',
  31325. type: 'float',
  31326. inputs: [
  31327. { name: 'p', type: 'vec2' }
  31328. ]
  31329. } );
  31330. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31331. const p = vec3( p_immutable ).toVar();
  31332. const ix = int( mx_floor( p.x ) ).toVar();
  31333. const iy = int( mx_floor( p.y ) ).toVar();
  31334. const iz = int( mx_floor( p.z ) ).toVar();
  31335. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  31336. } ).setLayout( {
  31337. name: 'mx_cell_noise_float_2',
  31338. type: 'float',
  31339. inputs: [
  31340. { name: 'p', type: 'vec3' }
  31341. ]
  31342. } );
  31343. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31344. const p = vec4( p_immutable ).toVar();
  31345. const ix = int( mx_floor( p.x ) ).toVar();
  31346. const iy = int( mx_floor( p.y ) ).toVar();
  31347. const iz = int( mx_floor( p.z ) ).toVar();
  31348. const iw = int( mx_floor( p.w ) ).toVar();
  31349. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  31350. } ).setLayout( {
  31351. name: 'mx_cell_noise_float_3',
  31352. type: 'float',
  31353. inputs: [
  31354. { name: 'p', type: 'vec4' }
  31355. ]
  31356. } );
  31357. 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 ] );
  31358. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31359. const p = float( p_immutable ).toVar();
  31360. const ix = int( mx_floor( p ) ).toVar();
  31361. 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 ) ) ) );
  31362. } ).setLayout( {
  31363. name: 'mx_cell_noise_vec3_0',
  31364. type: 'vec3',
  31365. inputs: [
  31366. { name: 'p', type: 'float' }
  31367. ]
  31368. } );
  31369. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31370. const p = vec2( p_immutable ).toVar();
  31371. const ix = int( mx_floor( p.x ) ).toVar();
  31372. const iy = int( mx_floor( p.y ) ).toVar();
  31373. 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 ) ) ) );
  31374. } ).setLayout( {
  31375. name: 'mx_cell_noise_vec3_1',
  31376. type: 'vec3',
  31377. inputs: [
  31378. { name: 'p', type: 'vec2' }
  31379. ]
  31380. } );
  31381. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31382. const p = vec3( p_immutable ).toVar();
  31383. const ix = int( mx_floor( p.x ) ).toVar();
  31384. const iy = int( mx_floor( p.y ) ).toVar();
  31385. const iz = int( mx_floor( p.z ) ).toVar();
  31386. 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 ) ) ) );
  31387. } ).setLayout( {
  31388. name: 'mx_cell_noise_vec3_2',
  31389. type: 'vec3',
  31390. inputs: [
  31391. { name: 'p', type: 'vec3' }
  31392. ]
  31393. } );
  31394. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31395. const p = vec4( p_immutable ).toVar();
  31396. const ix = int( mx_floor( p.x ) ).toVar();
  31397. const iy = int( mx_floor( p.y ) ).toVar();
  31398. const iz = int( mx_floor( p.z ) ).toVar();
  31399. const iw = int( mx_floor( p.w ) ).toVar();
  31400. 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 ) ) ) );
  31401. } ).setLayout( {
  31402. name: 'mx_cell_noise_vec3_3',
  31403. type: 'vec3',
  31404. inputs: [
  31405. { name: 'p', type: 'vec4' }
  31406. ]
  31407. } );
  31408. 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 ] );
  31409. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31410. const diminish = float( diminish_immutable ).toVar();
  31411. const lacunarity = float( lacunarity_immutable ).toVar();
  31412. const octaves = int( octaves_immutable ).toVar();
  31413. const p = vec3( p_immutable ).toVar();
  31414. const result = float( 0.0 ).toVar();
  31415. const amplitude = float( 1.0 ).toVar();
  31416. Loop( octaves, () => {
  31417. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  31418. amplitude.mulAssign( diminish );
  31419. p.mulAssign( lacunarity );
  31420. } );
  31421. return result;
  31422. } ).setLayout( {
  31423. name: 'mx_fractal_noise_float',
  31424. type: 'float',
  31425. inputs: [
  31426. { name: 'p', type: 'vec3' },
  31427. { name: 'octaves', type: 'int' },
  31428. { name: 'lacunarity', type: 'float' },
  31429. { name: 'diminish', type: 'float' }
  31430. ]
  31431. } );
  31432. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31433. const diminish = float( diminish_immutable ).toVar();
  31434. const lacunarity = float( lacunarity_immutable ).toVar();
  31435. const octaves = int( octaves_immutable ).toVar();
  31436. const p = vec3( p_immutable ).toVar();
  31437. const result = vec3( 0.0 ).toVar();
  31438. const amplitude = float( 1.0 ).toVar();
  31439. Loop( octaves, () => {
  31440. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  31441. amplitude.mulAssign( diminish );
  31442. p.mulAssign( lacunarity );
  31443. } );
  31444. return result;
  31445. } ).setLayout( {
  31446. name: 'mx_fractal_noise_vec3',
  31447. type: 'vec3',
  31448. inputs: [
  31449. { name: 'p', type: 'vec3' },
  31450. { name: 'octaves', type: 'int' },
  31451. { name: 'lacunarity', type: 'float' },
  31452. { name: 'diminish', type: 'float' }
  31453. ]
  31454. } );
  31455. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31456. const diminish = float( diminish_immutable ).toVar();
  31457. const lacunarity = float( lacunarity_immutable ).toVar();
  31458. const octaves = int( octaves_immutable ).toVar();
  31459. const p = vec3( p_immutable ).toVar();
  31460. 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 ) );
  31461. } ).setLayout( {
  31462. name: 'mx_fractal_noise_vec2',
  31463. type: 'vec2',
  31464. inputs: [
  31465. { name: 'p', type: 'vec3' },
  31466. { name: 'octaves', type: 'int' },
  31467. { name: 'lacunarity', type: 'float' },
  31468. { name: 'diminish', type: 'float' }
  31469. ]
  31470. } );
  31471. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31472. const diminish = float( diminish_immutable ).toVar();
  31473. const lacunarity = float( lacunarity_immutable ).toVar();
  31474. const octaves = int( octaves_immutable ).toVar();
  31475. const p = vec3( p_immutable ).toVar();
  31476. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  31477. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  31478. return vec4( c, f );
  31479. } ).setLayout( {
  31480. name: 'mx_fractal_noise_vec4',
  31481. type: 'vec4',
  31482. inputs: [
  31483. { name: 'p', type: 'vec3' },
  31484. { name: 'octaves', type: 'int' },
  31485. { name: 'lacunarity', type: 'float' },
  31486. { name: 'diminish', type: 'float' }
  31487. ]
  31488. } );
  31489. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  31490. const metric = int( metric_immutable ).toVar();
  31491. const jitter = float( jitter_immutable ).toVar();
  31492. const yoff = int( yoff_immutable ).toVar();
  31493. const xoff = int( xoff_immutable ).toVar();
  31494. const y = int( y_immutable ).toVar();
  31495. const x = int( x_immutable ).toVar();
  31496. const p = vec2( p_immutable ).toVar();
  31497. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  31498. const off = vec2( tmp.x, tmp.y ).toVar();
  31499. off.subAssign( 0.5 );
  31500. off.mulAssign( jitter );
  31501. off.addAssign( 0.5 );
  31502. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  31503. const diff = vec2( cellpos.sub( p ) ).toVar();
  31504. If( metric.equal( int( 2 ) ), () => {
  31505. return abs( diff.x ).add( abs( diff.y ) );
  31506. } );
  31507. If( metric.equal( int( 3 ) ), () => {
  31508. return max$1( abs( diff.x ), abs( diff.y ) );
  31509. } );
  31510. return dot( diff, diff );
  31511. } ).setLayout( {
  31512. name: 'mx_worley_distance_0',
  31513. type: 'float',
  31514. inputs: [
  31515. { name: 'p', type: 'vec2' },
  31516. { name: 'x', type: 'int' },
  31517. { name: 'y', type: 'int' },
  31518. { name: 'xoff', type: 'int' },
  31519. { name: 'yoff', type: 'int' },
  31520. { name: 'jitter', type: 'float' },
  31521. { name: 'metric', type: 'int' }
  31522. ]
  31523. } );
  31524. 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 ] ) => {
  31525. const metric = int( metric_immutable ).toVar();
  31526. const jitter = float( jitter_immutable ).toVar();
  31527. const zoff = int( zoff_immutable ).toVar();
  31528. const yoff = int( yoff_immutable ).toVar();
  31529. const xoff = int( xoff_immutable ).toVar();
  31530. const z = int( z_immutable ).toVar();
  31531. const y = int( y_immutable ).toVar();
  31532. const x = int( x_immutable ).toVar();
  31533. const p = vec3( p_immutable ).toVar();
  31534. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  31535. off.subAssign( 0.5 );
  31536. off.mulAssign( jitter );
  31537. off.addAssign( 0.5 );
  31538. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  31539. const diff = vec3( cellpos.sub( p ) ).toVar();
  31540. If( metric.equal( int( 2 ) ), () => {
  31541. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  31542. } );
  31543. If( metric.equal( int( 3 ) ), () => {
  31544. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  31545. } );
  31546. return dot( diff, diff );
  31547. } ).setLayout( {
  31548. name: 'mx_worley_distance_1',
  31549. type: 'float',
  31550. inputs: [
  31551. { name: 'p', type: 'vec3' },
  31552. { name: 'x', type: 'int' },
  31553. { name: 'y', type: 'int' },
  31554. { name: 'z', type: 'int' },
  31555. { name: 'xoff', type: 'int' },
  31556. { name: 'yoff', type: 'int' },
  31557. { name: 'zoff', type: 'int' },
  31558. { name: 'jitter', type: 'float' },
  31559. { name: 'metric', type: 'int' }
  31560. ]
  31561. } );
  31562. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31563. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31564. const metric = int( metric_immutable ).toVar();
  31565. const jitter = float( jitter_immutable ).toVar();
  31566. const p = vec2( p_immutable ).toVar();
  31567. const X = int().toVar(), Y = int().toVar();
  31568. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31569. const sqdist = float( 1e6 ).toVar();
  31570. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31571. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31572. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31573. sqdist.assign( min$1( sqdist, dist ) );
  31574. } );
  31575. } );
  31576. If( metric.equal( int( 0 ) ), () => {
  31577. sqdist.assign( sqrt( sqdist ) );
  31578. } );
  31579. return sqdist;
  31580. } ).setLayout( {
  31581. name: 'mx_worley_noise_float_0',
  31582. type: 'float',
  31583. inputs: [
  31584. { name: 'p', type: 'vec2' },
  31585. { name: 'jitter', type: 'float' },
  31586. { name: 'metric', type: 'int' }
  31587. ]
  31588. } );
  31589. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31590. const metric = int( metric_immutable ).toVar();
  31591. const jitter = float( jitter_immutable ).toVar();
  31592. const p = vec2( p_immutable ).toVar();
  31593. const X = int().toVar(), Y = int().toVar();
  31594. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31595. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31596. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31597. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31598. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31599. If( dist.lessThan( sqdist.x ), () => {
  31600. sqdist.y.assign( sqdist.x );
  31601. sqdist.x.assign( dist );
  31602. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31603. sqdist.y.assign( dist );
  31604. } );
  31605. } );
  31606. } );
  31607. If( metric.equal( int( 0 ) ), () => {
  31608. sqdist.assign( sqrt( sqdist ) );
  31609. } );
  31610. return sqdist;
  31611. } ).setLayout( {
  31612. name: 'mx_worley_noise_vec2_0',
  31613. type: 'vec2',
  31614. inputs: [
  31615. { name: 'p', type: 'vec2' },
  31616. { name: 'jitter', type: 'float' },
  31617. { name: 'metric', type: 'int' }
  31618. ]
  31619. } );
  31620. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31621. const metric = int( metric_immutable ).toVar();
  31622. const jitter = float( jitter_immutable ).toVar();
  31623. const p = vec2( p_immutable ).toVar();
  31624. const X = int().toVar(), Y = int().toVar();
  31625. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31626. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31627. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31628. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31629. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31630. If( dist.lessThan( sqdist.x ), () => {
  31631. sqdist.z.assign( sqdist.y );
  31632. sqdist.y.assign( sqdist.x );
  31633. sqdist.x.assign( dist );
  31634. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31635. sqdist.z.assign( sqdist.y );
  31636. sqdist.y.assign( dist );
  31637. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31638. sqdist.z.assign( dist );
  31639. } );
  31640. } );
  31641. } );
  31642. If( metric.equal( int( 0 ) ), () => {
  31643. sqdist.assign( sqrt( sqdist ) );
  31644. } );
  31645. return sqdist;
  31646. } ).setLayout( {
  31647. name: 'mx_worley_noise_vec3_0',
  31648. type: 'vec3',
  31649. inputs: [
  31650. { name: 'p', type: 'vec2' },
  31651. { name: 'jitter', type: 'float' },
  31652. { name: 'metric', type: 'int' }
  31653. ]
  31654. } );
  31655. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31656. const metric = int( metric_immutable ).toVar();
  31657. const jitter = float( jitter_immutable ).toVar();
  31658. const p = vec3( p_immutable ).toVar();
  31659. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31660. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31661. const sqdist = float( 1e6 ).toVar();
  31662. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31663. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31664. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31665. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31666. sqdist.assign( min$1( sqdist, dist ) );
  31667. } );
  31668. } );
  31669. } );
  31670. If( metric.equal( int( 0 ) ), () => {
  31671. sqdist.assign( sqrt( sqdist ) );
  31672. } );
  31673. return sqdist;
  31674. } ).setLayout( {
  31675. name: 'mx_worley_noise_float_1',
  31676. type: 'float',
  31677. inputs: [
  31678. { name: 'p', type: 'vec3' },
  31679. { name: 'jitter', type: 'float' },
  31680. { name: 'metric', type: 'int' }
  31681. ]
  31682. } );
  31683. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31684. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31685. const metric = int( metric_immutable ).toVar();
  31686. const jitter = float( jitter_immutable ).toVar();
  31687. const p = vec3( p_immutable ).toVar();
  31688. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31689. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31690. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31691. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31692. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31693. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31694. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31695. If( dist.lessThan( sqdist.x ), () => {
  31696. sqdist.y.assign( sqdist.x );
  31697. sqdist.x.assign( dist );
  31698. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31699. sqdist.y.assign( dist );
  31700. } );
  31701. } );
  31702. } );
  31703. } );
  31704. If( metric.equal( int( 0 ) ), () => {
  31705. sqdist.assign( sqrt( sqdist ) );
  31706. } );
  31707. return sqdist;
  31708. } ).setLayout( {
  31709. name: 'mx_worley_noise_vec2_1',
  31710. type: 'vec2',
  31711. inputs: [
  31712. { name: 'p', type: 'vec3' },
  31713. { name: 'jitter', type: 'float' },
  31714. { name: 'metric', type: 'int' }
  31715. ]
  31716. } );
  31717. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31718. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31719. const metric = int( metric_immutable ).toVar();
  31720. const jitter = float( jitter_immutable ).toVar();
  31721. const p = vec3( p_immutable ).toVar();
  31722. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31723. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31724. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31725. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31726. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31727. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31728. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31729. If( dist.lessThan( sqdist.x ), () => {
  31730. sqdist.z.assign( sqdist.y );
  31731. sqdist.y.assign( sqdist.x );
  31732. sqdist.x.assign( dist );
  31733. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31734. sqdist.z.assign( sqdist.y );
  31735. sqdist.y.assign( dist );
  31736. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31737. sqdist.z.assign( dist );
  31738. } );
  31739. } );
  31740. } );
  31741. } );
  31742. If( metric.equal( int( 0 ) ), () => {
  31743. sqdist.assign( sqrt( sqdist ) );
  31744. } );
  31745. return sqdist;
  31746. } ).setLayout( {
  31747. name: 'mx_worley_noise_vec3_1',
  31748. type: 'vec3',
  31749. inputs: [
  31750. { name: 'p', type: 'vec3' },
  31751. { name: 'jitter', type: 'float' },
  31752. { name: 'metric', type: 'int' }
  31753. ]
  31754. } );
  31755. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  31756. // Unified Noise 2D
  31757. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  31758. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  31759. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31760. octaves_immutable, lacunarity_immutable, diminish_immutable
  31761. ] ) => {
  31762. const noiseType = int( noiseType_immutable ).toVar();
  31763. const texcoord = vec2( texcoord_immutable ).toVar();
  31764. const freq = vec2( freq_immutable ).toVar();
  31765. const offset = vec2( offset_immutable ).toVar();
  31766. const jitter = float( jitter_immutable ).toVar();
  31767. const outmin = float( outmin_immutable ).toVar();
  31768. const outmax = float( outmax_immutable ).toVar();
  31769. const clampoutput = bool( clampoutput_immutable ).toVar();
  31770. const octaves = int( octaves_immutable ).toVar();
  31771. const lacunarity = float( lacunarity_immutable ).toVar();
  31772. const diminish = float( diminish_immutable ).toVar();
  31773. // Compute input position
  31774. const p = texcoord.mul( freq ).add( offset );
  31775. const result = float( 0.0 ).toVar();
  31776. // Perlin
  31777. If( noiseType.equal( int( 0 ) ), () => {
  31778. result.assign( mx_perlin_noise_vec3( p ) );
  31779. } );
  31780. // Cell
  31781. If( noiseType.equal( int( 1 ) ), () => {
  31782. result.assign( mx_cell_noise_vec3( p ) );
  31783. } );
  31784. // Worley (metric=0 = euclidean)
  31785. If( noiseType.equal( int( 2 ) ), () => {
  31786. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31787. } );
  31788. // Fractal (use vec3(p, 0.0) for 2D input)
  31789. If( noiseType.equal( int( 3 ) ), () => {
  31790. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  31791. } );
  31792. // Remap output to [outmin, outmax]
  31793. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31794. // Clamp if requested
  31795. If( clampoutput, () => {
  31796. result.assign( clamp( result, outmin, outmax ) );
  31797. } );
  31798. return result;
  31799. } ).setLayout( {
  31800. name: 'mx_unifiednoise2d',
  31801. type: 'float',
  31802. inputs: [
  31803. { name: 'noiseType', type: 'int' },
  31804. { name: 'texcoord', type: 'vec2' },
  31805. { name: 'freq', type: 'vec2' },
  31806. { name: 'offset', type: 'vec2' },
  31807. { name: 'jitter', type: 'float' },
  31808. { name: 'outmin', type: 'float' },
  31809. { name: 'outmax', type: 'float' },
  31810. { name: 'clampoutput', type: 'bool' },
  31811. { name: 'octaves', type: 'int' },
  31812. { name: 'lacunarity', type: 'float' },
  31813. { name: 'diminish', type: 'float' }
  31814. ]
  31815. } );
  31816. // Unified Noise 3D
  31817. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  31818. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  31819. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31820. octaves_immutable, lacunarity_immutable, diminish_immutable
  31821. ] ) => {
  31822. const noiseType = int( noiseType_immutable ).toVar();
  31823. const position = vec3( position_immutable ).toVar();
  31824. const freq = vec3( freq_immutable ).toVar();
  31825. const offset = vec3( offset_immutable ).toVar();
  31826. const jitter = float( jitter_immutable ).toVar();
  31827. const outmin = float( outmin_immutable ).toVar();
  31828. const outmax = float( outmax_immutable ).toVar();
  31829. const clampoutput = bool( clampoutput_immutable ).toVar();
  31830. const octaves = int( octaves_immutable ).toVar();
  31831. const lacunarity = float( lacunarity_immutable ).toVar();
  31832. const diminish = float( diminish_immutable ).toVar();
  31833. // Compute input position
  31834. const p = position.mul( freq ).add( offset );
  31835. const result = float( 0.0 ).toVar();
  31836. // Perlin
  31837. If( noiseType.equal( int( 0 ) ), () => {
  31838. result.assign( mx_perlin_noise_vec3( p ) );
  31839. } );
  31840. // Cell
  31841. If( noiseType.equal( int( 1 ) ), () => {
  31842. result.assign( mx_cell_noise_vec3( p ) );
  31843. } );
  31844. // Worley (metric=0 = euclidean)
  31845. If( noiseType.equal( int( 2 ) ), () => {
  31846. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31847. } );
  31848. // Fractal
  31849. If( noiseType.equal( int( 3 ) ), () => {
  31850. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  31851. } );
  31852. // Remap output to [outmin, outmax]
  31853. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31854. // Clamp if requested
  31855. If( clampoutput, () => {
  31856. result.assign( clamp( result, outmin, outmax ) );
  31857. } );
  31858. return result;
  31859. } ).setLayout( {
  31860. name: 'mx_unifiednoise3d',
  31861. type: 'float',
  31862. inputs: [
  31863. { name: 'noiseType', type: 'int' },
  31864. { name: 'position', type: 'vec3' },
  31865. { name: 'freq', type: 'vec3' },
  31866. { name: 'offset', type: 'vec3' },
  31867. { name: 'jitter', type: 'float' },
  31868. { name: 'outmin', type: 'float' },
  31869. { name: 'outmax', type: 'float' },
  31870. { name: 'clampoutput', type: 'bool' },
  31871. { name: 'octaves', type: 'int' },
  31872. { name: 'lacunarity', type: 'float' },
  31873. { name: 'diminish', type: 'float' }
  31874. ]
  31875. } );
  31876. // Three.js Transpiler
  31877. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31878. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31879. const s = hsv.y;
  31880. const v = hsv.z;
  31881. const result = vec3().toVar();
  31882. If( s.lessThan( 0.0001 ), () => {
  31883. result.assign( vec3( v, v, v ) );
  31884. } ).Else( () => {
  31885. let h = hsv.x;
  31886. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31887. const hi = int( trunc( h ) );
  31888. const f = h.sub( float( hi ) );
  31889. const p = v.mul( s.oneMinus() );
  31890. const q = v.mul( s.mul( f ).oneMinus() );
  31891. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31892. If( hi.equal( int( 0 ) ), () => {
  31893. result.assign( vec3( v, t, p ) );
  31894. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31895. result.assign( vec3( q, v, p ) );
  31896. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31897. result.assign( vec3( p, v, t ) );
  31898. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31899. result.assign( vec3( p, q, v ) );
  31900. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31901. result.assign( vec3( t, p, v ) );
  31902. } ).Else( () => {
  31903. result.assign( vec3( v, p, q ) );
  31904. } );
  31905. } );
  31906. return result;
  31907. } ).setLayout( {
  31908. name: 'mx_hsvtorgb',
  31909. type: 'vec3',
  31910. inputs: [
  31911. { name: 'hsv', type: 'vec3' }
  31912. ]
  31913. } );
  31914. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31915. const c = vec3( c_immutable ).toVar();
  31916. const r = float( c.x ).toVar();
  31917. const g = float( c.y ).toVar();
  31918. const b = float( c.z ).toVar();
  31919. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31920. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31921. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31922. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31923. v.assign( maxcomp );
  31924. If( maxcomp.greaterThan( 0.0 ), () => {
  31925. s.assign( delta.div( maxcomp ) );
  31926. } ).Else( () => {
  31927. s.assign( 0.0 );
  31928. } );
  31929. If( s.lessThanEqual( 0.0 ), () => {
  31930. h.assign( 0.0 );
  31931. } ).Else( () => {
  31932. If( r.greaterThanEqual( maxcomp ), () => {
  31933. h.assign( g.sub( b ).div( delta ) );
  31934. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31935. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31936. } ).Else( () => {
  31937. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31938. } );
  31939. h.mulAssign( 1.0 / 6.0 );
  31940. If( h.lessThan( 0.0 ), () => {
  31941. h.addAssign( 1.0 );
  31942. } );
  31943. } );
  31944. return vec3( h, s, v );
  31945. } ).setLayout( {
  31946. name: 'mx_rgbtohsv',
  31947. type: 'vec3',
  31948. inputs: [
  31949. { name: 'c', type: 'vec3' }
  31950. ]
  31951. } );
  31952. // Three.js Transpiler
  31953. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31954. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31955. const color = vec3( color_immutable ).toVar();
  31956. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31957. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31958. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31959. return mix( linSeg, powSeg, isAbove );
  31960. } ).setLayout( {
  31961. name: 'mx_srgb_texture_to_lin_rec709',
  31962. type: 'vec3',
  31963. inputs: [
  31964. { name: 'color', type: 'vec3' }
  31965. ]
  31966. } );
  31967. const mx_aastep = ( threshold, value ) => {
  31968. threshold = float( threshold );
  31969. value = float( value );
  31970. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31971. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31972. };
  31973. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31974. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31975. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31976. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31977. const mx_ramp4 = (
  31978. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31979. ) => {
  31980. const u = texcoord.x.clamp();
  31981. const v = texcoord.y.clamp();
  31982. const top = mix( valuetl, valuetr, u );
  31983. const bottom = mix( valuebl, valuebr, u );
  31984. return mix( top, bottom, v );
  31985. };
  31986. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31987. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31988. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31989. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31990. const mx_safepower = ( in1, in2 = 1 ) => {
  31991. in1 = float( in1 );
  31992. return in1.abs().pow( in2 ).mul( in1.sign() );
  31993. };
  31994. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31995. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31996. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31997. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31998. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  31999. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  32000. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  32001. return noise_vec4.mul( amplitude ).add( pivot );
  32002. };
  32003. 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 );
  32004. 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 );
  32005. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32006. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32007. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32008. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  32009. 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 );
  32010. 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 );
  32011. 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 );
  32012. 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 );
  32013. // === Moved from MaterialXLoader.js ===
  32014. // Math ops
  32015. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  32016. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  32017. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  32018. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  32019. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  32020. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  32021. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  32022. const mx_timer = () => time;
  32023. const mx_frame = () => frameId;
  32024. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  32025. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  32026. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  32027. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  32028. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  32029. const mx_separate = ( in1, channelOrOut = null ) => {
  32030. if ( typeof channelOrOut === 'string' ) {
  32031. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32032. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  32033. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  32034. }
  32035. if ( typeof channelOrOut === 'number' ) {
  32036. return in1.element( channelOrOut );
  32037. }
  32038. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  32039. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32040. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  32041. }
  32042. return in1;
  32043. };
  32044. const mx_place2d = (
  32045. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  32046. ) => {
  32047. let uv = texcoord;
  32048. if ( pivot ) uv = uv.sub( pivot );
  32049. if ( scale ) uv = uv.mul( scale );
  32050. if ( rotate ) {
  32051. const rad = rotate.mul( Math.PI / 180.0 );
  32052. const cosR = rad.cos();
  32053. const sinR = rad.sin();
  32054. uv = vec2(
  32055. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  32056. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  32057. );
  32058. }
  32059. if ( pivot ) uv = uv.add( pivot );
  32060. if ( offset ) uv = uv.add( offset );
  32061. return uv;
  32062. };
  32063. const mx_rotate2d = ( input, amount ) => {
  32064. input = vec2( input );
  32065. amount = float( amount );
  32066. const radians = amount.mul( Math.PI / 180.0 );
  32067. return rotate( input, radians );
  32068. };
  32069. const mx_rotate3d = ( input, amount, axis ) => {
  32070. input = vec3( input );
  32071. amount = float( amount );
  32072. axis = vec3( axis );
  32073. const radians = amount.mul( Math.PI / 180.0 );
  32074. const nAxis = axis.normalize();
  32075. const cosA = radians.cos();
  32076. const sinA = radians.sin();
  32077. const oneMinusCosA = float( 1 ).sub( cosA );
  32078. const rot =
  32079. input.mul( cosA )
  32080. .add( nAxis.cross( input ).mul( sinA ) )
  32081. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  32082. return rot;
  32083. };
  32084. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  32085. input = vec3( input );
  32086. scale = float( scale );
  32087. return bumpMap( input, scale );
  32088. };
  32089. /**
  32090. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  32091. *
  32092. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  32093. *
  32094. * ```js
  32095. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  32096. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  32097. * ```
  32098. *
  32099. * @tsl
  32100. * @function
  32101. * @param {Node<vec3>} normal - The normal to correct.
  32102. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  32103. * @param {Node<vec3>} cubePos - The cube position.
  32104. * @return {Node<vec3>} The parallax corrected normal.
  32105. */
  32106. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  32107. const nDir = normalize( normal ).toVar();
  32108. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32109. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32110. const rbminmax = vec3().toVar();
  32111. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  32112. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  32113. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  32114. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  32115. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  32116. return boxIntersection.sub( cubePos );
  32117. } );
  32118. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  32119. // normal is assumed to have unit length
  32120. const x = normal.x, y = normal.y, z = normal.z;
  32121. // band 0
  32122. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  32123. // band 1
  32124. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  32125. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  32126. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  32127. // band 2
  32128. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  32129. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  32130. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  32131. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  32132. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  32133. return result;
  32134. } );
  32135. // constants
  32136. var TSL = /*#__PURE__*/Object.freeze({
  32137. __proto__: null,
  32138. BRDF_GGX: BRDF_GGX,
  32139. BRDF_Lambert: BRDF_Lambert,
  32140. BasicPointShadowFilter: BasicPointShadowFilter,
  32141. BasicShadowFilter: BasicShadowFilter,
  32142. Break: Break,
  32143. Const: Const,
  32144. Continue: Continue,
  32145. DFGApprox: DFGApprox,
  32146. D_GGX: D_GGX,
  32147. Discard: Discard,
  32148. EPSILON: EPSILON,
  32149. F_Schlick: F_Schlick,
  32150. Fn: Fn,
  32151. HALF_PI: HALF_PI,
  32152. INFINITY: INFINITY,
  32153. If: If,
  32154. Loop: Loop,
  32155. NodeAccess: NodeAccess,
  32156. NodeShaderStage: NodeShaderStage,
  32157. NodeType: NodeType,
  32158. NodeUpdateType: NodeUpdateType,
  32159. OnMaterialUpdate: OnMaterialUpdate,
  32160. OnObjectUpdate: OnObjectUpdate,
  32161. PCFShadowFilter: PCFShadowFilter,
  32162. PCFSoftShadowFilter: PCFSoftShadowFilter,
  32163. PI: PI,
  32164. PI2: PI2,
  32165. PointShadowFilter: PointShadowFilter,
  32166. Return: Return,
  32167. Schlick_to_F0: Schlick_to_F0,
  32168. ScriptableNodeResources: ScriptableNodeResources,
  32169. ShaderNode: ShaderNode,
  32170. Stack: Stack,
  32171. Switch: Switch,
  32172. TBNViewMatrix: TBNViewMatrix,
  32173. TWO_PI: TWO_PI,
  32174. VSMShadowFilter: VSMShadowFilter,
  32175. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  32176. Var: Var,
  32177. VarIntent: VarIntent,
  32178. abs: abs,
  32179. acesFilmicToneMapping: acesFilmicToneMapping,
  32180. acos: acos,
  32181. add: add,
  32182. addMethodChaining: addMethodChaining,
  32183. addNodeElement: addNodeElement,
  32184. agxToneMapping: agxToneMapping,
  32185. all: all,
  32186. alphaT: alphaT,
  32187. and: and,
  32188. anisotropy: anisotropy,
  32189. anisotropyB: anisotropyB,
  32190. anisotropyT: anisotropyT,
  32191. any: any,
  32192. append: append,
  32193. array: array,
  32194. arrayBuffer: arrayBuffer,
  32195. asin: asin,
  32196. assign: assign,
  32197. atan: atan,
  32198. atan2: atan2,
  32199. atomicAdd: atomicAdd,
  32200. atomicAnd: atomicAnd,
  32201. atomicFunc: atomicFunc,
  32202. atomicLoad: atomicLoad,
  32203. atomicMax: atomicMax,
  32204. atomicMin: atomicMin,
  32205. atomicOr: atomicOr,
  32206. atomicStore: atomicStore,
  32207. atomicSub: atomicSub,
  32208. atomicXor: atomicXor,
  32209. attenuationColor: attenuationColor,
  32210. attenuationDistance: attenuationDistance,
  32211. attribute: attribute,
  32212. attributeArray: attributeArray,
  32213. backgroundBlurriness: backgroundBlurriness,
  32214. backgroundIntensity: backgroundIntensity,
  32215. backgroundRotation: backgroundRotation,
  32216. batch: batch,
  32217. bentNormalView: bentNormalView,
  32218. billboarding: billboarding,
  32219. bitAnd: bitAnd,
  32220. bitNot: bitNot,
  32221. bitOr: bitOr,
  32222. bitXor: bitXor,
  32223. bitangentGeometry: bitangentGeometry,
  32224. bitangentLocal: bitangentLocal,
  32225. bitangentView: bitangentView,
  32226. bitangentWorld: bitangentWorld,
  32227. bitcast: bitcast,
  32228. blendBurn: blendBurn,
  32229. blendColor: blendColor,
  32230. blendDodge: blendDodge,
  32231. blendOverlay: blendOverlay,
  32232. blendScreen: blendScreen,
  32233. blur: blur,
  32234. bool: bool,
  32235. buffer: buffer,
  32236. bufferAttribute: bufferAttribute,
  32237. builtin: builtin,
  32238. bumpMap: bumpMap,
  32239. burn: burn,
  32240. bvec2: bvec2,
  32241. bvec3: bvec3,
  32242. bvec4: bvec4,
  32243. bypass: bypass,
  32244. cache: cache,
  32245. call: call,
  32246. cameraFar: cameraFar,
  32247. cameraIndex: cameraIndex,
  32248. cameraNear: cameraNear,
  32249. cameraNormalMatrix: cameraNormalMatrix,
  32250. cameraPosition: cameraPosition,
  32251. cameraProjectionMatrix: cameraProjectionMatrix,
  32252. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  32253. cameraViewMatrix: cameraViewMatrix,
  32254. cameraViewport: cameraViewport,
  32255. cameraWorldMatrix: cameraWorldMatrix,
  32256. cbrt: cbrt,
  32257. cdl: cdl,
  32258. ceil: ceil,
  32259. checker: checker,
  32260. cineonToneMapping: cineonToneMapping,
  32261. clamp: clamp,
  32262. clearcoat: clearcoat,
  32263. clearcoatNormalView: clearcoatNormalView,
  32264. clearcoatRoughness: clearcoatRoughness,
  32265. code: code,
  32266. color: color,
  32267. colorSpaceToWorking: colorSpaceToWorking,
  32268. colorToDirection: colorToDirection,
  32269. compute: compute,
  32270. computeKernel: computeKernel,
  32271. computeSkinning: computeSkinning,
  32272. context: context,
  32273. convert: convert,
  32274. convertColorSpace: convertColorSpace,
  32275. convertToTexture: convertToTexture,
  32276. cos: cos,
  32277. cross: cross,
  32278. cubeTexture: cubeTexture,
  32279. cubeTextureBase: cubeTextureBase,
  32280. cubeToUV: cubeToUV,
  32281. dFdx: dFdx,
  32282. dFdy: dFdy,
  32283. dashSize: dashSize,
  32284. debug: debug,
  32285. decrement: decrement,
  32286. decrementBefore: decrementBefore,
  32287. defaultBuildStages: defaultBuildStages,
  32288. defaultShaderStages: defaultShaderStages,
  32289. defined: defined,
  32290. degrees: degrees,
  32291. deltaTime: deltaTime,
  32292. densityFog: densityFog,
  32293. densityFogFactor: densityFogFactor,
  32294. depth: depth,
  32295. depthPass: depthPass,
  32296. determinant: determinant,
  32297. difference: difference,
  32298. diffuseColor: diffuseColor,
  32299. directPointLight: directPointLight,
  32300. directionToColor: directionToColor,
  32301. directionToFaceDirection: directionToFaceDirection,
  32302. dispersion: dispersion,
  32303. distance: distance,
  32304. div: div,
  32305. dodge: dodge,
  32306. dot: dot,
  32307. drawIndex: drawIndex,
  32308. dynamicBufferAttribute: dynamicBufferAttribute,
  32309. element: element,
  32310. emissive: emissive,
  32311. equal: equal,
  32312. equals: equals,
  32313. equirectUV: equirectUV,
  32314. exp: exp,
  32315. exp2: exp2,
  32316. expression: expression,
  32317. faceDirection: faceDirection,
  32318. faceForward: faceForward,
  32319. faceforward: faceforward,
  32320. float: float,
  32321. floatBitsToInt: floatBitsToInt,
  32322. floatBitsToUint: floatBitsToUint,
  32323. floor: floor,
  32324. fog: fog,
  32325. fract: fract,
  32326. frameGroup: frameGroup,
  32327. frameId: frameId,
  32328. frontFacing: frontFacing,
  32329. fwidth: fwidth,
  32330. gain: gain,
  32331. gapSize: gapSize,
  32332. getConstNodeType: getConstNodeType,
  32333. getCurrentStack: getCurrentStack,
  32334. getDirection: getDirection,
  32335. getDistanceAttenuation: getDistanceAttenuation,
  32336. getGeometryRoughness: getGeometryRoughness,
  32337. getNormalFromDepth: getNormalFromDepth,
  32338. getParallaxCorrectNormal: getParallaxCorrectNormal,
  32339. getRoughness: getRoughness,
  32340. getScreenPosition: getScreenPosition,
  32341. getShIrradianceAt: getShIrradianceAt,
  32342. getShadowMaterial: getShadowMaterial,
  32343. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  32344. getTextureIndex: getTextureIndex,
  32345. getViewPosition: getViewPosition,
  32346. globalId: globalId,
  32347. glsl: glsl,
  32348. glslFn: glslFn,
  32349. grayscale: grayscale,
  32350. greaterThan: greaterThan,
  32351. greaterThanEqual: greaterThanEqual,
  32352. hash: hash,
  32353. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  32354. highpModelViewMatrix: highpModelViewMatrix,
  32355. hue: hue,
  32356. increment: increment,
  32357. incrementBefore: incrementBefore,
  32358. inspector: inspector,
  32359. instance: instance,
  32360. instanceIndex: instanceIndex,
  32361. instancedArray: instancedArray,
  32362. instancedBufferAttribute: instancedBufferAttribute,
  32363. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  32364. instancedMesh: instancedMesh,
  32365. int: int,
  32366. intBitsToFloat: intBitsToFloat,
  32367. inverse: inverse,
  32368. inverseSqrt: inverseSqrt,
  32369. inversesqrt: inversesqrt,
  32370. invocationLocalIndex: invocationLocalIndex,
  32371. invocationSubgroupIndex: invocationSubgroupIndex,
  32372. ior: ior,
  32373. iridescence: iridescence,
  32374. iridescenceIOR: iridescenceIOR,
  32375. iridescenceThickness: iridescenceThickness,
  32376. isolate: isolate,
  32377. ivec2: ivec2,
  32378. ivec3: ivec3,
  32379. ivec4: ivec4,
  32380. js: js,
  32381. label: label,
  32382. length: length,
  32383. lengthSq: lengthSq,
  32384. lessThan: lessThan,
  32385. lessThanEqual: lessThanEqual,
  32386. lightPosition: lightPosition,
  32387. lightProjectionUV: lightProjectionUV,
  32388. lightShadowMatrix: lightShadowMatrix,
  32389. lightTargetDirection: lightTargetDirection,
  32390. lightTargetPosition: lightTargetPosition,
  32391. lightViewPosition: lightViewPosition,
  32392. lightingContext: lightingContext,
  32393. lights: lights,
  32394. linearDepth: linearDepth,
  32395. linearToneMapping: linearToneMapping,
  32396. localId: localId,
  32397. log: log,
  32398. log2: log2,
  32399. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  32400. luminance: luminance,
  32401. mat2: mat2,
  32402. mat3: mat3,
  32403. mat4: mat4,
  32404. matcapUV: matcapUV,
  32405. materialAO: materialAO,
  32406. materialAlphaTest: materialAlphaTest,
  32407. materialAnisotropy: materialAnisotropy,
  32408. materialAnisotropyVector: materialAnisotropyVector,
  32409. materialAttenuationColor: materialAttenuationColor,
  32410. materialAttenuationDistance: materialAttenuationDistance,
  32411. materialClearcoat: materialClearcoat,
  32412. materialClearcoatNormal: materialClearcoatNormal,
  32413. materialClearcoatRoughness: materialClearcoatRoughness,
  32414. materialColor: materialColor,
  32415. materialDispersion: materialDispersion,
  32416. materialEmissive: materialEmissive,
  32417. materialEnvIntensity: materialEnvIntensity,
  32418. materialEnvRotation: materialEnvRotation,
  32419. materialIOR: materialIOR,
  32420. materialIridescence: materialIridescence,
  32421. materialIridescenceIOR: materialIridescenceIOR,
  32422. materialIridescenceThickness: materialIridescenceThickness,
  32423. materialLightMap: materialLightMap,
  32424. materialLineDashOffset: materialLineDashOffset,
  32425. materialLineDashSize: materialLineDashSize,
  32426. materialLineGapSize: materialLineGapSize,
  32427. materialLineScale: materialLineScale,
  32428. materialLineWidth: materialLineWidth,
  32429. materialMetalness: materialMetalness,
  32430. materialNormal: materialNormal,
  32431. materialOpacity: materialOpacity,
  32432. materialPointSize: materialPointSize,
  32433. materialReference: materialReference,
  32434. materialReflectivity: materialReflectivity,
  32435. materialRefractionRatio: materialRefractionRatio,
  32436. materialRotation: materialRotation,
  32437. materialRoughness: materialRoughness,
  32438. materialSheen: materialSheen,
  32439. materialSheenRoughness: materialSheenRoughness,
  32440. materialShininess: materialShininess,
  32441. materialSpecular: materialSpecular,
  32442. materialSpecularColor: materialSpecularColor,
  32443. materialSpecularIntensity: materialSpecularIntensity,
  32444. materialSpecularStrength: materialSpecularStrength,
  32445. materialThickness: materialThickness,
  32446. materialTransmission: materialTransmission,
  32447. max: max$1,
  32448. maxMipLevel: maxMipLevel,
  32449. mediumpModelViewMatrix: mediumpModelViewMatrix,
  32450. metalness: metalness,
  32451. min: min$1,
  32452. mix: mix,
  32453. mixElement: mixElement,
  32454. mod: mod,
  32455. modInt: modInt,
  32456. modelDirection: modelDirection,
  32457. modelNormalMatrix: modelNormalMatrix,
  32458. modelPosition: modelPosition,
  32459. modelRadius: modelRadius,
  32460. modelScale: modelScale,
  32461. modelViewMatrix: modelViewMatrix,
  32462. modelViewPosition: modelViewPosition,
  32463. modelViewProjection: modelViewProjection,
  32464. modelWorldMatrix: modelWorldMatrix,
  32465. modelWorldMatrixInverse: modelWorldMatrixInverse,
  32466. morphReference: morphReference,
  32467. mrt: mrt,
  32468. mul: mul,
  32469. mx_aastep: mx_aastep,
  32470. mx_add: mx_add,
  32471. mx_atan2: mx_atan2,
  32472. mx_cell_noise_float: mx_cell_noise_float,
  32473. mx_contrast: mx_contrast,
  32474. mx_divide: mx_divide,
  32475. mx_fractal_noise_float: mx_fractal_noise_float,
  32476. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  32477. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  32478. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  32479. mx_frame: mx_frame,
  32480. mx_heighttonormal: mx_heighttonormal,
  32481. mx_hsvtorgb: mx_hsvtorgb,
  32482. mx_ifequal: mx_ifequal,
  32483. mx_ifgreater: mx_ifgreater,
  32484. mx_ifgreatereq: mx_ifgreatereq,
  32485. mx_invert: mx_invert,
  32486. mx_modulo: mx_modulo,
  32487. mx_multiply: mx_multiply,
  32488. mx_noise_float: mx_noise_float,
  32489. mx_noise_vec3: mx_noise_vec3,
  32490. mx_noise_vec4: mx_noise_vec4,
  32491. mx_place2d: mx_place2d,
  32492. mx_power: mx_power,
  32493. mx_ramp4: mx_ramp4,
  32494. mx_ramplr: mx_ramplr,
  32495. mx_ramptb: mx_ramptb,
  32496. mx_rgbtohsv: mx_rgbtohsv,
  32497. mx_rotate2d: mx_rotate2d,
  32498. mx_rotate3d: mx_rotate3d,
  32499. mx_safepower: mx_safepower,
  32500. mx_separate: mx_separate,
  32501. mx_splitlr: mx_splitlr,
  32502. mx_splittb: mx_splittb,
  32503. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  32504. mx_subtract: mx_subtract,
  32505. mx_timer: mx_timer,
  32506. mx_transform_uv: mx_transform_uv,
  32507. mx_unifiednoise2d: mx_unifiednoise2d,
  32508. mx_unifiednoise3d: mx_unifiednoise3d,
  32509. mx_worley_noise_float: mx_worley_noise_float,
  32510. mx_worley_noise_vec2: mx_worley_noise_vec2,
  32511. mx_worley_noise_vec3: mx_worley_noise_vec3,
  32512. negate: negate,
  32513. neutralToneMapping: neutralToneMapping,
  32514. nodeArray: nodeArray,
  32515. nodeImmutable: nodeImmutable,
  32516. nodeObject: nodeObject,
  32517. nodeObjectIntent: nodeObjectIntent,
  32518. nodeObjects: nodeObjects,
  32519. nodeProxy: nodeProxy,
  32520. nodeProxyIntent: nodeProxyIntent,
  32521. normalFlat: normalFlat,
  32522. normalGeometry: normalGeometry,
  32523. normalLocal: normalLocal,
  32524. normalMap: normalMap,
  32525. normalView: normalView,
  32526. normalViewGeometry: normalViewGeometry,
  32527. normalWorld: normalWorld,
  32528. normalWorldGeometry: normalWorldGeometry,
  32529. normalize: normalize,
  32530. not: not,
  32531. notEqual: notEqual,
  32532. numWorkgroups: numWorkgroups,
  32533. objectDirection: objectDirection,
  32534. objectGroup: objectGroup,
  32535. objectPosition: objectPosition,
  32536. objectRadius: objectRadius,
  32537. objectScale: objectScale,
  32538. objectViewPosition: objectViewPosition,
  32539. objectWorldMatrix: objectWorldMatrix,
  32540. oneMinus: oneMinus,
  32541. or: or,
  32542. orthographicDepthToViewZ: orthographicDepthToViewZ,
  32543. oscSawtooth: oscSawtooth,
  32544. oscSine: oscSine,
  32545. oscSquare: oscSquare,
  32546. oscTriangle: oscTriangle,
  32547. output: output,
  32548. outputStruct: outputStruct,
  32549. overlay: overlay,
  32550. overloadingFn: overloadingFn,
  32551. parabola: parabola,
  32552. parallaxDirection: parallaxDirection,
  32553. parallaxUV: parallaxUV,
  32554. parameter: parameter,
  32555. pass: pass,
  32556. passTexture: passTexture,
  32557. pcurve: pcurve,
  32558. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  32559. pmremTexture: pmremTexture,
  32560. pointShadow: pointShadow,
  32561. pointUV: pointUV,
  32562. pointWidth: pointWidth,
  32563. positionGeometry: positionGeometry,
  32564. positionLocal: positionLocal,
  32565. positionPrevious: positionPrevious,
  32566. positionView: positionView,
  32567. positionViewDirection: positionViewDirection,
  32568. positionWorld: positionWorld,
  32569. positionWorldDirection: positionWorldDirection,
  32570. posterize: posterize,
  32571. pow: pow,
  32572. pow2: pow2,
  32573. pow3: pow3,
  32574. pow4: pow4,
  32575. premultiplyAlpha: premultiplyAlpha,
  32576. property: property,
  32577. quadBroadcast: quadBroadcast,
  32578. quadSwapDiagonal: quadSwapDiagonal,
  32579. quadSwapX: quadSwapX,
  32580. quadSwapY: quadSwapY,
  32581. radians: radians,
  32582. rand: rand,
  32583. range: range,
  32584. rangeFog: rangeFog,
  32585. rangeFogFactor: rangeFogFactor,
  32586. reciprocal: reciprocal,
  32587. reference: reference,
  32588. referenceBuffer: referenceBuffer,
  32589. reflect: reflect,
  32590. reflectVector: reflectVector,
  32591. reflectView: reflectView,
  32592. reflector: reflector,
  32593. refract: refract,
  32594. refractVector: refractVector,
  32595. refractView: refractView,
  32596. reinhardToneMapping: reinhardToneMapping,
  32597. remap: remap,
  32598. remapClamp: remapClamp,
  32599. renderGroup: renderGroup,
  32600. renderOutput: renderOutput,
  32601. rendererReference: rendererReference,
  32602. rotate: rotate,
  32603. rotateUV: rotateUV,
  32604. roughness: roughness,
  32605. round: round,
  32606. rtt: rtt,
  32607. sRGBTransferEOTF: sRGBTransferEOTF,
  32608. sRGBTransferOETF: sRGBTransferOETF,
  32609. sample: sample,
  32610. sampler: sampler,
  32611. samplerComparison: samplerComparison,
  32612. saturate: saturate,
  32613. saturation: saturation,
  32614. screen: screen,
  32615. screenCoordinate: screenCoordinate,
  32616. screenDPR: screenDPR,
  32617. screenSize: screenSize,
  32618. screenUV: screenUV,
  32619. scriptable: scriptable,
  32620. scriptableValue: scriptableValue,
  32621. select: select,
  32622. setCurrentStack: setCurrentStack,
  32623. setName: setName,
  32624. shaderStages: shaderStages,
  32625. shadow: shadow,
  32626. shadowPositionWorld: shadowPositionWorld,
  32627. shapeCircle: shapeCircle,
  32628. sharedUniformGroup: sharedUniformGroup,
  32629. sheen: sheen,
  32630. sheenRoughness: sheenRoughness,
  32631. shiftLeft: shiftLeft,
  32632. shiftRight: shiftRight,
  32633. shininess: shininess,
  32634. sign: sign,
  32635. sin: sin,
  32636. sinc: sinc,
  32637. skinning: skinning,
  32638. smoothstep: smoothstep,
  32639. smoothstepElement: smoothstepElement,
  32640. specularColor: specularColor,
  32641. specularF90: specularF90,
  32642. spherizeUV: spherizeUV,
  32643. split: split,
  32644. spritesheetUV: spritesheetUV,
  32645. sqrt: sqrt,
  32646. stack: stack,
  32647. step: step,
  32648. stepElement: stepElement,
  32649. storage: storage,
  32650. storageBarrier: storageBarrier,
  32651. storageObject: storageObject,
  32652. storageTexture: storageTexture,
  32653. string: string,
  32654. struct: struct,
  32655. sub: sub,
  32656. subBuild: subBuild,
  32657. subgroupAdd: subgroupAdd,
  32658. subgroupAll: subgroupAll,
  32659. subgroupAnd: subgroupAnd,
  32660. subgroupAny: subgroupAny,
  32661. subgroupBallot: subgroupBallot,
  32662. subgroupBroadcast: subgroupBroadcast,
  32663. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32664. subgroupElect: subgroupElect,
  32665. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32666. subgroupExclusiveMul: subgroupExclusiveMul,
  32667. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32668. subgroupInclusiveMul: subgroupInclusiveMul,
  32669. subgroupIndex: subgroupIndex,
  32670. subgroupMax: subgroupMax,
  32671. subgroupMin: subgroupMin,
  32672. subgroupMul: subgroupMul,
  32673. subgroupOr: subgroupOr,
  32674. subgroupShuffle: subgroupShuffle,
  32675. subgroupShuffleDown: subgroupShuffleDown,
  32676. subgroupShuffleUp: subgroupShuffleUp,
  32677. subgroupShuffleXor: subgroupShuffleXor,
  32678. subgroupSize: subgroupSize,
  32679. subgroupXor: subgroupXor,
  32680. tan: tan,
  32681. tangentGeometry: tangentGeometry,
  32682. tangentLocal: tangentLocal,
  32683. tangentView: tangentView,
  32684. tangentWorld: tangentWorld,
  32685. texture: texture,
  32686. texture3D: texture3D,
  32687. textureBarrier: textureBarrier,
  32688. textureBicubic: textureBicubic,
  32689. textureBicubicLevel: textureBicubicLevel,
  32690. textureCubeUV: textureCubeUV,
  32691. textureLevel: textureLevel,
  32692. textureLoad: textureLoad,
  32693. textureSize: textureSize,
  32694. textureStore: textureStore,
  32695. thickness: thickness,
  32696. time: time,
  32697. toneMapping: toneMapping,
  32698. toneMappingExposure: toneMappingExposure,
  32699. toonOutlinePass: toonOutlinePass,
  32700. transformDirection: transformDirection,
  32701. transformNormal: transformNormal,
  32702. transformNormalToView: transformNormalToView,
  32703. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32704. transformedNormalView: transformedNormalView,
  32705. transformedNormalWorld: transformedNormalWorld,
  32706. transmission: transmission,
  32707. transpose: transpose,
  32708. triNoise3D: triNoise3D,
  32709. triplanarTexture: triplanarTexture,
  32710. triplanarTextures: triplanarTextures,
  32711. trunc: trunc,
  32712. uint: uint,
  32713. uintBitsToFloat: uintBitsToFloat,
  32714. uniform: uniform,
  32715. uniformArray: uniformArray,
  32716. uniformCubeTexture: uniformCubeTexture,
  32717. uniformFlow: uniformFlow,
  32718. uniformGroup: uniformGroup,
  32719. uniformTexture: uniformTexture,
  32720. unpremultiplyAlpha: unpremultiplyAlpha,
  32721. userData: userData,
  32722. uv: uv$1,
  32723. uvec2: uvec2,
  32724. uvec3: uvec3,
  32725. uvec4: uvec4,
  32726. varying: varying,
  32727. varyingProperty: varyingProperty,
  32728. vec2: vec2,
  32729. vec3: vec3,
  32730. vec4: vec4,
  32731. vectorComponents: vectorComponents,
  32732. velocity: velocity,
  32733. vertexColor: vertexColor,
  32734. vertexIndex: vertexIndex,
  32735. vertexStage: vertexStage,
  32736. vibrance: vibrance,
  32737. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32738. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32739. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32740. viewport: viewport,
  32741. viewportCoordinate: viewportCoordinate,
  32742. viewportDepthTexture: viewportDepthTexture,
  32743. viewportLinearDepth: viewportLinearDepth,
  32744. viewportMipTexture: viewportMipTexture,
  32745. viewportResolution: viewportResolution,
  32746. viewportSafeUV: viewportSafeUV,
  32747. viewportSharedTexture: viewportSharedTexture,
  32748. viewportSize: viewportSize,
  32749. viewportTexture: viewportTexture,
  32750. viewportUV: viewportUV,
  32751. wgsl: wgsl,
  32752. wgslFn: wgslFn,
  32753. workgroupArray: workgroupArray,
  32754. workgroupBarrier: workgroupBarrier,
  32755. workgroupId: workgroupId,
  32756. workingToColorSpace: workingToColorSpace,
  32757. xor: xor
  32758. });
  32759. const _clearColor = /*@__PURE__*/ new Color4();
  32760. /**
  32761. * This renderer module manages the background.
  32762. *
  32763. * @private
  32764. * @augments DataMap
  32765. */
  32766. class Background extends DataMap {
  32767. /**
  32768. * Constructs a new background management component.
  32769. *
  32770. * @param {Renderer} renderer - The renderer.
  32771. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  32772. */
  32773. constructor( renderer, nodes ) {
  32774. super();
  32775. /**
  32776. * The renderer.
  32777. *
  32778. * @type {Renderer}
  32779. */
  32780. this.renderer = renderer;
  32781. /**
  32782. * Renderer component for managing nodes related logic.
  32783. *
  32784. * @type {Nodes}
  32785. */
  32786. this.nodes = nodes;
  32787. }
  32788. /**
  32789. * Updates the background for the given scene. Depending on how `Scene.background`
  32790. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  32791. * or add a mesh to the render list for rendering the background as a textured plane
  32792. * or skybox.
  32793. *
  32794. * @param {Scene} scene - The scene.
  32795. * @param {RenderList} renderList - The current render list.
  32796. * @param {RenderContext} renderContext - The current render context.
  32797. */
  32798. update( scene, renderList, renderContext ) {
  32799. const renderer = this.renderer;
  32800. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  32801. let forceClear = false;
  32802. if ( background === null ) {
  32803. // no background settings, use clear color configuration from the renderer
  32804. renderer._clearColor.getRGB( _clearColor );
  32805. _clearColor.a = renderer._clearColor.a;
  32806. } else if ( background.isColor === true ) {
  32807. // background is an opaque color
  32808. background.getRGB( _clearColor );
  32809. _clearColor.a = 1;
  32810. forceClear = true;
  32811. } else if ( background.isNode === true ) {
  32812. const sceneData = this.get( scene );
  32813. const backgroundNode = background;
  32814. _clearColor.copy( renderer._clearColor );
  32815. let backgroundMesh = sceneData.backgroundMesh;
  32816. if ( backgroundMesh === undefined ) {
  32817. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  32818. // @TODO: Add Texture2D support using node context
  32819. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  32820. getTextureLevel: () => backgroundBlurriness
  32821. } );
  32822. let viewProj = modelViewProjection;
  32823. viewProj = viewProj.setZ( viewProj.w );
  32824. const nodeMaterial = new NodeMaterial();
  32825. nodeMaterial.name = 'Background.material';
  32826. nodeMaterial.side = BackSide;
  32827. nodeMaterial.depthTest = false;
  32828. nodeMaterial.depthWrite = false;
  32829. nodeMaterial.allowOverride = false;
  32830. nodeMaterial.fog = false;
  32831. nodeMaterial.lights = false;
  32832. nodeMaterial.vertexNode = viewProj;
  32833. nodeMaterial.colorNode = backgroundMeshNode;
  32834. sceneData.backgroundMeshNode = backgroundMeshNode;
  32835. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  32836. backgroundMesh.frustumCulled = false;
  32837. backgroundMesh.name = 'Background.mesh';
  32838. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  32839. this.matrixWorld.copyPosition( camera.matrixWorld );
  32840. };
  32841. function onBackgroundDispose() {
  32842. background.removeEventListener( 'dispose', onBackgroundDispose );
  32843. backgroundMesh.material.dispose();
  32844. backgroundMesh.geometry.dispose();
  32845. }
  32846. background.addEventListener( 'dispose', onBackgroundDispose );
  32847. }
  32848. const backgroundCacheKey = backgroundNode.getCacheKey();
  32849. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  32850. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  32851. sceneData.backgroundMeshNode.needsUpdate = true;
  32852. backgroundMesh.material.needsUpdate = true;
  32853. sceneData.backgroundCacheKey = backgroundCacheKey;
  32854. }
  32855. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  32856. } else {
  32857. error( 'Renderer: Unsupported background configuration.', background );
  32858. }
  32859. //
  32860. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  32861. if ( environmentBlendMode === 'additive' ) {
  32862. _clearColor.set( 0, 0, 0, 1 );
  32863. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32864. _clearColor.set( 0, 0, 0, 0 );
  32865. }
  32866. //
  32867. if ( renderer.autoClear === true || forceClear === true ) {
  32868. const clearColorValue = renderContext.clearColorValue;
  32869. clearColorValue.r = _clearColor.r;
  32870. clearColorValue.g = _clearColor.g;
  32871. clearColorValue.b = _clearColor.b;
  32872. clearColorValue.a = _clearColor.a;
  32873. // premultiply alpha
  32874. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32875. clearColorValue.r *= clearColorValue.a;
  32876. clearColorValue.g *= clearColorValue.a;
  32877. clearColorValue.b *= clearColorValue.a;
  32878. }
  32879. //
  32880. renderContext.depthClearValue = renderer._clearDepth;
  32881. renderContext.stencilClearValue = renderer._clearStencil;
  32882. renderContext.clearColor = renderer.autoClearColor === true;
  32883. renderContext.clearDepth = renderer.autoClearDepth === true;
  32884. renderContext.clearStencil = renderer.autoClearStencil === true;
  32885. } else {
  32886. renderContext.clearColor = false;
  32887. renderContext.clearDepth = false;
  32888. renderContext.clearStencil = false;
  32889. }
  32890. }
  32891. }
  32892. let _id$6 = 0;
  32893. /**
  32894. * A bind group represents a collection of bindings and thus a collection
  32895. * or resources. Bind groups are assigned to pipelines to provide them
  32896. * with the required resources (like uniform buffers or textures).
  32897. *
  32898. * @private
  32899. */
  32900. class BindGroup {
  32901. /**
  32902. * Constructs a new bind group.
  32903. *
  32904. * @param {string} name - The bind group's name.
  32905. * @param {Array<Binding>} bindings - An array of bindings.
  32906. * @param {number} index - The group index.
  32907. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32908. */
  32909. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32910. /**
  32911. * The bind group's name.
  32912. *
  32913. * @type {string}
  32914. */
  32915. this.name = name;
  32916. /**
  32917. * An array of bindings.
  32918. *
  32919. * @type {Array<Binding>}
  32920. */
  32921. this.bindings = bindings;
  32922. /**
  32923. * The group index.
  32924. *
  32925. * @type {number}
  32926. */
  32927. this.index = index;
  32928. /**
  32929. * An array of reference bindings.
  32930. *
  32931. * @type {Array<Binding>}
  32932. */
  32933. this.bindingsReference = bindingsReference;
  32934. /**
  32935. * The group's ID.
  32936. *
  32937. * @type {number}
  32938. */
  32939. this.id = _id$6 ++;
  32940. }
  32941. }
  32942. /**
  32943. * This module represents the state of a node builder after it was
  32944. * used to build the nodes for a render object. The state holds the
  32945. * results of the build for further processing in the renderer.
  32946. *
  32947. * Render objects with identical cache keys share the same node builder state.
  32948. *
  32949. * @private
  32950. */
  32951. class NodeBuilderState {
  32952. /**
  32953. * Constructs a new node builder state.
  32954. *
  32955. * @param {string} vertexShader - The native vertex shader code.
  32956. * @param {string} fragmentShader - The native fragment shader code.
  32957. * @param {string} computeShader - The native compute shader code.
  32958. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32959. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32960. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32961. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32962. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32963. * @param {NodeMaterialObserver} observer - A node material observer.
  32964. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32965. */
  32966. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32967. /**
  32968. * The native vertex shader code.
  32969. *
  32970. * @type {string}
  32971. */
  32972. this.vertexShader = vertexShader;
  32973. /**
  32974. * The native fragment shader code.
  32975. *
  32976. * @type {string}
  32977. */
  32978. this.fragmentShader = fragmentShader;
  32979. /**
  32980. * The native compute shader code.
  32981. *
  32982. * @type {string}
  32983. */
  32984. this.computeShader = computeShader;
  32985. /**
  32986. * An array with transform attribute objects.
  32987. * Only relevant when using compute shaders with WebGL 2.
  32988. *
  32989. * @type {Array<Object>}
  32990. */
  32991. this.transforms = transforms;
  32992. /**
  32993. * An array of node attributes representing
  32994. * the attributes of the shaders.
  32995. *
  32996. * @type {Array<NodeAttribute>}
  32997. */
  32998. this.nodeAttributes = nodeAttributes;
  32999. /**
  33000. * An array of bind groups representing the uniform or storage
  33001. * buffers, texture or samplers of the shader.
  33002. *
  33003. * @type {Array<BindGroup>}
  33004. */
  33005. this.bindings = bindings;
  33006. /**
  33007. * An array of nodes that implement their `update()` method.
  33008. *
  33009. * @type {Array<Node>}
  33010. */
  33011. this.updateNodes = updateNodes;
  33012. /**
  33013. * An array of nodes that implement their `updateBefore()` method.
  33014. *
  33015. * @type {Array<Node>}
  33016. */
  33017. this.updateBeforeNodes = updateBeforeNodes;
  33018. /**
  33019. * An array of nodes that implement their `updateAfter()` method.
  33020. *
  33021. * @type {Array<Node>}
  33022. */
  33023. this.updateAfterNodes = updateAfterNodes;
  33024. /**
  33025. * A node material observer.
  33026. *
  33027. * @type {NodeMaterialObserver}
  33028. */
  33029. this.observer = observer;
  33030. /**
  33031. * How often this state is used by render objects.
  33032. *
  33033. * @type {number}
  33034. */
  33035. this.usedTimes = 0;
  33036. }
  33037. /**
  33038. * This method is used to create a array of bind groups based
  33039. * on the existing bind groups of this state. Shared groups are
  33040. * not cloned.
  33041. *
  33042. * @return {Array<BindGroup>} A array of bind groups.
  33043. */
  33044. createBindings() {
  33045. const bindings = [];
  33046. for ( const instanceGroup of this.bindings ) {
  33047. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  33048. if ( shared !== true ) {
  33049. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  33050. bindings.push( bindingsGroup );
  33051. for ( const instanceBinding of instanceGroup.bindings ) {
  33052. bindingsGroup.bindings.push( instanceBinding.clone() );
  33053. }
  33054. } else {
  33055. bindings.push( instanceGroup );
  33056. }
  33057. }
  33058. return bindings;
  33059. }
  33060. }
  33061. /**
  33062. * {@link NodeBuilder} is going to create instances of this class during the build process
  33063. * of nodes. They represent the final shader attributes that are going to be generated
  33064. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  33065. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  33066. */
  33067. class NodeAttribute {
  33068. /**
  33069. * Constructs a new node attribute.
  33070. *
  33071. * @param {string} name - The name of the attribute.
  33072. * @param {string} type - The type of the attribute.
  33073. * @param {?Node} node - An optional reference to the node.
  33074. */
  33075. constructor( name, type, node = null ) {
  33076. /**
  33077. * This flag can be used for type testing.
  33078. *
  33079. * @type {boolean}
  33080. * @readonly
  33081. * @default true
  33082. */
  33083. this.isNodeAttribute = true;
  33084. /**
  33085. * The name of the attribute.
  33086. *
  33087. * @type {string}
  33088. */
  33089. this.name = name;
  33090. /**
  33091. * The type of the attribute.
  33092. *
  33093. * @type {string}
  33094. */
  33095. this.type = type;
  33096. /**
  33097. * An optional reference to the node.
  33098. *
  33099. * @type {?Node}
  33100. * @default null
  33101. */
  33102. this.node = node;
  33103. }
  33104. }
  33105. /**
  33106. * {@link NodeBuilder} is going to create instances of this class during the build process
  33107. * of nodes. They represent the final shader uniforms that are going to be generated
  33108. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  33109. * for this purpose.
  33110. */
  33111. class NodeUniform {
  33112. /**
  33113. * Constructs a new node uniform.
  33114. *
  33115. * @param {string} name - The name of the uniform.
  33116. * @param {string} type - The type of the uniform.
  33117. * @param {UniformNode} node - An reference to the node.
  33118. */
  33119. constructor( name, type, node ) {
  33120. /**
  33121. * This flag can be used for type testing.
  33122. *
  33123. * @type {boolean}
  33124. * @readonly
  33125. * @default true
  33126. */
  33127. this.isNodeUniform = true;
  33128. /**
  33129. * The name of the uniform.
  33130. *
  33131. * @type {string}
  33132. */
  33133. this.name = name;
  33134. /**
  33135. * The type of the uniform.
  33136. *
  33137. * @type {string}
  33138. */
  33139. this.type = type;
  33140. /**
  33141. * An reference to the node.
  33142. *
  33143. * @type {UniformNode}
  33144. */
  33145. this.node = node;
  33146. }
  33147. /**
  33148. * The value of the uniform node.
  33149. *
  33150. * @type {any}
  33151. */
  33152. get value() {
  33153. return this.node.value;
  33154. }
  33155. set value( val ) {
  33156. this.node.value = val;
  33157. }
  33158. /**
  33159. * The id of the uniform node.
  33160. *
  33161. * @type {number}
  33162. */
  33163. get id() {
  33164. return this.node.id;
  33165. }
  33166. /**
  33167. * The uniform node's group.
  33168. *
  33169. * @type {UniformGroupNode}
  33170. */
  33171. get groupNode() {
  33172. return this.node.groupNode;
  33173. }
  33174. }
  33175. /**
  33176. * {@link NodeBuilder} is going to create instances of this class during the build process
  33177. * of nodes. They represent the final shader variables that are going to be generated
  33178. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  33179. * this purpose.
  33180. */
  33181. class NodeVar {
  33182. /**
  33183. * Constructs a new node variable.
  33184. *
  33185. * @param {string} name - The name of the variable.
  33186. * @param {string} type - The type of the variable.
  33187. * @param {boolean} [readOnly=false] - The read-only flag.
  33188. * @param {?number} [count=null] - The size.
  33189. */
  33190. constructor( name, type, readOnly = false, count = null ) {
  33191. /**
  33192. * This flag can be used for type testing.
  33193. *
  33194. * @type {boolean}
  33195. * @readonly
  33196. * @default true
  33197. */
  33198. this.isNodeVar = true;
  33199. /**
  33200. * The name of the variable.
  33201. *
  33202. * @type {string}
  33203. */
  33204. this.name = name;
  33205. /**
  33206. * The type of the variable.
  33207. *
  33208. * @type {string}
  33209. */
  33210. this.type = type;
  33211. /**
  33212. * The read-only flag.
  33213. *
  33214. * @type {boolean}
  33215. */
  33216. this.readOnly = readOnly;
  33217. /**
  33218. * The size.
  33219. *
  33220. * @type {?number}
  33221. */
  33222. this.count = count;
  33223. }
  33224. }
  33225. /**
  33226. * {@link NodeBuilder} is going to create instances of this class during the build process
  33227. * of nodes. They represent the final shader varyings that are going to be generated
  33228. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  33229. * this purpose.
  33230. *
  33231. * @augments NodeVar
  33232. */
  33233. class NodeVarying extends NodeVar {
  33234. /**
  33235. * Constructs a new node varying.
  33236. *
  33237. * @param {string} name - The name of the varying.
  33238. * @param {string} type - The type of the varying.
  33239. * @param {?string} interpolationType - The interpolation type of the varying.
  33240. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33241. */
  33242. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  33243. super( name, type );
  33244. /**
  33245. * Whether this varying requires interpolation or not. This property can be used
  33246. * to check if the varying can be optimized for a variable.
  33247. *
  33248. * @type {boolean}
  33249. * @default false
  33250. */
  33251. this.needsInterpolation = false;
  33252. /**
  33253. * This flag can be used for type testing.
  33254. *
  33255. * @type {boolean}
  33256. * @readonly
  33257. * @default true
  33258. */
  33259. this.isNodeVarying = true;
  33260. /**
  33261. * The interpolation type of the varying data.
  33262. *
  33263. * @type {?string}
  33264. * @default null
  33265. */
  33266. this.interpolationType = interpolationType;
  33267. /**
  33268. * The interpolation sampling type of varying data.
  33269. *
  33270. * @type {?string}
  33271. * @default null
  33272. */
  33273. this.interpolationSampling = interpolationSampling;
  33274. }
  33275. }
  33276. /**
  33277. * {@link NodeBuilder} is going to create instances of this class during the build process
  33278. * of nodes. They represent user-defined, native shader code portions that are going to be
  33279. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  33280. * for this purpose.
  33281. */
  33282. class NodeCode {
  33283. /**
  33284. * Constructs a new code node.
  33285. *
  33286. * @param {string} name - The name of the code.
  33287. * @param {string} type - The node type.
  33288. * @param {string} [code=''] - The native shader code.
  33289. */
  33290. constructor( name, type, code = '' ) {
  33291. /**
  33292. * The name of the code.
  33293. *
  33294. * @type {string}
  33295. */
  33296. this.name = name;
  33297. /**
  33298. * The node type.
  33299. *
  33300. * @type {string}
  33301. */
  33302. this.type = type;
  33303. /**
  33304. * The native shader code.
  33305. *
  33306. * @type {string}
  33307. * @default ''
  33308. */
  33309. this.code = code;
  33310. Object.defineProperty( this, 'isNodeCode', { value: true } );
  33311. }
  33312. }
  33313. let _id$5 = 0;
  33314. /**
  33315. * This utility class is used in {@link NodeBuilder} as an internal
  33316. * cache data structure for node data.
  33317. */
  33318. class NodeCache {
  33319. /**
  33320. * Constructs a new node cache.
  33321. *
  33322. * @param {?NodeCache} parent - A reference to a parent cache.
  33323. */
  33324. constructor( parent = null ) {
  33325. /**
  33326. * The id of the cache.
  33327. *
  33328. * @type {number}
  33329. * @readonly
  33330. */
  33331. this.id = _id$5 ++;
  33332. /**
  33333. * A weak map for managing node data.
  33334. *
  33335. * @type {WeakMap<Node, Object>}
  33336. */
  33337. this.nodesData = new WeakMap();
  33338. /**
  33339. * Reference to a parent node cache.
  33340. *
  33341. * @type {?NodeCache}
  33342. * @default null
  33343. */
  33344. this.parent = parent;
  33345. }
  33346. /**
  33347. * Returns the data for the given node.
  33348. *
  33349. * @param {Node} node - The node.
  33350. * @return {?Object} The data for the node.
  33351. */
  33352. getData( node ) {
  33353. let data = this.nodesData.get( node );
  33354. if ( data === undefined && this.parent !== null ) {
  33355. data = this.parent.getData( node );
  33356. }
  33357. return data;
  33358. }
  33359. /**
  33360. * Sets the data for a given node.
  33361. *
  33362. * @param {Node} node - The node.
  33363. * @param {Object} data - The data that should be cached.
  33364. */
  33365. setData( node, data ) {
  33366. this.nodesData.set( node, data );
  33367. }
  33368. }
  33369. class StructType {
  33370. constructor( name, members ) {
  33371. this.name = name;
  33372. this.members = members;
  33373. this.output = false;
  33374. }
  33375. }
  33376. /**
  33377. * Abstract base class for uniforms.
  33378. *
  33379. * @abstract
  33380. * @private
  33381. */
  33382. class Uniform {
  33383. /**
  33384. * Constructs a new uniform.
  33385. *
  33386. * @param {string} name - The uniform's name.
  33387. * @param {any} value - The uniform's value.
  33388. */
  33389. constructor( name, value ) {
  33390. /**
  33391. * The uniform's name.
  33392. *
  33393. * @type {string}
  33394. */
  33395. this.name = name;
  33396. /**
  33397. * The uniform's value.
  33398. *
  33399. * @type {any}
  33400. */
  33401. this.value = value;
  33402. /**
  33403. * Used to build the uniform buffer according to the STD140 layout.
  33404. * Derived uniforms will set this property to a data type specific
  33405. * value.
  33406. *
  33407. * @type {number}
  33408. */
  33409. this.boundary = 0;
  33410. /**
  33411. * The item size. Derived uniforms will set this property to a data
  33412. * type specific value.
  33413. *
  33414. * @type {number}
  33415. */
  33416. this.itemSize = 0;
  33417. /**
  33418. * This property is set by {@link UniformsGroup} and marks
  33419. * the start position in the uniform buffer.
  33420. *
  33421. * @type {number}
  33422. */
  33423. this.offset = 0;
  33424. }
  33425. /**
  33426. * Sets the uniform's value.
  33427. *
  33428. * @param {any} value - The value to set.
  33429. */
  33430. setValue( value ) {
  33431. this.value = value;
  33432. }
  33433. /**
  33434. * Returns the uniform's value.
  33435. *
  33436. * @return {any} The value.
  33437. */
  33438. getValue() {
  33439. return this.value;
  33440. }
  33441. }
  33442. /**
  33443. * Represents a Number uniform.
  33444. *
  33445. * @private
  33446. * @augments Uniform
  33447. */
  33448. class NumberUniform extends Uniform {
  33449. /**
  33450. * Constructs a new Number uniform.
  33451. *
  33452. * @param {string} name - The uniform's name.
  33453. * @param {number} value - The uniform's value.
  33454. */
  33455. constructor( name, value = 0 ) {
  33456. super( name, value );
  33457. /**
  33458. * This flag can be used for type testing.
  33459. *
  33460. * @type {boolean}
  33461. * @readonly
  33462. * @default true
  33463. */
  33464. this.isNumberUniform = true;
  33465. this.boundary = 4;
  33466. this.itemSize = 1;
  33467. }
  33468. }
  33469. /**
  33470. * Represents a Vector2 uniform.
  33471. *
  33472. * @private
  33473. * @augments Uniform
  33474. */
  33475. class Vector2Uniform extends Uniform {
  33476. /**
  33477. * Constructs a new Number uniform.
  33478. *
  33479. * @param {string} name - The uniform's name.
  33480. * @param {Vector2} value - The uniform's value.
  33481. */
  33482. constructor( name, value = new Vector2() ) {
  33483. super( name, value );
  33484. /**
  33485. * This flag can be used for type testing.
  33486. *
  33487. * @type {boolean}
  33488. * @readonly
  33489. * @default true
  33490. */
  33491. this.isVector2Uniform = true;
  33492. this.boundary = 8;
  33493. this.itemSize = 2;
  33494. }
  33495. }
  33496. /**
  33497. * Represents a Vector3 uniform.
  33498. *
  33499. * @private
  33500. * @augments Uniform
  33501. */
  33502. class Vector3Uniform extends Uniform {
  33503. /**
  33504. * Constructs a new Number uniform.
  33505. *
  33506. * @param {string} name - The uniform's name.
  33507. * @param {Vector3} value - The uniform's value.
  33508. */
  33509. constructor( name, value = new Vector3() ) {
  33510. super( name, value );
  33511. /**
  33512. * This flag can be used for type testing.
  33513. *
  33514. * @type {boolean}
  33515. * @readonly
  33516. * @default true
  33517. */
  33518. this.isVector3Uniform = true;
  33519. this.boundary = 16;
  33520. this.itemSize = 3;
  33521. }
  33522. }
  33523. /**
  33524. * Represents a Vector4 uniform.
  33525. *
  33526. * @private
  33527. * @augments Uniform
  33528. */
  33529. class Vector4Uniform extends Uniform {
  33530. /**
  33531. * Constructs a new Number uniform.
  33532. *
  33533. * @param {string} name - The uniform's name.
  33534. * @param {Vector4} value - The uniform's value.
  33535. */
  33536. constructor( name, value = new Vector4() ) {
  33537. super( name, value );
  33538. /**
  33539. * This flag can be used for type testing.
  33540. *
  33541. * @type {boolean}
  33542. * @readonly
  33543. * @default true
  33544. */
  33545. this.isVector4Uniform = true;
  33546. this.boundary = 16;
  33547. this.itemSize = 4;
  33548. }
  33549. }
  33550. /**
  33551. * Represents a Color uniform.
  33552. *
  33553. * @private
  33554. * @augments Uniform
  33555. */
  33556. class ColorUniform extends Uniform {
  33557. /**
  33558. * Constructs a new Number uniform.
  33559. *
  33560. * @param {string} name - The uniform's name.
  33561. * @param {Color} value - The uniform's value.
  33562. */
  33563. constructor( name, value = new Color() ) {
  33564. super( name, value );
  33565. /**
  33566. * This flag can be used for type testing.
  33567. *
  33568. * @type {boolean}
  33569. * @readonly
  33570. * @default true
  33571. */
  33572. this.isColorUniform = true;
  33573. this.boundary = 16;
  33574. this.itemSize = 3;
  33575. }
  33576. }
  33577. /**
  33578. * Represents a Matrix2 uniform.
  33579. *
  33580. * @private
  33581. * @augments Uniform
  33582. */
  33583. class Matrix2Uniform extends Uniform {
  33584. /**
  33585. * Constructs a new Number uniform.
  33586. *
  33587. * @param {string} name - The uniform's name.
  33588. * @param {Matrix2} value - The uniform's value.
  33589. */
  33590. constructor( name, value = new Matrix2() ) {
  33591. super( name, value );
  33592. /**
  33593. * This flag can be used for type testing.
  33594. *
  33595. * @type {boolean}
  33596. * @readonly
  33597. * @default true
  33598. */
  33599. this.isMatrix2Uniform = true;
  33600. this.boundary = 8;
  33601. this.itemSize = 4;
  33602. }
  33603. }
  33604. /**
  33605. * Represents a Matrix3 uniform.
  33606. *
  33607. * @private
  33608. * @augments Uniform
  33609. */
  33610. class Matrix3Uniform extends Uniform {
  33611. /**
  33612. * Constructs a new Number uniform.
  33613. *
  33614. * @param {string} name - The uniform's name.
  33615. * @param {Matrix3} value - The uniform's value.
  33616. */
  33617. constructor( name, value = new Matrix3() ) {
  33618. super( name, value );
  33619. /**
  33620. * This flag can be used for type testing.
  33621. *
  33622. * @type {boolean}
  33623. * @readonly
  33624. * @default true
  33625. */
  33626. this.isMatrix3Uniform = true;
  33627. this.boundary = 48;
  33628. this.itemSize = 12;
  33629. }
  33630. }
  33631. /**
  33632. * Represents a Matrix4 uniform.
  33633. *
  33634. * @private
  33635. * @augments Uniform
  33636. */
  33637. class Matrix4Uniform extends Uniform {
  33638. /**
  33639. * Constructs a new Number uniform.
  33640. *
  33641. * @param {string} name - The uniform's name.
  33642. * @param {Matrix4} value - The uniform's value.
  33643. */
  33644. constructor( name, value = new Matrix4() ) {
  33645. super( name, value );
  33646. /**
  33647. * This flag can be used for type testing.
  33648. *
  33649. * @type {boolean}
  33650. * @readonly
  33651. * @default true
  33652. */
  33653. this.isMatrix4Uniform = true;
  33654. this.boundary = 64;
  33655. this.itemSize = 16;
  33656. }
  33657. }
  33658. /**
  33659. * A special form of Number uniform binding type.
  33660. * It's value is managed by a node object.
  33661. *
  33662. * @private
  33663. * @augments NumberUniform
  33664. */
  33665. class NumberNodeUniform extends NumberUniform {
  33666. /**
  33667. * Constructs a new node-based Number uniform.
  33668. *
  33669. * @param {NodeUniform} nodeUniform - The node uniform.
  33670. */
  33671. constructor( nodeUniform ) {
  33672. super( nodeUniform.name, nodeUniform.value );
  33673. /**
  33674. * The node uniform.
  33675. *
  33676. * @type {NodeUniform}
  33677. */
  33678. this.nodeUniform = nodeUniform;
  33679. }
  33680. /**
  33681. * Overwritten to return the value of the node uniform.
  33682. *
  33683. * @return {number} The value.
  33684. */
  33685. getValue() {
  33686. return this.nodeUniform.value;
  33687. }
  33688. /**
  33689. * Returns the node uniform data type.
  33690. *
  33691. * @return {string} The data type.
  33692. */
  33693. getType() {
  33694. return this.nodeUniform.type;
  33695. }
  33696. }
  33697. /**
  33698. * A special form of Vector2 uniform binding type.
  33699. * It's value is managed by a node object.
  33700. *
  33701. * @private
  33702. * @augments Vector2Uniform
  33703. */
  33704. class Vector2NodeUniform extends Vector2Uniform {
  33705. /**
  33706. * Constructs a new node-based Vector2 uniform.
  33707. *
  33708. * @param {NodeUniform} nodeUniform - The node uniform.
  33709. */
  33710. constructor( nodeUniform ) {
  33711. super( nodeUniform.name, nodeUniform.value );
  33712. /**
  33713. * The node uniform.
  33714. *
  33715. * @type {NodeUniform}
  33716. */
  33717. this.nodeUniform = nodeUniform;
  33718. }
  33719. /**
  33720. * Overwritten to return the value of the node uniform.
  33721. *
  33722. * @return {Vector2} The value.
  33723. */
  33724. getValue() {
  33725. return this.nodeUniform.value;
  33726. }
  33727. /**
  33728. * Returns the node uniform data type.
  33729. *
  33730. * @return {string} The data type.
  33731. */
  33732. getType() {
  33733. return this.nodeUniform.type;
  33734. }
  33735. }
  33736. /**
  33737. * A special form of Vector3 uniform binding type.
  33738. * It's value is managed by a node object.
  33739. *
  33740. * @private
  33741. * @augments Vector3Uniform
  33742. */
  33743. class Vector3NodeUniform extends Vector3Uniform {
  33744. /**
  33745. * Constructs a new node-based Vector3 uniform.
  33746. *
  33747. * @param {NodeUniform} nodeUniform - The node uniform.
  33748. */
  33749. constructor( nodeUniform ) {
  33750. super( nodeUniform.name, nodeUniform.value );
  33751. /**
  33752. * The node uniform.
  33753. *
  33754. * @type {NodeUniform}
  33755. */
  33756. this.nodeUniform = nodeUniform;
  33757. }
  33758. /**
  33759. * Overwritten to return the value of the node uniform.
  33760. *
  33761. * @return {Vector3} The value.
  33762. */
  33763. getValue() {
  33764. return this.nodeUniform.value;
  33765. }
  33766. /**
  33767. * Returns the node uniform data type.
  33768. *
  33769. * @return {string} The data type.
  33770. */
  33771. getType() {
  33772. return this.nodeUniform.type;
  33773. }
  33774. }
  33775. /**
  33776. * A special form of Vector4 uniform binding type.
  33777. * It's value is managed by a node object.
  33778. *
  33779. * @private
  33780. * @augments Vector4Uniform
  33781. */
  33782. class Vector4NodeUniform extends Vector4Uniform {
  33783. /**
  33784. * Constructs a new node-based Vector4 uniform.
  33785. *
  33786. * @param {NodeUniform} nodeUniform - The node uniform.
  33787. */
  33788. constructor( nodeUniform ) {
  33789. super( nodeUniform.name, nodeUniform.value );
  33790. /**
  33791. * The node uniform.
  33792. *
  33793. * @type {NodeUniform}
  33794. */
  33795. this.nodeUniform = nodeUniform;
  33796. }
  33797. /**
  33798. * Overwritten to return the value of the node uniform.
  33799. *
  33800. * @return {Vector4} The value.
  33801. */
  33802. getValue() {
  33803. return this.nodeUniform.value;
  33804. }
  33805. /**
  33806. * Returns the node uniform data type.
  33807. *
  33808. * @return {string} The data type.
  33809. */
  33810. getType() {
  33811. return this.nodeUniform.type;
  33812. }
  33813. }
  33814. /**
  33815. * A special form of Color uniform binding type.
  33816. * It's value is managed by a node object.
  33817. *
  33818. * @private
  33819. * @augments ColorUniform
  33820. */
  33821. class ColorNodeUniform extends ColorUniform {
  33822. /**
  33823. * Constructs a new node-based Color uniform.
  33824. *
  33825. * @param {NodeUniform} nodeUniform - The node uniform.
  33826. */
  33827. constructor( nodeUniform ) {
  33828. super( nodeUniform.name, nodeUniform.value );
  33829. /**
  33830. * The node uniform.
  33831. *
  33832. * @type {NodeUniform}
  33833. */
  33834. this.nodeUniform = nodeUniform;
  33835. }
  33836. /**
  33837. * Overwritten to return the value of the node uniform.
  33838. *
  33839. * @return {Color} The value.
  33840. */
  33841. getValue() {
  33842. return this.nodeUniform.value;
  33843. }
  33844. /**
  33845. * Returns the node uniform data type.
  33846. *
  33847. * @return {string} The data type.
  33848. */
  33849. getType() {
  33850. return this.nodeUniform.type;
  33851. }
  33852. }
  33853. /**
  33854. * A special form of Matrix2 uniform binding type.
  33855. * It's value is managed by a node object.
  33856. *
  33857. * @private
  33858. * @augments Matrix2Uniform
  33859. */
  33860. class Matrix2NodeUniform extends Matrix2Uniform {
  33861. /**
  33862. * Constructs a new node-based Matrix2 uniform.
  33863. *
  33864. * @param {NodeUniform} nodeUniform - The node uniform.
  33865. */
  33866. constructor( nodeUniform ) {
  33867. super( nodeUniform.name, nodeUniform.value );
  33868. /**
  33869. * The node uniform.
  33870. *
  33871. * @type {NodeUniform}
  33872. */
  33873. this.nodeUniform = nodeUniform;
  33874. }
  33875. /**
  33876. * Overwritten to return the value of the node uniform.
  33877. *
  33878. * @return {Matrix2} The value.
  33879. */
  33880. getValue() {
  33881. return this.nodeUniform.value;
  33882. }
  33883. /**
  33884. * Returns the node uniform data type.
  33885. *
  33886. * @return {string} The data type.
  33887. */
  33888. getType() {
  33889. return this.nodeUniform.type;
  33890. }
  33891. }
  33892. /**
  33893. * A special form of Matrix3 uniform binding type.
  33894. * It's value is managed by a node object.
  33895. *
  33896. * @private
  33897. * @augments Matrix3Uniform
  33898. */
  33899. class Matrix3NodeUniform extends Matrix3Uniform {
  33900. /**
  33901. * Constructs a new node-based Matrix3 uniform.
  33902. *
  33903. * @param {NodeUniform} nodeUniform - The node uniform.
  33904. */
  33905. constructor( nodeUniform ) {
  33906. super( nodeUniform.name, nodeUniform.value );
  33907. /**
  33908. * The node uniform.
  33909. *
  33910. * @type {NodeUniform}
  33911. */
  33912. this.nodeUniform = nodeUniform;
  33913. }
  33914. /**
  33915. * Overwritten to return the value of the node uniform.
  33916. *
  33917. * @return {Matrix3} The value.
  33918. */
  33919. getValue() {
  33920. return this.nodeUniform.value;
  33921. }
  33922. /**
  33923. * Returns the node uniform data type.
  33924. *
  33925. * @return {string} The data type.
  33926. */
  33927. getType() {
  33928. return this.nodeUniform.type;
  33929. }
  33930. }
  33931. /**
  33932. * A special form of Matrix4 uniform binding type.
  33933. * It's value is managed by a node object.
  33934. *
  33935. * @private
  33936. * @augments Matrix4Uniform
  33937. */
  33938. class Matrix4NodeUniform extends Matrix4Uniform {
  33939. /**
  33940. * Constructs a new node-based Matrix4 uniform.
  33941. *
  33942. * @param {NodeUniform} nodeUniform - The node uniform.
  33943. */
  33944. constructor( nodeUniform ) {
  33945. super( nodeUniform.name, nodeUniform.value );
  33946. /**
  33947. * The node uniform.
  33948. *
  33949. * @type {NodeUniform}
  33950. */
  33951. this.nodeUniform = nodeUniform;
  33952. }
  33953. /**
  33954. * Overwritten to return the value of the node uniform.
  33955. *
  33956. * @return {Matrix4} The value.
  33957. */
  33958. getValue() {
  33959. return this.nodeUniform.value;
  33960. }
  33961. /**
  33962. * Returns the node uniform data type.
  33963. *
  33964. * @return {string} The data type.
  33965. */
  33966. getType() {
  33967. return this.nodeUniform.type;
  33968. }
  33969. }
  33970. const rendererCache = new WeakMap();
  33971. const typeFromArray = new Map( [
  33972. [ Int8Array, 'int' ],
  33973. [ Int16Array, 'int' ],
  33974. [ Int32Array, 'int' ],
  33975. [ Uint8Array, 'uint' ],
  33976. [ Uint16Array, 'uint' ],
  33977. [ Uint32Array, 'uint' ],
  33978. [ Float32Array, 'float' ]
  33979. ] );
  33980. const toFloat = ( value ) => {
  33981. if ( /e/g.test( value ) ) {
  33982. return String( value ).replace( /\+/g, '' );
  33983. } else {
  33984. value = Number( value );
  33985. return value + ( value % 1 ? '' : '.0' );
  33986. }
  33987. };
  33988. /**
  33989. * Base class for builders which generate a shader program based
  33990. * on a 3D object and its node material definition.
  33991. */
  33992. class NodeBuilder {
  33993. /**
  33994. * Constructs a new node builder.
  33995. *
  33996. * @param {Object3D} object - The 3D object.
  33997. * @param {Renderer} renderer - The current renderer.
  33998. * @param {NodeParser} parser - A reference to a node parser.
  33999. */
  34000. constructor( object, renderer, parser ) {
  34001. /**
  34002. * The 3D object.
  34003. *
  34004. * @type {Object3D}
  34005. */
  34006. this.object = object;
  34007. /**
  34008. * The material of the 3D object.
  34009. *
  34010. * @type {?Material}
  34011. */
  34012. this.material = ( object && object.material ) || null;
  34013. /**
  34014. * The geometry of the 3D object.
  34015. *
  34016. * @type {?BufferGeometry}
  34017. */
  34018. this.geometry = ( object && object.geometry ) || null;
  34019. /**
  34020. * The current renderer.
  34021. *
  34022. * @type {Renderer}
  34023. */
  34024. this.renderer = renderer;
  34025. /**
  34026. * A reference to a node parser.
  34027. *
  34028. * @type {NodeParser}
  34029. */
  34030. this.parser = parser;
  34031. /**
  34032. * The scene the 3D object belongs to.
  34033. *
  34034. * @type {?Scene}
  34035. * @default null
  34036. */
  34037. this.scene = null;
  34038. /**
  34039. * The camera the 3D object is rendered with.
  34040. *
  34041. * @type {?Camera}
  34042. * @default null
  34043. */
  34044. this.camera = null;
  34045. /**
  34046. * A list of all nodes the builder is processing
  34047. * for this 3D object.
  34048. *
  34049. * @type {Array<Node>}
  34050. */
  34051. this.nodes = [];
  34052. /**
  34053. * A list of all sequential nodes.
  34054. *
  34055. * @type {Array<Node>}
  34056. */
  34057. this.sequentialNodes = [];
  34058. /**
  34059. * A list of all nodes which {@link Node#update} method should be executed.
  34060. *
  34061. * @type {Array<Node>}
  34062. */
  34063. this.updateNodes = [];
  34064. /**
  34065. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  34066. *
  34067. * @type {Array<Node>}
  34068. */
  34069. this.updateBeforeNodes = [];
  34070. /**
  34071. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  34072. *
  34073. * @type {Array<Node>}
  34074. */
  34075. this.updateAfterNodes = [];
  34076. /**
  34077. * A dictionary that assigns each node to a unique hash.
  34078. *
  34079. * @type {Object<number,Node>}
  34080. */
  34081. this.hashNodes = {};
  34082. /**
  34083. * A reference to a node material observer.
  34084. *
  34085. * @type {?NodeMaterialObserver}
  34086. * @default null
  34087. */
  34088. this.observer = null;
  34089. /**
  34090. * A reference to the current lights node.
  34091. *
  34092. * @type {?LightsNode}
  34093. * @default null
  34094. */
  34095. this.lightsNode = null;
  34096. /**
  34097. * A reference to the current environment node.
  34098. *
  34099. * @type {?Node}
  34100. * @default null
  34101. */
  34102. this.environmentNode = null;
  34103. /**
  34104. * A reference to the current fog node.
  34105. *
  34106. * @type {?Node}
  34107. * @default null
  34108. */
  34109. this.fogNode = null;
  34110. /**
  34111. * The current clipping context.
  34112. *
  34113. * @type {?ClippingContext}
  34114. */
  34115. this.clippingContext = null;
  34116. /**
  34117. * The generated vertex shader.
  34118. *
  34119. * @type {?string}
  34120. */
  34121. this.vertexShader = null;
  34122. /**
  34123. * The generated fragment shader.
  34124. *
  34125. * @type {?string}
  34126. */
  34127. this.fragmentShader = null;
  34128. /**
  34129. * The generated compute shader.
  34130. *
  34131. * @type {?string}
  34132. */
  34133. this.computeShader = null;
  34134. /**
  34135. * Nodes used in the primary flow of code generation.
  34136. *
  34137. * @type {Object<string,Array<Node>>}
  34138. */
  34139. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  34140. /**
  34141. * Nodes code from `.flowNodes`.
  34142. *
  34143. * @type {Object<string,string>}
  34144. */
  34145. this.flowCode = { vertex: '', fragment: '', compute: '' };
  34146. /**
  34147. * This dictionary holds the node uniforms of the builder.
  34148. * The uniforms are maintained in an array for each shader stage.
  34149. *
  34150. * @type {Object}
  34151. */
  34152. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  34153. /**
  34154. * This dictionary holds the output structs of the builder.
  34155. * The structs are maintained in an array for each shader stage.
  34156. *
  34157. * @type {Object}
  34158. */
  34159. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  34160. /**
  34161. * This dictionary holds the types of the builder.
  34162. *
  34163. * @type {Object}
  34164. */
  34165. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  34166. /**
  34167. * This dictionary holds the bindings for each shader stage.
  34168. *
  34169. * @type {Object}
  34170. */
  34171. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  34172. /**
  34173. * This dictionary maintains the binding indices per bind group.
  34174. *
  34175. * @type {Object}
  34176. */
  34177. this.bindingsIndexes = {};
  34178. /**
  34179. * Reference to the array of bind groups.
  34180. *
  34181. * @type {?Array<BindGroup>}
  34182. */
  34183. this.bindGroups = null;
  34184. /**
  34185. * This array holds the node attributes of this builder
  34186. * created via {@link AttributeNode}.
  34187. *
  34188. * @type {Array<NodeAttribute>}
  34189. */
  34190. this.attributes = [];
  34191. /**
  34192. * This array holds the node attributes of this builder
  34193. * created via {@link BufferAttributeNode}.
  34194. *
  34195. * @type {Array<NodeAttribute>}
  34196. */
  34197. this.bufferAttributes = [];
  34198. /**
  34199. * This array holds the node varyings of this builder.
  34200. *
  34201. * @type {Array<NodeVarying>}
  34202. */
  34203. this.varyings = [];
  34204. /**
  34205. * This dictionary holds the (native) node codes of this builder.
  34206. * The codes are maintained in an array for each shader stage.
  34207. *
  34208. * @type {Object<string,Array<NodeCode>>}
  34209. */
  34210. this.codes = {};
  34211. /**
  34212. * This dictionary holds the node variables of this builder.
  34213. * The variables are maintained in an array for each shader stage.
  34214. * This dictionary is also used to count the number of variables
  34215. * according to their type (const, vars).
  34216. *
  34217. * @type {Object<string,Array<NodeVar>|number>}
  34218. */
  34219. this.vars = {};
  34220. /**
  34221. * This dictionary holds the declarations for each shader stage.
  34222. *
  34223. * @type {Object}
  34224. */
  34225. this.declarations = {};
  34226. /**
  34227. * Current code flow.
  34228. * All code generated in this stack will be stored in `.flow`.
  34229. *
  34230. * @type {{code: string}}
  34231. */
  34232. this.flow = { code: '' };
  34233. /**
  34234. * A chain of nodes.
  34235. * Used to check recursive calls in node-graph.
  34236. *
  34237. * @type {Array<Node>}
  34238. */
  34239. this.chaining = [];
  34240. /**
  34241. * The current stack.
  34242. * This reflects the current process in the code block hierarchy,
  34243. * it is useful to know if the current process is inside a conditional for example.
  34244. *
  34245. * @type {StackNode}
  34246. */
  34247. this.stack = stack();
  34248. /**
  34249. * List of stack nodes.
  34250. * The current stack hierarchy is stored in an array.
  34251. *
  34252. * @type {Array<StackNode>}
  34253. */
  34254. this.stacks = [];
  34255. /**
  34256. * A tab value. Used for shader string generation.
  34257. *
  34258. * @type {string}
  34259. * @default '\t'
  34260. */
  34261. this.tab = '\t';
  34262. /**
  34263. * Reference to the current function node.
  34264. *
  34265. * @type {?FunctionNode}
  34266. * @default null
  34267. */
  34268. this.currentFunctionNode = null;
  34269. /**
  34270. * The builder's context.
  34271. *
  34272. * @type {Object}
  34273. */
  34274. this.context = {
  34275. material: this.material
  34276. };
  34277. /**
  34278. * The builder's cache.
  34279. *
  34280. * @type {NodeCache}
  34281. */
  34282. this.cache = new NodeCache();
  34283. /**
  34284. * Since the {@link NodeBuilder#cache} might be temporarily
  34285. * overwritten by other caches, this member retains the reference
  34286. * to the builder's own cache.
  34287. *
  34288. * @type {NodeCache}
  34289. * @default this.cache
  34290. */
  34291. this.globalCache = this.cache;
  34292. this.flowsData = new WeakMap();
  34293. /**
  34294. * The current shader stage.
  34295. *
  34296. * @type {?('vertex'|'fragment'|'compute'|'any')}
  34297. */
  34298. this.shaderStage = null;
  34299. /**
  34300. * The current build stage.
  34301. *
  34302. * @type {?('setup'|'analyze'|'generate')}
  34303. */
  34304. this.buildStage = null;
  34305. /**
  34306. * The sub-build layers.
  34307. *
  34308. * @type {Array<SubBuildNode>}
  34309. * @default []
  34310. */
  34311. this.subBuildLayers = [];
  34312. /**
  34313. * The current stack of nodes.
  34314. *
  34315. * @type {?StackNode}
  34316. * @default null
  34317. */
  34318. this.currentStack = null;
  34319. /**
  34320. * The current sub-build TSL function(Fn).
  34321. *
  34322. * @type {?string}
  34323. * @default null
  34324. */
  34325. this.subBuildFn = null;
  34326. /**
  34327. * The current TSL function(Fn) call node.
  34328. *
  34329. * @type {?Node}
  34330. * @default null
  34331. */
  34332. this.fnCall = null;
  34333. }
  34334. /**
  34335. * Returns the bind groups of the current renderer.
  34336. *
  34337. * @return {ChainMap} The cache.
  34338. */
  34339. getBindGroupsCache() {
  34340. let bindGroupsCache = rendererCache.get( this.renderer );
  34341. if ( bindGroupsCache === undefined ) {
  34342. bindGroupsCache = new ChainMap();
  34343. rendererCache.set( this.renderer, bindGroupsCache );
  34344. }
  34345. return bindGroupsCache;
  34346. }
  34347. /**
  34348. * Factory method for creating an instance of {@link RenderTarget} with the given
  34349. * dimensions and options.
  34350. *
  34351. * @param {number} width - The width of the render target.
  34352. * @param {number} height - The height of the render target.
  34353. * @param {Object} options - The options of the render target.
  34354. * @return {RenderTarget} The render target.
  34355. */
  34356. createRenderTarget( width, height, options ) {
  34357. return new RenderTarget( width, height, options );
  34358. }
  34359. /**
  34360. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  34361. * dimensions and options.
  34362. *
  34363. * @param {number} size - The size of the cube render target.
  34364. * @param {Object} options - The options of the cube render target.
  34365. * @return {CubeRenderTarget} The cube render target.
  34366. */
  34367. createCubeRenderTarget( size, options ) {
  34368. return new CubeRenderTarget( size, options );
  34369. }
  34370. /**
  34371. * Whether the given node is included in the internal array of nodes or not.
  34372. *
  34373. * @param {Node} node - The node to test.
  34374. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  34375. */
  34376. includes( node ) {
  34377. return this.nodes.includes( node );
  34378. }
  34379. /**
  34380. * Returns the output struct name which is required by
  34381. * {@link OutputStructNode}.
  34382. *
  34383. * @abstract
  34384. * @return {string} The name of the output struct.
  34385. */
  34386. getOutputStructName() {}
  34387. /**
  34388. * Returns a bind group for the given group name and binding.
  34389. *
  34390. * @private
  34391. * @param {string} groupName - The group name.
  34392. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  34393. * @return {BindGroup} The bind group
  34394. */
  34395. _getBindGroup( groupName, bindings ) {
  34396. const bindGroupsCache = this.getBindGroupsCache();
  34397. //
  34398. const bindingsArray = [];
  34399. let sharedGroup = true;
  34400. for ( const binding of bindings ) {
  34401. bindingsArray.push( binding );
  34402. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  34403. }
  34404. //
  34405. let bindGroup;
  34406. if ( sharedGroup ) {
  34407. bindGroup = bindGroupsCache.get( bindingsArray );
  34408. if ( bindGroup === undefined ) {
  34409. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34410. bindGroupsCache.set( bindingsArray, bindGroup );
  34411. }
  34412. } else {
  34413. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34414. }
  34415. return bindGroup;
  34416. }
  34417. /**
  34418. * Returns an array of node uniform groups for the given group name and shader stage.
  34419. *
  34420. * @param {string} groupName - The group name.
  34421. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34422. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  34423. */
  34424. getBindGroupArray( groupName, shaderStage ) {
  34425. const bindings = this.bindings[ shaderStage ];
  34426. let bindGroup = bindings[ groupName ];
  34427. if ( bindGroup === undefined ) {
  34428. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  34429. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  34430. }
  34431. bindings[ groupName ] = bindGroup = [];
  34432. }
  34433. return bindGroup;
  34434. }
  34435. /**
  34436. * Returns a list bindings of all shader stages separated by groups.
  34437. *
  34438. * @return {Array<BindGroup>} The list of bindings.
  34439. */
  34440. getBindings() {
  34441. let bindingsGroups = this.bindGroups;
  34442. if ( bindingsGroups === null ) {
  34443. const groups = {};
  34444. const bindings = this.bindings;
  34445. for ( const shaderStage of shaderStages ) {
  34446. for ( const groupName in bindings[ shaderStage ] ) {
  34447. const uniforms = bindings[ shaderStage ][ groupName ];
  34448. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  34449. groupUniforms.push( ...uniforms );
  34450. }
  34451. }
  34452. bindingsGroups = [];
  34453. for ( const groupName in groups ) {
  34454. const group = groups[ groupName ];
  34455. const bindingsGroup = this._getBindGroup( groupName, group );
  34456. bindingsGroups.push( bindingsGroup );
  34457. }
  34458. this.bindGroups = bindingsGroups;
  34459. }
  34460. return bindingsGroups;
  34461. }
  34462. /**
  34463. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  34464. */
  34465. sortBindingGroups() {
  34466. const bindingsGroups = this.getBindings();
  34467. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  34468. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  34469. const bindingGroup = bindingsGroups[ i ];
  34470. this.bindingsIndexes[ bindingGroup.name ].group = i;
  34471. bindingGroup.index = i;
  34472. }
  34473. }
  34474. /**
  34475. * The builder maintains each node in a hash-based dictionary.
  34476. * This method sets the given node (value) with the given hash (key) into this dictionary.
  34477. *
  34478. * @param {Node} node - The node to add.
  34479. * @param {number} hash - The hash of the node.
  34480. */
  34481. setHashNode( node, hash ) {
  34482. this.hashNodes[ hash ] = node;
  34483. }
  34484. /**
  34485. * Adds a node to this builder.
  34486. *
  34487. * @param {Node} node - The node to add.
  34488. */
  34489. addNode( node ) {
  34490. if ( this.nodes.includes( node ) === false ) {
  34491. this.nodes.push( node );
  34492. this.setHashNode( node, node.getHash( this ) );
  34493. }
  34494. }
  34495. /**
  34496. * It is used to add Nodes that will be used as FRAME and RENDER events,
  34497. * and need to follow a certain sequence in the calls to work correctly.
  34498. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  34499. *
  34500. * @param {Node} node - The node to add.
  34501. */
  34502. addSequentialNode( node ) {
  34503. if ( this.sequentialNodes.includes( node ) === false ) {
  34504. this.sequentialNodes.push( node );
  34505. }
  34506. }
  34507. /**
  34508. * Checks the update types of nodes
  34509. */
  34510. buildUpdateNodes() {
  34511. for ( const node of this.nodes ) {
  34512. const updateType = node.getUpdateType();
  34513. if ( updateType !== NodeUpdateType.NONE ) {
  34514. this.updateNodes.push( node );
  34515. }
  34516. }
  34517. for ( const node of this.sequentialNodes ) {
  34518. const updateBeforeType = node.getUpdateBeforeType();
  34519. const updateAfterType = node.getUpdateAfterType();
  34520. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  34521. this.updateBeforeNodes.push( node );
  34522. }
  34523. if ( updateAfterType !== NodeUpdateType.NONE ) {
  34524. this.updateAfterNodes.push( node );
  34525. }
  34526. }
  34527. }
  34528. /**
  34529. * A reference the current node which is the
  34530. * last node in the chain of nodes.
  34531. *
  34532. * @type {Node}
  34533. */
  34534. get currentNode() {
  34535. return this.chaining[ this.chaining.length - 1 ];
  34536. }
  34537. /**
  34538. * Whether the given texture is filtered or not.
  34539. *
  34540. * @param {Texture} texture - The texture to check.
  34541. * @return {boolean} Whether the given texture is filtered or not.
  34542. */
  34543. isFilteredTexture( texture ) {
  34544. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  34545. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  34546. }
  34547. /**
  34548. * Adds the given node to the internal node chain.
  34549. * This is used to check recursive calls in node-graph.
  34550. *
  34551. * @param {Node} node - The node to add.
  34552. */
  34553. addChain( node ) {
  34554. /*
  34555. if ( this.chaining.indexOf( node ) !== - 1 ) {
  34556. warn( 'Recursive node: ', node );
  34557. }
  34558. */
  34559. this.chaining.push( node );
  34560. }
  34561. /**
  34562. * Removes the given node from the internal node chain.
  34563. *
  34564. * @param {Node} node - The node to remove.
  34565. */
  34566. removeChain( node ) {
  34567. const lastChain = this.chaining.pop();
  34568. if ( lastChain !== node ) {
  34569. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  34570. }
  34571. }
  34572. /**
  34573. * Returns the native shader method name for a given generic name. E.g.
  34574. * the method name `textureDimensions` matches the WGSL name but must be
  34575. * resolved to `textureSize` in GLSL.
  34576. *
  34577. * @abstract
  34578. * @param {string} method - The method name to resolve.
  34579. * @return {string} The resolved method name.
  34580. */
  34581. getMethod( method ) {
  34582. return method;
  34583. }
  34584. /**
  34585. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34586. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34587. *
  34588. * @abstract
  34589. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34590. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34591. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34592. * @return {string} The resolved method name.
  34593. */
  34594. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34595. return null;
  34596. }
  34597. /**
  34598. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34599. *
  34600. * @param {number} hash - The hash of the node.
  34601. * @return {Node} The found node.
  34602. */
  34603. getNodeFromHash( hash ) {
  34604. return this.hashNodes[ hash ];
  34605. }
  34606. /**
  34607. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34608. *
  34609. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34610. * @param {Node} node - The node to add.
  34611. * @return {Node} The node.
  34612. */
  34613. addFlow( shaderStage, node ) {
  34614. this.flowNodes[ shaderStage ].push( node );
  34615. return node;
  34616. }
  34617. /**
  34618. * Sets builder's context.
  34619. *
  34620. * @param {Object} context - The context to set.
  34621. */
  34622. setContext( context ) {
  34623. this.context = context;
  34624. }
  34625. /**
  34626. * Returns the builder's current context.
  34627. *
  34628. * @return {Object} The builder's current context.
  34629. */
  34630. getContext() {
  34631. return this.context;
  34632. }
  34633. /**
  34634. * Adds context data to the builder's current context.
  34635. *
  34636. * @param {Object} context - The context to add.
  34637. * @return {Object} The previous context.
  34638. */
  34639. addContext( context ) {
  34640. const previousContext = this.getContext();
  34641. this.setContext( { ...this.context, ...context } );
  34642. return previousContext;
  34643. }
  34644. /**
  34645. * Gets a context used in shader construction that can be shared across different materials.
  34646. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34647. *
  34648. * @return {Object} The builder's current context without material.
  34649. */
  34650. getSharedContext() {
  34651. ({ ...this.context });
  34652. return this.context;
  34653. }
  34654. /**
  34655. * Sets builder's cache.
  34656. *
  34657. * @param {NodeCache} cache - The cache to set.
  34658. */
  34659. setCache( cache ) {
  34660. this.cache = cache;
  34661. }
  34662. /**
  34663. * Returns the builder's current cache.
  34664. *
  34665. * @return {NodeCache} The builder's current cache.
  34666. */
  34667. getCache() {
  34668. return this.cache;
  34669. }
  34670. /**
  34671. * Returns a cache for the given node.
  34672. *
  34673. * @param {Node} node - The node.
  34674. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34675. * @return {NodeCache} The cache.
  34676. */
  34677. getCacheFromNode( node, parent = true ) {
  34678. const data = this.getDataFromNode( node );
  34679. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34680. return data.cache;
  34681. }
  34682. /**
  34683. * Whether the requested feature is available or not.
  34684. *
  34685. * @abstract
  34686. * @param {string} name - The requested feature.
  34687. * @return {boolean} Whether the requested feature is supported or not.
  34688. */
  34689. isAvailable( /*name*/ ) {
  34690. return false;
  34691. }
  34692. /**
  34693. * Returns the vertexIndex input variable as a native shader string.
  34694. *
  34695. * @abstract
  34696. * @return {string} The instanceIndex shader string.
  34697. */
  34698. getVertexIndex() {
  34699. warn( 'Abstract function.' );
  34700. }
  34701. /**
  34702. * Contextually returns either the vertex stage instance index builtin
  34703. * or the linearized index of an compute invocation within a grid of workgroups.
  34704. *
  34705. * @abstract
  34706. * @return {string} The instanceIndex shader string.
  34707. */
  34708. getInstanceIndex() {
  34709. warn( 'Abstract function.' );
  34710. }
  34711. /**
  34712. * Returns the drawIndex input variable as a native shader string.
  34713. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34714. *
  34715. * @abstract
  34716. * @return {?string} The drawIndex shader string.
  34717. */
  34718. getDrawIndex() {
  34719. warn( 'Abstract function.' );
  34720. }
  34721. /**
  34722. * Returns the frontFacing input variable as a native shader string.
  34723. *
  34724. * @abstract
  34725. * @return {string} The frontFacing shader string.
  34726. */
  34727. getFrontFacing() {
  34728. warn( 'Abstract function.' );
  34729. }
  34730. /**
  34731. * Returns the fragCoord input variable as a native shader string.
  34732. *
  34733. * @abstract
  34734. * @return {string} The fragCoord shader string.
  34735. */
  34736. getFragCoord() {
  34737. warn( 'Abstract function.' );
  34738. }
  34739. /**
  34740. * Whether to flip texture data along its vertical axis or not. WebGL needs
  34741. * this method evaluate to `true`, WebGPU to `false`.
  34742. *
  34743. * @abstract
  34744. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  34745. */
  34746. isFlipY() {
  34747. return false;
  34748. }
  34749. /**
  34750. * Calling this method increases the usage count for the given node by one.
  34751. *
  34752. * @param {Node} node - The node to increase the usage count for.
  34753. * @return {number} The updated usage count.
  34754. */
  34755. increaseUsage( node ) {
  34756. const nodeData = this.getDataFromNode( node );
  34757. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  34758. return nodeData.usageCount;
  34759. }
  34760. /**
  34761. * Generates a texture sample shader string for the given texture data.
  34762. *
  34763. * @abstract
  34764. * @param {Texture} texture - The texture.
  34765. * @param {string} textureProperty - The texture property name.
  34766. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34767. * @return {string} The generated shader string.
  34768. */
  34769. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  34770. warn( 'Abstract function.' );
  34771. }
  34772. /**
  34773. * Generates a texture LOD shader string for the given texture data.
  34774. *
  34775. * @abstract
  34776. * @param {Texture} texture - The texture.
  34777. * @param {string} textureProperty - The texture property name.
  34778. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34779. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  34780. * @param {string} levelSnippet - Snippet defining the mip level.
  34781. * @return {string} The generated shader string.
  34782. */
  34783. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  34784. warn( 'Abstract function.' );
  34785. }
  34786. /**
  34787. * Generates the array declaration string.
  34788. *
  34789. * @param {string} type - The type.
  34790. * @param {?number} [count] - The count.
  34791. * @return {string} The generated value as a shader string.
  34792. */
  34793. generateArrayDeclaration( type, count ) {
  34794. return this.getType( type ) + '[ ' + count + ' ]';
  34795. }
  34796. /**
  34797. * Generates the array shader string for the given type and value.
  34798. *
  34799. * @param {string} type - The type.
  34800. * @param {?number} [count] - The count.
  34801. * @param {?Array<Node>} [values=null] - The default values.
  34802. * @return {string} The generated value as a shader string.
  34803. */
  34804. generateArray( type, count, values = null ) {
  34805. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  34806. for ( let i = 0; i < count; i ++ ) {
  34807. const value = values ? values[ i ] : null;
  34808. if ( value !== null ) {
  34809. snippet += value.build( this, type );
  34810. } else {
  34811. snippet += this.generateConst( type );
  34812. }
  34813. if ( i < count - 1 ) snippet += ', ';
  34814. }
  34815. snippet += ' )';
  34816. return snippet;
  34817. }
  34818. /**
  34819. * Generates the struct shader string.
  34820. *
  34821. * @param {string} type - The type.
  34822. * @param {Array<Object>} [membersLayout] - The count.
  34823. * @param {?Array<Node>} [values=null] - The default values.
  34824. * @return {string} The generated value as a shader string.
  34825. */
  34826. generateStruct( type, membersLayout, values = null ) {
  34827. const snippets = [];
  34828. for ( const member of membersLayout ) {
  34829. const { name, type } = member;
  34830. if ( values && values[ name ] && values[ name ].isNode ) {
  34831. snippets.push( values[ name ].build( this, type ) );
  34832. } else {
  34833. snippets.push( this.generateConst( type ) );
  34834. }
  34835. }
  34836. return type + '( ' + snippets.join( ', ' ) + ' )';
  34837. }
  34838. /**
  34839. * Generates the shader string for the given type and value.
  34840. *
  34841. * @param {string} type - The type.
  34842. * @param {?any} [value=null] - The value.
  34843. * @return {string} The generated value as a shader string.
  34844. */
  34845. generateConst( type, value = null ) {
  34846. if ( value === null ) {
  34847. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  34848. else if ( type === 'bool' ) value = false;
  34849. else if ( type === 'color' ) value = new Color();
  34850. else if ( type === 'vec2' ) value = new Vector2();
  34851. else if ( type === 'vec3' ) value = new Vector3();
  34852. else if ( type === 'vec4' ) value = new Vector4();
  34853. }
  34854. if ( type === 'float' ) return toFloat( value );
  34855. if ( type === 'int' ) return `${ Math.round( value ) }`;
  34856. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  34857. if ( type === 'bool' ) return value ? 'true' : 'false';
  34858. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  34859. const typeLength = this.getTypeLength( type );
  34860. const componentType = this.getComponentType( type );
  34861. const generateConst = value => this.generateConst( componentType, value );
  34862. if ( typeLength === 2 ) {
  34863. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  34864. } else if ( typeLength === 3 ) {
  34865. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  34866. } else if ( typeLength === 4 && type !== 'mat2' ) {
  34867. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  34868. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  34869. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  34870. } else if ( typeLength > 4 ) {
  34871. return `${ this.getType( type ) }()`;
  34872. }
  34873. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  34874. }
  34875. /**
  34876. * It might be necessary to convert certain data types to different ones
  34877. * so this method can be used to hide the conversion.
  34878. *
  34879. * @param {string} type - The type.
  34880. * @return {string} The updated type.
  34881. */
  34882. getType( type ) {
  34883. if ( type === 'color' ) return 'vec3';
  34884. return type;
  34885. }
  34886. /**
  34887. * Whether the given attribute name is defined in the geometry or not.
  34888. *
  34889. * @param {string} name - The attribute name.
  34890. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34891. */
  34892. hasGeometryAttribute( name ) {
  34893. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34894. }
  34895. /**
  34896. * Returns a node attribute for the given name and type.
  34897. *
  34898. * @param {string} name - The attribute's name.
  34899. * @param {string} type - The attribute's type.
  34900. * @return {NodeAttribute} The node attribute.
  34901. */
  34902. getAttribute( name, type ) {
  34903. const attributes = this.attributes;
  34904. // find attribute
  34905. for ( const attribute of attributes ) {
  34906. if ( attribute.name === name ) {
  34907. return attribute;
  34908. }
  34909. }
  34910. // create a new if no exist
  34911. const attribute = new NodeAttribute( name, type );
  34912. this.registerDeclaration( attribute );
  34913. attributes.push( attribute );
  34914. return attribute;
  34915. }
  34916. /**
  34917. * Returns for the given node and shader stage the property name for the shader.
  34918. *
  34919. * @param {Node} node - The node.
  34920. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34921. * @return {string} The property name.
  34922. */
  34923. getPropertyName( node/*, shaderStage*/ ) {
  34924. return node.name;
  34925. }
  34926. /**
  34927. * Whether the given type is a vector type or not.
  34928. *
  34929. * @param {string} type - The type to check.
  34930. * @return {boolean} Whether the given type is a vector type or not.
  34931. */
  34932. isVector( type ) {
  34933. return /vec\d/.test( type );
  34934. }
  34935. /**
  34936. * Whether the given type is a matrix type or not.
  34937. *
  34938. * @param {string} type - The type to check.
  34939. * @return {boolean} Whether the given type is a matrix type or not.
  34940. */
  34941. isMatrix( type ) {
  34942. return /mat\d/.test( type );
  34943. }
  34944. /**
  34945. * Whether the given type is a reference type or not.
  34946. *
  34947. * @param {string} type - The type to check.
  34948. * @return {boolean} Whether the given type is a reference type or not.
  34949. */
  34950. isReference( type ) {
  34951. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34952. }
  34953. /**
  34954. * Checks if the given texture requires a manual conversion to the working color space.
  34955. *
  34956. * @abstract
  34957. * @param {Texture} texture - The texture to check.
  34958. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34959. */
  34960. needsToWorkingColorSpace( /*texture*/ ) {
  34961. return false;
  34962. }
  34963. /**
  34964. * Returns the component type of a given texture.
  34965. *
  34966. * @param {Texture} texture - The texture.
  34967. * @return {string} The component type.
  34968. */
  34969. getComponentTypeFromTexture( texture ) {
  34970. const type = texture.type;
  34971. if ( texture.isDataTexture ) {
  34972. if ( type === IntType ) return 'int';
  34973. if ( type === UnsignedIntType ) return 'uint';
  34974. }
  34975. return 'float';
  34976. }
  34977. /**
  34978. * Returns the element type for a given type.
  34979. *
  34980. * @param {string} type - The type.
  34981. * @return {string} The element type.
  34982. */
  34983. getElementType( type ) {
  34984. if ( type === 'mat2' ) return 'vec2';
  34985. if ( type === 'mat3' ) return 'vec3';
  34986. if ( type === 'mat4' ) return 'vec4';
  34987. return this.getComponentType( type );
  34988. }
  34989. /**
  34990. * Returns the component type for a given type.
  34991. *
  34992. * @param {string} type - The type.
  34993. * @return {string} The component type.
  34994. */
  34995. getComponentType( type ) {
  34996. type = this.getVectorType( type );
  34997. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  34998. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  34999. if ( componentType === null ) return null;
  35000. if ( componentType[ 1 ] === 'b' ) return 'bool';
  35001. if ( componentType[ 1 ] === 'i' ) return 'int';
  35002. if ( componentType[ 1 ] === 'u' ) return 'uint';
  35003. return 'float';
  35004. }
  35005. /**
  35006. * Returns the vector type for a given type.
  35007. *
  35008. * @param {string} type - The type.
  35009. * @return {string} The vector type.
  35010. */
  35011. getVectorType( type ) {
  35012. if ( type === 'color' ) return 'vec3';
  35013. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  35014. return type;
  35015. }
  35016. /**
  35017. * Returns the data type for the given the length and component type.
  35018. *
  35019. * @param {number} length - The length.
  35020. * @param {string} [componentType='float'] - The component type.
  35021. * @return {string} The type.
  35022. */
  35023. getTypeFromLength( length, componentType = 'float' ) {
  35024. if ( length === 1 ) return componentType;
  35025. let baseType = getTypeFromLength( length );
  35026. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  35027. // fix edge case for mat2x2 being same size as vec4
  35028. if ( /mat2/.test( componentType ) === true ) {
  35029. baseType = baseType.replace( 'vec', 'mat' );
  35030. }
  35031. return prefix + baseType;
  35032. }
  35033. /**
  35034. * Returns the type for a given typed array.
  35035. *
  35036. * @param {TypedArray} array - The typed array.
  35037. * @return {string} The type.
  35038. */
  35039. getTypeFromArray( array ) {
  35040. return typeFromArray.get( array.constructor );
  35041. }
  35042. /**
  35043. * Returns the type is an integer type.
  35044. *
  35045. * @param {string} type - The type.
  35046. * @return {boolean} Whether the type is an integer type or not.
  35047. */
  35048. isInteger( type ) {
  35049. return /int|uint|(i|u)vec/.test( type );
  35050. }
  35051. /**
  35052. * Returns the type for a given buffer attribute.
  35053. *
  35054. * @param {BufferAttribute} attribute - The buffer attribute.
  35055. * @return {string} The type.
  35056. */
  35057. getTypeFromAttribute( attribute ) {
  35058. let dataAttribute = attribute;
  35059. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35060. const array = dataAttribute.array;
  35061. const itemSize = attribute.itemSize;
  35062. const normalized = attribute.normalized;
  35063. let arrayType;
  35064. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  35065. arrayType = this.getTypeFromArray( array );
  35066. }
  35067. return this.getTypeFromLength( itemSize, arrayType );
  35068. }
  35069. /**
  35070. * Returns the length for the given data type.
  35071. *
  35072. * @param {string} type - The data type.
  35073. * @return {number} The length.
  35074. */
  35075. getTypeLength( type ) {
  35076. const vecType = this.getVectorType( type );
  35077. const vecNum = /vec([2-4])/.exec( vecType );
  35078. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  35079. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  35080. if ( /mat2/.test( type ) === true ) return 4;
  35081. if ( /mat3/.test( type ) === true ) return 9;
  35082. if ( /mat4/.test( type ) === true ) return 16;
  35083. return 0;
  35084. }
  35085. /**
  35086. * Returns the vector type for a given matrix type.
  35087. *
  35088. * @param {string} type - The matrix type.
  35089. * @return {string} The vector type.
  35090. */
  35091. getVectorFromMatrix( type ) {
  35092. return type.replace( 'mat', 'vec' );
  35093. }
  35094. /**
  35095. * For a given type this method changes the component type to the
  35096. * given value. E.g. `vec4` should be changed to the new component type
  35097. * `uint` which results in `uvec4`.
  35098. *
  35099. * @param {string} type - The type.
  35100. * @param {string} newComponentType - The new component type.
  35101. * @return {string} The new type.
  35102. */
  35103. changeComponentType( type, newComponentType ) {
  35104. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  35105. }
  35106. /**
  35107. * Returns the integer type pendant for the given type.
  35108. *
  35109. * @param {string} type - The type.
  35110. * @return {string} The integer type.
  35111. */
  35112. getIntegerType( type ) {
  35113. const componentType = this.getComponentType( type );
  35114. if ( componentType === 'int' || componentType === 'uint' ) return type;
  35115. return this.changeComponentType( type, 'int' );
  35116. }
  35117. /**
  35118. * Adds a stack node to the internal stack.
  35119. *
  35120. * @return {StackNode} The added stack node.
  35121. */
  35122. addStack() {
  35123. this.stack = stack( this.stack );
  35124. const previousStack = getCurrentStack();
  35125. this.stacks.push( previousStack );
  35126. setCurrentStack( this.stack );
  35127. return this.stack;
  35128. }
  35129. /**
  35130. * Removes the last stack node from the internal stack.
  35131. *
  35132. * @return {StackNode} The removed stack node.
  35133. */
  35134. removeStack() {
  35135. const lastStack = this.stack;
  35136. this.stack = lastStack.parent;
  35137. setCurrentStack( this.stacks.pop() );
  35138. return lastStack;
  35139. }
  35140. /**
  35141. * The builder maintains (cached) data for each node during the building process. This method
  35142. * can be used to get these data for a specific shader stage and cache.
  35143. *
  35144. * @param {Node} node - The node to get the data for.
  35145. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35146. * @param {?NodeCache} cache - An optional cache.
  35147. * @return {Object} The node data.
  35148. */
  35149. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  35150. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  35151. let nodeData = cache.getData( node );
  35152. if ( nodeData === undefined ) {
  35153. nodeData = {};
  35154. cache.setData( node, nodeData );
  35155. }
  35156. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  35157. //
  35158. let data = nodeData[ shaderStage ];
  35159. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  35160. const subBuild = this.getClosestSubBuild( subBuilds );
  35161. if ( subBuild ) {
  35162. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  35163. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  35164. data.subBuilds = subBuilds;
  35165. }
  35166. return data;
  35167. }
  35168. /**
  35169. * Returns the properties for the given node and shader stage.
  35170. *
  35171. * Properties are typically used within a build stage to reference a node's
  35172. * child node or nodes manually assigned to the properties in a separate build stage.
  35173. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  35174. * to the current node's properties in the setup stage and building those properties in the generate stage.
  35175. *
  35176. * @param {Node} node - The node to get the properties for.
  35177. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  35178. * @return {Object} The node properties.
  35179. */
  35180. getNodeProperties( node, shaderStage = 'any' ) {
  35181. const nodeData = this.getDataFromNode( node, shaderStage );
  35182. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  35183. }
  35184. /**
  35185. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  35186. *
  35187. * @param {BufferAttributeNode} node - The buffer attribute node.
  35188. * @param {string} type - The node type.
  35189. * @return {NodeAttribute} The node attribute.
  35190. */
  35191. getBufferAttributeFromNode( node, type ) {
  35192. const nodeData = this.getDataFromNode( node );
  35193. let bufferAttribute = nodeData.bufferAttribute;
  35194. if ( bufferAttribute === undefined ) {
  35195. const index = this.uniforms.index ++;
  35196. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  35197. this.bufferAttributes.push( bufferAttribute );
  35198. nodeData.bufferAttribute = bufferAttribute;
  35199. }
  35200. return bufferAttribute;
  35201. }
  35202. /**
  35203. * Returns an instance of {@link StructType} for the given struct name and shader stage
  35204. * or null if not found.
  35205. *
  35206. * @param {string} name - The name of the struct.
  35207. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35208. * @return {?StructType} The struct type or null if not found.
  35209. */
  35210. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  35211. return this.types[ shaderStage ][ name ] || null;
  35212. }
  35213. /**
  35214. * Returns an instance of {@link StructType} for the given output struct node.
  35215. *
  35216. * @param {OutputStructNode} node - The output struct node.
  35217. * @param {Array<Object>} membersLayout - The output struct types.
  35218. * @param {?string} [name=null] - The name of the struct.
  35219. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35220. * @return {StructType} The struct type attribute.
  35221. */
  35222. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  35223. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35224. let structType = nodeData.structType;
  35225. if ( structType === undefined ) {
  35226. const index = this.structs.index ++;
  35227. if ( name === null ) name = 'StructType' + index;
  35228. structType = new StructType( name, membersLayout );
  35229. this.structs[ shaderStage ].push( structType );
  35230. this.types[ shaderStage ][ name ] = node;
  35231. nodeData.structType = structType;
  35232. }
  35233. return structType;
  35234. }
  35235. /**
  35236. * Returns an instance of {@link StructType} for the given output struct node.
  35237. *
  35238. * @param {OutputStructNode} node - The output struct node.
  35239. * @param {Array<Object>} membersLayout - The output struct types.
  35240. * @return {StructType} The struct type attribute.
  35241. */
  35242. getOutputStructTypeFromNode( node, membersLayout ) {
  35243. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  35244. structType.output = true;
  35245. return structType;
  35246. }
  35247. /**
  35248. * Returns an instance of {@link NodeUniform} for the given uniform node.
  35249. *
  35250. * @param {UniformNode} node - The uniform node.
  35251. * @param {string} type - The uniform type.
  35252. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35253. * @param {?string} name - The name of the uniform.
  35254. * @return {NodeUniform} The node uniform.
  35255. */
  35256. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  35257. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35258. let nodeUniform = nodeData.uniform;
  35259. if ( nodeUniform === undefined ) {
  35260. const index = this.uniforms.index ++;
  35261. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  35262. this.uniforms[ shaderStage ].push( nodeUniform );
  35263. this.registerDeclaration( nodeUniform );
  35264. nodeData.uniform = nodeUniform;
  35265. }
  35266. return nodeUniform;
  35267. }
  35268. /**
  35269. * Returns an instance of {@link NodeVar} for the given variable node.
  35270. *
  35271. * @param {VarNode} node - The variable node.
  35272. * @param {?string} name - The variable's name.
  35273. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  35274. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35275. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  35276. *
  35277. * @return {NodeVar} The node variable.
  35278. */
  35279. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  35280. const nodeData = this.getDataFromNode( node, shaderStage );
  35281. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  35282. let nodeVar = nodeData[ subBuildVariable ];
  35283. if ( nodeVar === undefined ) {
  35284. const idNS = readOnly ? '_const' : '_var';
  35285. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  35286. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  35287. if ( name === null ) {
  35288. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  35289. this.vars[ idNS ] ++;
  35290. }
  35291. //
  35292. if ( subBuildVariable !== 'variable' ) {
  35293. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35294. }
  35295. //
  35296. const count = node.getArrayCount( this );
  35297. nodeVar = new NodeVar( name, type, readOnly, count );
  35298. if ( ! readOnly ) {
  35299. vars.push( nodeVar );
  35300. }
  35301. this.registerDeclaration( nodeVar );
  35302. nodeData[ subBuildVariable ] = nodeVar;
  35303. }
  35304. return nodeVar;
  35305. }
  35306. /**
  35307. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  35308. *
  35309. * @param {Node} node - The varying node.
  35310. * @return {boolean} Returns true if deterministic.
  35311. */
  35312. isDeterministic( node ) {
  35313. if ( node.isMathNode ) {
  35314. return this.isDeterministic( node.aNode ) &&
  35315. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  35316. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  35317. } else if ( node.isOperatorNode ) {
  35318. return this.isDeterministic( node.aNode ) &&
  35319. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  35320. } else if ( node.isArrayNode ) {
  35321. if ( node.values !== null ) {
  35322. for ( const n of node.values ) {
  35323. if ( ! this.isDeterministic( n ) ) {
  35324. return false;
  35325. }
  35326. }
  35327. }
  35328. return true;
  35329. } else if ( node.isConstNode ) {
  35330. return true;
  35331. }
  35332. return false;
  35333. }
  35334. /**
  35335. * Returns an instance of {@link NodeVarying} for the given varying node.
  35336. *
  35337. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  35338. * @param {?string} name - The varying's name.
  35339. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  35340. * @param {?string} interpolationType - The interpolation type of the varying.
  35341. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35342. * @return {NodeVar} The node varying.
  35343. */
  35344. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  35345. const nodeData = this.getDataFromNode( node, 'any' );
  35346. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  35347. let nodeVarying = nodeData[ subBuildVarying ];
  35348. if ( nodeVarying === undefined ) {
  35349. const varyings = this.varyings;
  35350. const index = varyings.length;
  35351. if ( name === null ) name = 'nodeVarying' + index;
  35352. //
  35353. if ( subBuildVarying !== 'varying' ) {
  35354. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35355. }
  35356. //
  35357. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  35358. varyings.push( nodeVarying );
  35359. this.registerDeclaration( nodeVarying );
  35360. nodeData[ subBuildVarying ] = nodeVarying;
  35361. }
  35362. return nodeVarying;
  35363. }
  35364. /**
  35365. * Registers a node declaration in the current shader stage.
  35366. *
  35367. * @param {Object} node - The node to be registered.
  35368. */
  35369. registerDeclaration( node ) {
  35370. const shaderStage = this.shaderStage;
  35371. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  35372. const property = this.getPropertyName( node );
  35373. let index = 1;
  35374. let name = property;
  35375. // Automatically renames the property if the name is already in use.
  35376. while ( declarations[ name ] !== undefined ) {
  35377. name = property + '_' + index ++;
  35378. }
  35379. if ( index > 1 ) {
  35380. node.name = name;
  35381. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  35382. }
  35383. declarations[ name ] = node;
  35384. }
  35385. /**
  35386. * Returns an instance of {@link NodeCode} for the given code node.
  35387. *
  35388. * @param {CodeNode} node - The code node.
  35389. * @param {string} type - The node type.
  35390. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35391. * @return {NodeCode} The node code.
  35392. */
  35393. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  35394. const nodeData = this.getDataFromNode( node );
  35395. let nodeCode = nodeData.code;
  35396. if ( nodeCode === undefined ) {
  35397. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  35398. const index = codes.length;
  35399. nodeCode = new NodeCode( 'nodeCode' + index, type );
  35400. codes.push( nodeCode );
  35401. nodeData.code = nodeCode;
  35402. }
  35403. return nodeCode;
  35404. }
  35405. /**
  35406. * Adds a code flow based on the code-block hierarchy.
  35407. * This is used so that code-blocks like If,Else create their variables locally if the Node
  35408. * is only used inside one of these conditionals in the current shader stage.
  35409. *
  35410. * @param {Node} node - The node to add.
  35411. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  35412. */
  35413. addFlowCodeHierarchy( node, nodeBlock ) {
  35414. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  35415. let needsFlowCode = true;
  35416. let nodeBlockHierarchy = nodeBlock;
  35417. while ( nodeBlockHierarchy ) {
  35418. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  35419. needsFlowCode = false;
  35420. break;
  35421. }
  35422. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  35423. }
  35424. if ( needsFlowCode ) {
  35425. for ( const flowCode of flowCodes ) {
  35426. this.addLineFlowCode( flowCode );
  35427. }
  35428. }
  35429. }
  35430. /**
  35431. * Add a inline-code to the current flow code-block.
  35432. *
  35433. * @param {Node} node - The node to add.
  35434. * @param {string} code - The code to add.
  35435. * @param {Node} nodeBlock - Current ConditionalNode
  35436. */
  35437. addLineFlowCodeBlock( node, code, nodeBlock ) {
  35438. const nodeData = this.getDataFromNode( node );
  35439. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  35440. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  35441. flowCodes.push( code );
  35442. codeBlock.set( nodeBlock, true );
  35443. }
  35444. /**
  35445. * Add a inline-code to the current flow.
  35446. *
  35447. * @param {string} code - The code to add.
  35448. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  35449. * @return {NodeBuilder} A reference to this node builder.
  35450. */
  35451. addLineFlowCode( code, node = null ) {
  35452. if ( code === '' ) return this;
  35453. if ( node !== null && this.context.nodeBlock ) {
  35454. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  35455. }
  35456. code = this.tab + code;
  35457. if ( ! /;\s*$/.test( code ) ) {
  35458. code = code + ';\n';
  35459. }
  35460. this.flow.code += code;
  35461. return this;
  35462. }
  35463. /**
  35464. * Adds a code to the current code flow.
  35465. *
  35466. * @param {string} code - Shader code.
  35467. * @return {NodeBuilder} A reference to this node builder.
  35468. */
  35469. addFlowCode( code ) {
  35470. this.flow.code += code;
  35471. return this;
  35472. }
  35473. /**
  35474. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  35475. * Typically used in codes with If,Else.
  35476. *
  35477. * @return {NodeBuilder} A reference to this node builder.
  35478. */
  35479. addFlowTab() {
  35480. this.tab += '\t';
  35481. return this;
  35482. }
  35483. /**
  35484. * Removes a tab.
  35485. *
  35486. * @return {NodeBuilder} A reference to this node builder.
  35487. */
  35488. removeFlowTab() {
  35489. this.tab = this.tab.slice( 0, -1 );
  35490. return this;
  35491. }
  35492. /**
  35493. * Gets the current flow data based on a Node.
  35494. *
  35495. * @param {Node} node - Node that the flow was started.
  35496. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35497. * @return {Object} The flow data.
  35498. */
  35499. getFlowData( node/*, shaderStage*/ ) {
  35500. return this.flowsData.get( node );
  35501. }
  35502. /**
  35503. * Executes the node flow based on a root node to generate the final shader code.
  35504. *
  35505. * @param {Node} node - The node to execute.
  35506. * @return {Object} The code flow.
  35507. */
  35508. flowNode( node ) {
  35509. const output = node.getNodeType( this );
  35510. const flowData = this.flowChildNode( node, output );
  35511. this.flowsData.set( node, flowData );
  35512. return flowData;
  35513. }
  35514. /**
  35515. * Includes a node in the current function node.
  35516. *
  35517. * @param {Node} node - The node to include.
  35518. * @returns {void}
  35519. */
  35520. addInclude( node ) {
  35521. if ( this.currentFunctionNode !== null ) {
  35522. this.currentFunctionNode.includes.push( node );
  35523. }
  35524. }
  35525. /**
  35526. * Returns the native shader operator name for a given generic name.
  35527. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35528. *
  35529. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  35530. * @return {FunctionNode} The build function node.
  35531. */
  35532. buildFunctionNode( shaderNode ) {
  35533. const fn = new FunctionNode();
  35534. const previous = this.currentFunctionNode;
  35535. this.currentFunctionNode = fn;
  35536. fn.code = this.buildFunctionCode( shaderNode );
  35537. this.currentFunctionNode = previous;
  35538. return fn;
  35539. }
  35540. /**
  35541. * Generates a code flow based on a TSL function: Fn().
  35542. *
  35543. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  35544. * @return {Object}
  35545. */
  35546. flowShaderNode( shaderNode ) {
  35547. const layout = shaderNode.layout;
  35548. const inputs = {
  35549. [ Symbol.iterator ]() {
  35550. let index = 0;
  35551. const values = Object.values( this );
  35552. return {
  35553. next: () => ( {
  35554. value: values[ index ],
  35555. done: index ++ >= values.length
  35556. } )
  35557. };
  35558. }
  35559. };
  35560. for ( const input of layout.inputs ) {
  35561. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  35562. }
  35563. //
  35564. shaderNode.layout = null;
  35565. const callNode = shaderNode.call( inputs );
  35566. const flowData = this.flowStagesNode( callNode, layout.type );
  35567. shaderNode.layout = layout;
  35568. return flowData;
  35569. }
  35570. /**
  35571. * Executes the node in a specific build stage.
  35572. *
  35573. * This function can be used to arbitrarily execute the specified build stage
  35574. * outside of the standard build process. For instance, if a node's type depends
  35575. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  35576. * can be used to execute the setup build stage and access its generated nodes
  35577. * before the standard build process begins.
  35578. *
  35579. * @param {Node} node - The node to execute.
  35580. * @param {string} buildStage - The build stage to execute the node in.
  35581. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  35582. * @return {?(Node|string)} The result of the node build.
  35583. */
  35584. flowBuildStage( node, buildStage, output = null ) {
  35585. const previousBuildStage = this.getBuildStage();
  35586. this.setBuildStage( buildStage );
  35587. const result = node.build( this, output );
  35588. this.setBuildStage( previousBuildStage );
  35589. return result;
  35590. }
  35591. /**
  35592. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  35593. *
  35594. * @param {Node} node - The node to execute.
  35595. * @param {?string} output - Expected output type. For example 'vec3'.
  35596. * @return {Object}
  35597. */
  35598. flowStagesNode( node, output = null ) {
  35599. const previousFlow = this.flow;
  35600. const previousVars = this.vars;
  35601. const previousDeclarations = this.declarations;
  35602. const previousCache = this.cache;
  35603. const previousBuildStage = this.buildStage;
  35604. const previousStack = this.stack;
  35605. const flow = {
  35606. code: ''
  35607. };
  35608. this.flow = flow;
  35609. this.vars = {};
  35610. this.declarations = {};
  35611. this.cache = new NodeCache();
  35612. this.stack = stack();
  35613. for ( const buildStage of defaultBuildStages ) {
  35614. this.setBuildStage( buildStage );
  35615. flow.result = node.build( this, output );
  35616. }
  35617. flow.vars = this.getVars( this.shaderStage );
  35618. this.flow = previousFlow;
  35619. this.vars = previousVars;
  35620. this.declarations = previousDeclarations;
  35621. this.cache = previousCache;
  35622. this.stack = previousStack;
  35623. this.setBuildStage( previousBuildStage );
  35624. return flow;
  35625. }
  35626. /**
  35627. * Returns the native shader operator name for a given generic name.
  35628. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35629. *
  35630. * @abstract
  35631. * @param {string} op - The operator name to resolve.
  35632. * @return {?string} The resolved operator name.
  35633. */
  35634. getFunctionOperator( /* op */ ) {
  35635. return null;
  35636. }
  35637. /**
  35638. * Builds the given shader node.
  35639. *
  35640. * @abstract
  35641. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35642. * @return {string} The function code.
  35643. */
  35644. buildFunctionCode( /* shaderNode */ ) {
  35645. warn( 'Abstract function.' );
  35646. }
  35647. /**
  35648. * Generates a code flow based on a child Node.
  35649. *
  35650. * @param {Node} node - The node to execute.
  35651. * @param {?string} output - Expected output type. For example 'vec3'.
  35652. * @return {Object} The code flow.
  35653. */
  35654. flowChildNode( node, output = null ) {
  35655. const previousFlow = this.flow;
  35656. const flow = {
  35657. code: ''
  35658. };
  35659. this.flow = flow;
  35660. flow.result = node.build( this, output );
  35661. this.flow = previousFlow;
  35662. return flow;
  35663. }
  35664. /**
  35665. * Executes a flow of code in a different stage.
  35666. *
  35667. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35668. * return the value in fragment-stage even if it is being executed in an input fragment.
  35669. *
  35670. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35671. * @param {Node} node - The node to execute.
  35672. * @param {?string} output - Expected output type. For example 'vec3'.
  35673. * @param {?string} propertyName - The property name to assign the result.
  35674. * @return {?(Object|Node)} The code flow or node.build() result.
  35675. */
  35676. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35677. const previousTab = this.tab;
  35678. const previousCache = this.cache;
  35679. const previousShaderStage = this.shaderStage;
  35680. const previousContext = this.context;
  35681. this.setShaderStage( shaderStage );
  35682. const context = { ...this.context };
  35683. delete context.nodeBlock;
  35684. this.cache = this.globalCache;
  35685. this.tab = '\t';
  35686. this.context = context;
  35687. let result = null;
  35688. if ( this.buildStage === 'generate' ) {
  35689. const flowData = this.flowChildNode( node, output );
  35690. if ( propertyName !== null ) {
  35691. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  35692. }
  35693. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  35694. result = flowData;
  35695. } else {
  35696. result = node.build( this );
  35697. }
  35698. this.setShaderStage( previousShaderStage );
  35699. this.cache = previousCache;
  35700. this.tab = previousTab;
  35701. this.context = previousContext;
  35702. return result;
  35703. }
  35704. /**
  35705. * Returns an array holding all node attributes of this node builder.
  35706. *
  35707. * @return {Array<NodeAttribute>} The node attributes of this builder.
  35708. */
  35709. getAttributesArray() {
  35710. return this.attributes.concat( this.bufferAttributes );
  35711. }
  35712. /**
  35713. * Returns the attribute definitions as a shader string for the given shader stage.
  35714. *
  35715. * @abstract
  35716. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35717. * @return {string} The attribute code section.
  35718. */
  35719. getAttributes( /*shaderStage*/ ) {
  35720. warn( 'Abstract function.' );
  35721. }
  35722. /**
  35723. * Returns the varying definitions as a shader string for the given shader stage.
  35724. *
  35725. * @abstract
  35726. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35727. * @return {string} The varying code section.
  35728. */
  35729. getVaryings( /*shaderStage*/ ) {
  35730. warn( 'Abstract function.' );
  35731. }
  35732. /**
  35733. * Returns a single variable definition as a shader string for the given variable type and name.
  35734. *
  35735. * @param {string} type - The variable's type.
  35736. * @param {string} name - The variable's name.
  35737. * @param {?number} [count=null] - The array length.
  35738. * @return {string} The shader string.
  35739. */
  35740. getVar( type, name, count = null ) {
  35741. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  35742. }
  35743. /**
  35744. * Returns the variable definitions as a shader string for the given shader stage.
  35745. *
  35746. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35747. * @return {string} The variable code section.
  35748. */
  35749. getVars( shaderStage ) {
  35750. let snippet = '';
  35751. const vars = this.vars[ shaderStage ];
  35752. if ( vars !== undefined ) {
  35753. for ( const variable of vars ) {
  35754. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  35755. }
  35756. }
  35757. return snippet;
  35758. }
  35759. /**
  35760. * Returns the uniform definitions as a shader string for the given shader stage.
  35761. *
  35762. * @abstract
  35763. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35764. * @return {string} The uniform code section.
  35765. */
  35766. getUniforms( /*shaderStage*/ ) {
  35767. warn( 'Abstract function.' );
  35768. }
  35769. /**
  35770. * Returns the native code definitions as a shader string for the given shader stage.
  35771. *
  35772. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35773. * @return {string} The native code section.
  35774. */
  35775. getCodes( shaderStage ) {
  35776. const codes = this.codes[ shaderStage ];
  35777. let code = '';
  35778. if ( codes !== undefined ) {
  35779. for ( const nodeCode of codes ) {
  35780. code += nodeCode.code + '\n';
  35781. }
  35782. }
  35783. return code;
  35784. }
  35785. /**
  35786. * Returns the hash of this node builder.
  35787. *
  35788. * @return {string} The hash.
  35789. */
  35790. getHash() {
  35791. return this.vertexShader + this.fragmentShader + this.computeShader;
  35792. }
  35793. /**
  35794. * Sets the current shader stage.
  35795. *
  35796. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  35797. */
  35798. setShaderStage( shaderStage ) {
  35799. this.shaderStage = shaderStage;
  35800. }
  35801. /**
  35802. * Returns the current shader stage.
  35803. *
  35804. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  35805. */
  35806. getShaderStage() {
  35807. return this.shaderStage;
  35808. }
  35809. /**
  35810. * Sets the current build stage.
  35811. *
  35812. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  35813. */
  35814. setBuildStage( buildStage ) {
  35815. this.buildStage = buildStage;
  35816. }
  35817. /**
  35818. * Returns the current build stage.
  35819. *
  35820. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  35821. */
  35822. getBuildStage() {
  35823. return this.buildStage;
  35824. }
  35825. /**
  35826. * Controls the code build of the shader stages.
  35827. *
  35828. * @abstract
  35829. */
  35830. buildCode() {
  35831. warn( 'Abstract function.' );
  35832. }
  35833. /**
  35834. * Returns the current sub-build layer.
  35835. *
  35836. * @return {SubBuildNode} The current sub-build layers.
  35837. */
  35838. get subBuild() {
  35839. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  35840. }
  35841. /**
  35842. * Adds a sub-build layer to the node builder.
  35843. *
  35844. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  35845. */
  35846. addSubBuild( subBuild ) {
  35847. this.subBuildLayers.push( subBuild );
  35848. }
  35849. /**
  35850. * Removes the last sub-build layer from the node builder.
  35851. *
  35852. * @return {SubBuildNode} The removed sub-build layer.
  35853. */
  35854. removeSubBuild() {
  35855. return this.subBuildLayers.pop();
  35856. }
  35857. /**
  35858. * Returns the closest sub-build layer for the given data.
  35859. *
  35860. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  35861. * @return {?string} The closest sub-build name or null if none found.
  35862. */
  35863. getClosestSubBuild( data ) {
  35864. let subBuilds;
  35865. if ( data && data.isNode ) {
  35866. if ( data.isShaderCallNodeInternal ) {
  35867. subBuilds = data.shaderNode.subBuilds;
  35868. } else if ( data.isStackNode ) {
  35869. subBuilds = [ data.subBuild ];
  35870. } else {
  35871. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  35872. }
  35873. } else if ( data instanceof Set ) {
  35874. subBuilds = [ ...data ];
  35875. } else {
  35876. subBuilds = data;
  35877. }
  35878. if ( ! subBuilds ) return null;
  35879. const subBuildLayers = this.subBuildLayers;
  35880. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  35881. const subBuild = subBuilds[ i ];
  35882. if ( subBuildLayers.includes( subBuild ) ) {
  35883. return subBuild;
  35884. }
  35885. }
  35886. return null;
  35887. }
  35888. /**
  35889. * Returns the output node of a sub-build layer.
  35890. *
  35891. * @param {Node} node - The node to get the output from.
  35892. * @return {string} The output node name.
  35893. */
  35894. getSubBuildOutput( node ) {
  35895. return this.getSubBuildProperty( 'outputNode', node );
  35896. }
  35897. /**
  35898. * Returns the sub-build property name for the given property and node.
  35899. *
  35900. * @param {string} [property=''] - The property name.
  35901. * @param {?Node} [node=null] - The node to get the sub-build from.
  35902. * @return {string} The sub-build property name.
  35903. */
  35904. getSubBuildProperty( property = '', node = null ) {
  35905. let subBuild;
  35906. if ( node !== null ) {
  35907. subBuild = this.getClosestSubBuild( node );
  35908. } else {
  35909. subBuild = this.subBuildFn;
  35910. }
  35911. let result;
  35912. if ( subBuild ) {
  35913. result = property ? ( subBuild + '_' + property ) : subBuild;
  35914. } else {
  35915. result = property;
  35916. }
  35917. return result;
  35918. }
  35919. /**
  35920. * Central build method which controls the build for the given object.
  35921. *
  35922. * @return {NodeBuilder} A reference to this node builder.
  35923. */
  35924. build() {
  35925. const { object, material, renderer } = this;
  35926. if ( material !== null ) {
  35927. let nodeMaterial = renderer.library.fromMaterial( material );
  35928. if ( nodeMaterial === null ) {
  35929. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35930. nodeMaterial = new NodeMaterial();
  35931. }
  35932. nodeMaterial.build( this );
  35933. } else {
  35934. this.addFlow( 'compute', object );
  35935. }
  35936. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35937. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35938. // generate() -> stage 3: generate shader
  35939. for ( const buildStage of defaultBuildStages ) {
  35940. this.setBuildStage( buildStage );
  35941. if ( this.context.vertex && this.context.vertex.isNode ) {
  35942. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35943. }
  35944. for ( const shaderStage of shaderStages ) {
  35945. this.setShaderStage( shaderStage );
  35946. const flowNodes = this.flowNodes[ shaderStage ];
  35947. for ( const node of flowNodes ) {
  35948. if ( buildStage === 'generate' ) {
  35949. this.flowNode( node );
  35950. } else {
  35951. node.build( this );
  35952. }
  35953. }
  35954. }
  35955. }
  35956. this.setBuildStage( null );
  35957. this.setShaderStage( null );
  35958. // stage 4: build code for a specific output
  35959. this.buildCode();
  35960. this.buildUpdateNodes();
  35961. return this;
  35962. }
  35963. /**
  35964. * Returns a uniform representation which is later used for UBO generation and rendering.
  35965. *
  35966. * @param {NodeUniform} uniformNode - The uniform node.
  35967. * @param {string} type - The requested type.
  35968. * @return {Uniform} The uniform.
  35969. */
  35970. getNodeUniform( uniformNode, type ) {
  35971. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35972. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35973. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35974. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35975. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35976. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35977. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35978. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35979. throw new Error( `Uniform "${type}" not declared.` );
  35980. }
  35981. /**
  35982. * Formats the given shader snippet from a given type into another one. E.g.
  35983. * this method might be used to convert a simple float string `"1.0"` into a
  35984. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35985. *
  35986. * @param {string} snippet - The shader snippet.
  35987. * @param {string} fromType - The source type.
  35988. * @param {string} toType - The target type.
  35989. * @return {string} The updated shader string.
  35990. */
  35991. format( snippet, fromType, toType ) {
  35992. fromType = this.getVectorType( fromType );
  35993. toType = this.getVectorType( toType );
  35994. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35995. return snippet;
  35996. }
  35997. const fromTypeLength = this.getTypeLength( fromType );
  35998. const toTypeLength = this.getTypeLength( toType );
  35999. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36000. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  36001. }
  36002. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36003. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  36004. }
  36005. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36006. // @TODO: ignore for now
  36007. return snippet;
  36008. }
  36009. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36010. // @TODO: ignore for now
  36011. return snippet;
  36012. }
  36013. if ( fromTypeLength === toTypeLength ) {
  36014. return `${ this.getType( toType ) }( ${ snippet } )`;
  36015. }
  36016. if ( fromTypeLength > toTypeLength ) {
  36017. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  36018. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36019. }
  36020. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36021. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36022. }
  36023. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36024. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36025. }
  36026. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36027. // convert a number value to vector type, e.g:
  36028. // vec3( 1u ) -> vec3( float( 1u ) )
  36029. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36030. }
  36031. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36032. }
  36033. /**
  36034. * Returns a signature with the engine's current revision.
  36035. *
  36036. * @return {string} The signature.
  36037. */
  36038. getSignature() {
  36039. return `// Three.js r${ REVISION } - Node System\n`;
  36040. }
  36041. }
  36042. /**
  36043. * Management class for updating nodes. The module tracks metrics like
  36044. * the elapsed time, delta time, the render and frame ID to correctly
  36045. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  36046. * and {@link Node#updateAfter} depending on the node's configuration.
  36047. */
  36048. class NodeFrame {
  36049. /**
  36050. * Constructs a new node fame.
  36051. */
  36052. constructor() {
  36053. /**
  36054. * The elapsed time in seconds.
  36055. *
  36056. * @type {number}
  36057. * @default 0
  36058. */
  36059. this.time = 0;
  36060. /**
  36061. * The delta time in seconds.
  36062. *
  36063. * @type {number}
  36064. * @default 0
  36065. */
  36066. this.deltaTime = 0;
  36067. /**
  36068. * The frame ID.
  36069. *
  36070. * @type {number}
  36071. * @default 0
  36072. */
  36073. this.frameId = 0;
  36074. /**
  36075. * The render ID.
  36076. *
  36077. * @type {number}
  36078. * @default 0
  36079. */
  36080. this.renderId = 0;
  36081. /**
  36082. * Used to control the {@link Node#update} call.
  36083. *
  36084. * @type {WeakMap<Node, Object>}
  36085. */
  36086. this.updateMap = new WeakMap();
  36087. /**
  36088. * Used to control the {@link Node#updateBefore} call.
  36089. *
  36090. * @type {WeakMap<Node, Object>}
  36091. */
  36092. this.updateBeforeMap = new WeakMap();
  36093. /**
  36094. * Used to control the {@link Node#updateAfter} call.
  36095. *
  36096. * @type {WeakMap<Node, Object>}
  36097. */
  36098. this.updateAfterMap = new WeakMap();
  36099. /**
  36100. * A reference to the current renderer.
  36101. *
  36102. * @type {?Renderer}
  36103. * @default null
  36104. */
  36105. this.renderer = null;
  36106. /**
  36107. * A reference to the current material.
  36108. *
  36109. * @type {?Material}
  36110. * @default null
  36111. */
  36112. this.material = null;
  36113. /**
  36114. * A reference to the current camera.
  36115. *
  36116. * @type {?Camera}
  36117. * @default null
  36118. */
  36119. this.camera = null;
  36120. /**
  36121. * A reference to the current 3D object.
  36122. *
  36123. * @type {?Object3D}
  36124. * @default null
  36125. */
  36126. this.object = null;
  36127. /**
  36128. * A reference to the current scene.
  36129. *
  36130. * @type {?Scene}
  36131. * @default null
  36132. */
  36133. this.scene = null;
  36134. }
  36135. /**
  36136. * Returns a dictionary for a given node and update map which
  36137. * is used to correctly call node update methods per frame or render.
  36138. *
  36139. * @private
  36140. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  36141. * @param {Node} nodeRef - The reference to the current node.
  36142. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  36143. */
  36144. _getMaps( referenceMap, nodeRef ) {
  36145. let maps = referenceMap.get( nodeRef );
  36146. if ( maps === undefined ) {
  36147. maps = {
  36148. renderId: 0,
  36149. frameId: 0,
  36150. };
  36151. referenceMap.set( nodeRef, maps );
  36152. }
  36153. return maps;
  36154. }
  36155. /**
  36156. * This method executes the {@link Node#updateBefore} for the given node.
  36157. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  36158. * is only executed once per frame, render or object depending on the update
  36159. * type.
  36160. *
  36161. * @param {Node} node - The node that should be updated.
  36162. */
  36163. updateBeforeNode( node ) {
  36164. const updateType = node.getUpdateBeforeType();
  36165. const reference = node.updateReference( this );
  36166. if ( updateType === NodeUpdateType.FRAME ) {
  36167. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36168. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  36169. if ( node.updateBefore( this ) !== false ) {
  36170. nodeUpdateBeforeMap.frameId = this.frameId;
  36171. }
  36172. }
  36173. } else if ( updateType === NodeUpdateType.RENDER ) {
  36174. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36175. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  36176. if ( node.updateBefore( this ) !== false ) {
  36177. nodeUpdateBeforeMap.renderId = this.renderId;
  36178. }
  36179. }
  36180. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36181. node.updateBefore( this );
  36182. }
  36183. }
  36184. /**
  36185. * This method executes the {@link Node#updateAfter} for the given node.
  36186. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  36187. * is only executed once per frame, render or object depending on the update
  36188. * type.
  36189. *
  36190. * @param {Node} node - The node that should be updated.
  36191. */
  36192. updateAfterNode( node ) {
  36193. const updateType = node.getUpdateAfterType();
  36194. const reference = node.updateReference( this );
  36195. if ( updateType === NodeUpdateType.FRAME ) {
  36196. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36197. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  36198. if ( node.updateAfter( this ) !== false ) {
  36199. nodeUpdateAfterMap.frameId = this.frameId;
  36200. }
  36201. }
  36202. } else if ( updateType === NodeUpdateType.RENDER ) {
  36203. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36204. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  36205. if ( node.updateAfter( this ) !== false ) {
  36206. nodeUpdateAfterMap.renderId = this.renderId;
  36207. }
  36208. }
  36209. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36210. node.updateAfter( this );
  36211. }
  36212. }
  36213. /**
  36214. * This method executes the {@link Node#update} for the given node.
  36215. * It makes sure {@link Node#updateType} is honored meaning the update
  36216. * is only executed once per frame, render or object depending on the update
  36217. * type.
  36218. *
  36219. * @param {Node} node - The node that should be updated.
  36220. */
  36221. updateNode( node ) {
  36222. const updateType = node.getUpdateType();
  36223. const reference = node.updateReference( this );
  36224. if ( updateType === NodeUpdateType.FRAME ) {
  36225. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36226. if ( nodeUpdateMap.frameId !== this.frameId ) {
  36227. if ( node.update( this ) !== false ) {
  36228. nodeUpdateMap.frameId = this.frameId;
  36229. }
  36230. }
  36231. } else if ( updateType === NodeUpdateType.RENDER ) {
  36232. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36233. if ( nodeUpdateMap.renderId !== this.renderId ) {
  36234. if ( node.update( this ) !== false ) {
  36235. nodeUpdateMap.renderId = this.renderId;
  36236. }
  36237. }
  36238. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36239. node.update( this );
  36240. }
  36241. }
  36242. /**
  36243. * Updates the internal state of the node frame. This method is
  36244. * called by the renderer in its internal animation loop.
  36245. */
  36246. update() {
  36247. this.frameId ++;
  36248. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36249. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36250. this.lastTime = performance.now();
  36251. this.time += this.deltaTime;
  36252. }
  36253. }
  36254. /**
  36255. * Describes the input of a {@link NodeFunction}.
  36256. */
  36257. class NodeFunctionInput {
  36258. /**
  36259. * Constructs a new node function input.
  36260. *
  36261. * @param {string} type - The input type.
  36262. * @param {string} name - The input name.
  36263. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  36264. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  36265. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  36266. */
  36267. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36268. /**
  36269. * The input type.
  36270. *
  36271. * @type {string}
  36272. */
  36273. this.type = type;
  36274. /**
  36275. * The input name.
  36276. *
  36277. * @type {string}
  36278. */
  36279. this.name = name;
  36280. /**
  36281. * If the input is an Array, count will be the length.
  36282. *
  36283. * @type {?number}
  36284. * @default null
  36285. */
  36286. this.count = count;
  36287. /**
  36288. *The parameter qualifier (only relevant for GLSL).
  36289. *
  36290. * @type {('in'|'out'|'inout')}
  36291. * @default ''
  36292. */
  36293. this.qualifier = qualifier;
  36294. /**
  36295. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  36296. *
  36297. * @type {boolean}
  36298. * @default false
  36299. */
  36300. this.isConst = isConst;
  36301. }
  36302. }
  36303. NodeFunctionInput.isNodeFunctionInput = true;
  36304. /**
  36305. * Module for representing directional lights as nodes.
  36306. *
  36307. * @augments AnalyticLightNode
  36308. */
  36309. class DirectionalLightNode extends AnalyticLightNode {
  36310. static get type() {
  36311. return 'DirectionalLightNode';
  36312. }
  36313. /**
  36314. * Constructs a new directional light node.
  36315. *
  36316. * @param {?DirectionalLight} [light=null] - The directional light source.
  36317. */
  36318. constructor( light = null ) {
  36319. super( light );
  36320. }
  36321. setupDirect() {
  36322. const lightColor = this.colorNode;
  36323. const lightDirection = lightTargetDirection( this.light );
  36324. return { lightDirection, lightColor };
  36325. }
  36326. }
  36327. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36328. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36329. let _ltcLib = null;
  36330. /**
  36331. * Module for representing rect area lights as nodes.
  36332. *
  36333. * @augments AnalyticLightNode
  36334. */
  36335. class RectAreaLightNode extends AnalyticLightNode {
  36336. static get type() {
  36337. return 'RectAreaLightNode';
  36338. }
  36339. /**
  36340. * Constructs a new rect area light node.
  36341. *
  36342. * @param {?RectAreaLight} [light=null] - The rect area light source.
  36343. */
  36344. constructor( light = null ) {
  36345. super( light );
  36346. /**
  36347. * Uniform node representing the half height of the are light.
  36348. *
  36349. * @type {UniformNode<vec3>}
  36350. */
  36351. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36352. /**
  36353. * Uniform node representing the half width of the are light.
  36354. *
  36355. * @type {UniformNode<vec3>}
  36356. */
  36357. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36358. /**
  36359. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  36360. * relies on `viewMatrix` which might vary per render call.
  36361. *
  36362. * @type {string}
  36363. * @default 'render'
  36364. */
  36365. this.updateType = NodeUpdateType.RENDER;
  36366. }
  36367. /**
  36368. * Overwritten to updated rect area light specific uniforms.
  36369. *
  36370. * @param {NodeFrame} frame - A reference to the current node frame.
  36371. */
  36372. update( frame ) {
  36373. super.update( frame );
  36374. const { light } = this;
  36375. const viewMatrix = frame.camera.matrixWorldInverse;
  36376. _matrix42.identity();
  36377. _matrix41.copy( light.matrixWorld );
  36378. _matrix41.premultiply( viewMatrix );
  36379. _matrix42.extractRotation( _matrix41 );
  36380. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36381. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36382. this.halfWidth.value.applyMatrix4( _matrix42 );
  36383. this.halfHeight.value.applyMatrix4( _matrix42 );
  36384. }
  36385. setupDirectRectArea( builder ) {
  36386. let ltc_1, ltc_2;
  36387. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36388. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  36389. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  36390. } else {
  36391. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  36392. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  36393. }
  36394. const { colorNode, light } = this;
  36395. const lightPosition = lightViewPosition( light );
  36396. return {
  36397. lightColor: colorNode,
  36398. lightPosition,
  36399. halfWidth: this.halfWidth,
  36400. halfHeight: this.halfHeight,
  36401. ltc_1,
  36402. ltc_2
  36403. };
  36404. }
  36405. /**
  36406. * Used to configure the internal BRDF approximation texture data.
  36407. *
  36408. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  36409. */
  36410. static setLTC( ltc ) {
  36411. _ltcLib = ltc;
  36412. }
  36413. }
  36414. /**
  36415. * Module for representing spot lights as nodes.
  36416. *
  36417. * @augments AnalyticLightNode
  36418. */
  36419. class SpotLightNode extends AnalyticLightNode {
  36420. static get type() {
  36421. return 'SpotLightNode';
  36422. }
  36423. /**
  36424. * Constructs a new spot light node.
  36425. *
  36426. * @param {?SpotLight} [light=null] - The spot light source.
  36427. */
  36428. constructor( light = null ) {
  36429. super( light );
  36430. /**
  36431. * Uniform node representing the cone cosine.
  36432. *
  36433. * @type {UniformNode<float>}
  36434. */
  36435. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36436. /**
  36437. * Uniform node representing the penumbra cosine.
  36438. *
  36439. * @type {UniformNode<float>}
  36440. */
  36441. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36442. /**
  36443. * Uniform node representing the cutoff distance.
  36444. *
  36445. * @type {UniformNode<float>}
  36446. */
  36447. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36448. /**
  36449. * Uniform node representing the decay exponent.
  36450. *
  36451. * @type {UniformNode<float>}
  36452. */
  36453. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36454. /**
  36455. * Uniform node representing the light color.
  36456. *
  36457. * @type {UniformNode<Color>}
  36458. */
  36459. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  36460. }
  36461. /**
  36462. * Overwritten to updated spot light specific uniforms.
  36463. *
  36464. * @param {NodeFrame} frame - A reference to the current node frame.
  36465. */
  36466. update( frame ) {
  36467. super.update( frame );
  36468. const { light } = this;
  36469. this.coneCosNode.value = Math.cos( light.angle );
  36470. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36471. this.cutoffDistanceNode.value = light.distance;
  36472. this.decayExponentNode.value = light.decay;
  36473. }
  36474. /**
  36475. * Computes the spot attenuation for the given angle.
  36476. *
  36477. * @param {NodeBuilder} builder - The node builder.
  36478. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36479. * @return {Node<float>} The spot attenuation.
  36480. */
  36481. getSpotAttenuation( builder, angleCosine ) {
  36482. const { coneCosNode, penumbraCosNode } = this;
  36483. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36484. }
  36485. getLightCoord( builder ) {
  36486. const properties = builder.getNodeProperties( this );
  36487. let projectionUV = properties.projectionUV;
  36488. if ( projectionUV === undefined ) {
  36489. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  36490. properties.projectionUV = projectionUV;
  36491. }
  36492. return projectionUV;
  36493. }
  36494. setupDirect( builder ) {
  36495. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36496. const lightVector = this.getLightVector( builder );
  36497. const lightDirection = lightVector.normalize();
  36498. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36499. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  36500. const lightDistance = lightVector.length();
  36501. const lightAttenuation = getDistanceAttenuation( {
  36502. lightDistance,
  36503. cutoffDistance: cutoffDistanceNode,
  36504. decayExponent: decayExponentNode
  36505. } );
  36506. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36507. let projected, lightCoord;
  36508. if ( light.colorNode ) {
  36509. lightCoord = this.getLightCoord( builder );
  36510. projected = light.colorNode( lightCoord );
  36511. } else if ( light.map ) {
  36512. lightCoord = this.getLightCoord( builder );
  36513. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  36514. }
  36515. if ( projected ) {
  36516. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  36517. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  36518. }
  36519. return { lightColor, lightDirection };
  36520. }
  36521. }
  36522. /**
  36523. * An IES version of the default spot light node.
  36524. *
  36525. * @augments SpotLightNode
  36526. */
  36527. class IESSpotLightNode extends SpotLightNode {
  36528. static get type() {
  36529. return 'IESSpotLightNode';
  36530. }
  36531. /**
  36532. * Overwrites the default implementation to compute an IES conform spot attenuation.
  36533. *
  36534. * @param {NodeBuilder} builder - The node builder.
  36535. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36536. * @return {Node<float>} The spot attenuation.
  36537. */
  36538. getSpotAttenuation( builder, angleCosine ) {
  36539. const iesMap = this.light.iesMap;
  36540. let spotAttenuation = null;
  36541. if ( iesMap && iesMap.isTexture === true ) {
  36542. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36543. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36544. } else {
  36545. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36546. }
  36547. return spotAttenuation;
  36548. }
  36549. }
  36550. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  36551. const d = p.abs().sub( b );
  36552. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  36553. } );
  36554. /**
  36555. * An implementation of a projector light node.
  36556. *
  36557. * @augments SpotLightNode
  36558. */
  36559. class ProjectorLightNode extends SpotLightNode {
  36560. static get type() {
  36561. return 'ProjectorLightNode';
  36562. }
  36563. update( frame ) {
  36564. super.update( frame );
  36565. const light = this.light;
  36566. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  36567. if ( light.aspect === null ) {
  36568. let aspect = 1;
  36569. if ( light.map !== null ) {
  36570. aspect = light.map.width / light.map.height;
  36571. }
  36572. light.shadow.aspect = aspect;
  36573. } else {
  36574. light.shadow.aspect = light.aspect;
  36575. }
  36576. }
  36577. /**
  36578. * Overwrites the default implementation to compute projection attenuation.
  36579. *
  36580. * @param {NodeBuilder} builder - The node builder.
  36581. * @return {Node<float>} The spot attenuation.
  36582. */
  36583. getSpotAttenuation( builder ) {
  36584. const attenuation = float( 0 );
  36585. const penumbraCos = this.penumbraCosNode;
  36586. // compute the fragment's position in the light's clip space
  36587. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  36588. // the sign of w determines whether the current fragment is in front or behind the light.
  36589. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  36590. If( spotLightCoord.w.greaterThan( 0 ), () => {
  36591. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  36592. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  36593. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36594. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36595. } );
  36596. return attenuation;
  36597. }
  36598. }
  36599. /**
  36600. * Module for representing ambient lights as nodes.
  36601. *
  36602. * @augments AnalyticLightNode
  36603. */
  36604. class AmbientLightNode extends AnalyticLightNode {
  36605. static get type() {
  36606. return 'AmbientLightNode';
  36607. }
  36608. /**
  36609. * Constructs a new ambient light node.
  36610. *
  36611. * @param {?AmbientLight} [light=null] - The ambient light source.
  36612. */
  36613. constructor( light = null ) {
  36614. super( light );
  36615. }
  36616. setup( { context } ) {
  36617. context.irradiance.addAssign( this.colorNode );
  36618. }
  36619. }
  36620. /**
  36621. * Module for representing hemisphere lights as nodes.
  36622. *
  36623. * @augments AnalyticLightNode
  36624. */
  36625. class HemisphereLightNode extends AnalyticLightNode {
  36626. static get type() {
  36627. return 'HemisphereLightNode';
  36628. }
  36629. /**
  36630. * Constructs a new hemisphere light node.
  36631. *
  36632. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36633. */
  36634. constructor( light = null ) {
  36635. super( light );
  36636. /**
  36637. * Uniform node representing the light's position.
  36638. *
  36639. * @type {UniformNode<vec3>}
  36640. */
  36641. this.lightPositionNode = lightPosition( light );
  36642. /**
  36643. * A node representing the light's direction.
  36644. *
  36645. * @type {Node<vec3>}
  36646. */
  36647. this.lightDirectionNode = this.lightPositionNode.normalize();
  36648. /**
  36649. * Uniform node representing the light's ground color.
  36650. *
  36651. * @type {UniformNode<vec3>}
  36652. */
  36653. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36654. }
  36655. /**
  36656. * Overwritten to updated hemisphere light specific uniforms.
  36657. *
  36658. * @param {NodeFrame} frame - A reference to the current node frame.
  36659. */
  36660. update( frame ) {
  36661. const { light } = this;
  36662. super.update( frame );
  36663. this.lightPositionNode.object3d = light;
  36664. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36665. }
  36666. setup( builder ) {
  36667. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36668. const dotNL = normalWorld.dot( lightDirectionNode );
  36669. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36670. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36671. builder.context.irradiance.addAssign( irradiance );
  36672. }
  36673. }
  36674. /**
  36675. * Module for representing light probes as nodes.
  36676. *
  36677. * @augments AnalyticLightNode
  36678. */
  36679. class LightProbeNode extends AnalyticLightNode {
  36680. static get type() {
  36681. return 'LightProbeNode';
  36682. }
  36683. /**
  36684. * Constructs a new light probe node.
  36685. *
  36686. * @param {?LightProbe} [light=null] - The light probe.
  36687. */
  36688. constructor( light = null ) {
  36689. super( light );
  36690. const array = [];
  36691. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36692. /**
  36693. * Light probe represented as a uniform of spherical harmonics.
  36694. *
  36695. * @type {UniformArrayNode}
  36696. */
  36697. this.lightProbe = uniformArray( array );
  36698. }
  36699. /**
  36700. * Overwritten to updated light probe specific uniforms.
  36701. *
  36702. * @param {NodeFrame} frame - A reference to the current node frame.
  36703. */
  36704. update( frame ) {
  36705. const { light } = this;
  36706. super.update( frame );
  36707. //
  36708. for ( let i = 0; i < 9; i ++ ) {
  36709. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36710. }
  36711. }
  36712. setup( builder ) {
  36713. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36714. builder.context.irradiance.addAssign( irradiance );
  36715. }
  36716. }
  36717. /**
  36718. * Base class for node parsers. A derived parser must be implemented
  36719. * for each supported native shader language.
  36720. */
  36721. class NodeParser {
  36722. /**
  36723. * The method parses the given native code an returns a node function.
  36724. *
  36725. * @abstract
  36726. * @param {string} source - The native shader code.
  36727. * @return {NodeFunction} A node function.
  36728. */
  36729. parseFunction( /*source*/ ) {
  36730. warn( 'Abstract function.' );
  36731. }
  36732. }
  36733. /**
  36734. * Base class for node functions. A derived module must be implemented
  36735. * for each supported native shader language. Similar to other `Node*` modules,
  36736. * this class is only relevant during the building process and not used
  36737. * in user-level code.
  36738. */
  36739. class NodeFunction {
  36740. /**
  36741. * Constructs a new node function.
  36742. *
  36743. * @param {string} type - The node type. This type is the return type of the node function.
  36744. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  36745. * @param {string} [name=''] - The function's name.
  36746. * @param {string} [precision=''] - The precision qualifier.
  36747. */
  36748. constructor( type, inputs, name = '', precision = '' ) {
  36749. /**
  36750. * The node type. This type is the return type of the node function.
  36751. *
  36752. * @type {string}
  36753. */
  36754. this.type = type;
  36755. /**
  36756. * The function's inputs.
  36757. *
  36758. * @type {Array<NodeFunctionInput>}
  36759. */
  36760. this.inputs = inputs;
  36761. /**
  36762. * The name of the uniform.
  36763. *
  36764. * @type {string}
  36765. * @default ''
  36766. */
  36767. this.name = name;
  36768. /**
  36769. * The precision qualifier.
  36770. *
  36771. * @type {string}
  36772. * @default ''
  36773. */
  36774. this.precision = precision;
  36775. }
  36776. /**
  36777. * This method returns the native code of the node function.
  36778. *
  36779. * @abstract
  36780. * @param {string} name - The function's name.
  36781. * @return {string} A shader code.
  36782. */
  36783. getCode( /*name = this.name*/ ) {
  36784. warn( 'Abstract function.' );
  36785. }
  36786. }
  36787. NodeFunction.isNodeFunction = true;
  36788. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36789. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36790. const pragmaMain = '#pragma main';
  36791. const parse$1 = ( source ) => {
  36792. source = source.trim();
  36793. const pragmaMainIndex = source.indexOf( pragmaMain );
  36794. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36795. const declaration = mainCode.match( declarationRegexp$1 );
  36796. if ( declaration !== null && declaration.length === 5 ) {
  36797. // tokenizer
  36798. const inputsCode = declaration[ 4 ];
  36799. const propsMatches = [];
  36800. let nameMatch = null;
  36801. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36802. propsMatches.push( nameMatch );
  36803. }
  36804. // parser
  36805. const inputs = [];
  36806. let i = 0;
  36807. while ( i < propsMatches.length ) {
  36808. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36809. if ( isConst === true ) {
  36810. i ++;
  36811. }
  36812. let qualifier = propsMatches[ i ][ 0 ];
  36813. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36814. i ++;
  36815. } else {
  36816. qualifier = '';
  36817. }
  36818. const type = propsMatches[ i ++ ][ 0 ];
  36819. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36820. if ( Number.isNaN( count ) === false ) i ++;
  36821. else count = null;
  36822. const name = propsMatches[ i ++ ][ 0 ];
  36823. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36824. }
  36825. //
  36826. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36827. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36828. const type = declaration[ 2 ];
  36829. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36830. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  36831. return {
  36832. type,
  36833. inputs,
  36834. name,
  36835. precision,
  36836. inputsCode,
  36837. blockCode,
  36838. headerCode
  36839. };
  36840. } else {
  36841. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36842. }
  36843. };
  36844. /**
  36845. * This class represents a GLSL node function.
  36846. *
  36847. * @augments NodeFunction
  36848. */
  36849. class GLSLNodeFunction extends NodeFunction {
  36850. /**
  36851. * Constructs a new GLSL node function.
  36852. *
  36853. * @param {string} source - The GLSL source.
  36854. */
  36855. constructor( source ) {
  36856. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36857. super( type, inputs, name, precision );
  36858. this.inputsCode = inputsCode;
  36859. this.blockCode = blockCode;
  36860. this.headerCode = headerCode;
  36861. }
  36862. /**
  36863. * This method returns the GLSL code of the node function.
  36864. *
  36865. * @param {string} [name=this.name] - The function's name.
  36866. * @return {string} The shader code.
  36867. */
  36868. getCode( name = this.name ) {
  36869. let code;
  36870. const blockCode = this.blockCode;
  36871. if ( blockCode !== '' ) {
  36872. const { type, inputsCode, headerCode, precision } = this;
  36873. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36874. if ( precision !== '' ) {
  36875. declarationCode = `${ precision } ${ declarationCode }`;
  36876. }
  36877. code = headerCode + declarationCode + blockCode;
  36878. } else {
  36879. // interface function
  36880. code = '';
  36881. }
  36882. return code;
  36883. }
  36884. }
  36885. /**
  36886. * A GLSL node parser.
  36887. *
  36888. * @augments NodeParser
  36889. */
  36890. class GLSLNodeParser extends NodeParser {
  36891. /**
  36892. * The method parses the given GLSL code an returns a node function.
  36893. *
  36894. * @param {string} source - The GLSL code.
  36895. * @return {GLSLNodeFunction} A node function.
  36896. */
  36897. parseFunction( source ) {
  36898. return new GLSLNodeFunction( source );
  36899. }
  36900. }
  36901. const _outputNodeMap = new WeakMap();
  36902. const _chainKeys$2 = [];
  36903. const _cacheKeyValues = [];
  36904. /**
  36905. * This renderer module manages node-related objects and is the
  36906. * primary interface between the renderer and the node system.
  36907. *
  36908. * @private
  36909. * @augments DataMap
  36910. */
  36911. class Nodes extends DataMap {
  36912. /**
  36913. * Constructs a new nodes management component.
  36914. *
  36915. * @param {Renderer} renderer - The renderer.
  36916. * @param {Backend} backend - The renderer's backend.
  36917. */
  36918. constructor( renderer, backend ) {
  36919. super();
  36920. /**
  36921. * The renderer.
  36922. *
  36923. * @type {Renderer}
  36924. */
  36925. this.renderer = renderer;
  36926. /**
  36927. * The renderer's backend.
  36928. *
  36929. * @type {Backend}
  36930. */
  36931. this.backend = backend;
  36932. /**
  36933. * The node frame.
  36934. *
  36935. * @type {Renderer}
  36936. */
  36937. this.nodeFrame = new NodeFrame();
  36938. /**
  36939. * A cache for managing node builder states.
  36940. *
  36941. * @type {Map<number,NodeBuilderState>}
  36942. */
  36943. this.nodeBuilderCache = new Map();
  36944. /**
  36945. * A cache for managing data cache key data.
  36946. *
  36947. * @type {ChainMap}
  36948. */
  36949. this.callHashCache = new ChainMap();
  36950. /**
  36951. * A cache for managing node uniforms group data.
  36952. *
  36953. * @type {ChainMap}
  36954. */
  36955. this.groupsData = new ChainMap();
  36956. /**
  36957. * A cache for managing node objects of
  36958. * scene properties like fog or environments.
  36959. *
  36960. * @type {Object<string,WeakMap>}
  36961. */
  36962. this.cacheLib = {};
  36963. }
  36964. /**
  36965. * Returns `true` if the given node uniforms group must be updated or not.
  36966. *
  36967. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36968. * @return {boolean} Whether the node uniforms group requires an update or not.
  36969. */
  36970. updateGroup( nodeUniformsGroup ) {
  36971. const groupNode = nodeUniformsGroup.groupNode;
  36972. const name = groupNode.name;
  36973. // objectGroup is always updated
  36974. if ( name === objectGroup.name ) return true;
  36975. // renderGroup is updated once per render/compute call
  36976. if ( name === renderGroup.name ) {
  36977. const uniformsGroupData = this.get( nodeUniformsGroup );
  36978. const renderId = this.nodeFrame.renderId;
  36979. if ( uniformsGroupData.renderId !== renderId ) {
  36980. uniformsGroupData.renderId = renderId;
  36981. return true;
  36982. }
  36983. return false;
  36984. }
  36985. // frameGroup is updated once per frame
  36986. if ( name === frameGroup.name ) {
  36987. const uniformsGroupData = this.get( nodeUniformsGroup );
  36988. const frameId = this.nodeFrame.frameId;
  36989. if ( uniformsGroupData.frameId !== frameId ) {
  36990. uniformsGroupData.frameId = frameId;
  36991. return true;
  36992. }
  36993. return false;
  36994. }
  36995. // other groups are updated just when groupNode.needsUpdate is true
  36996. _chainKeys$2[ 0 ] = groupNode;
  36997. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  36998. let groupData = this.groupsData.get( _chainKeys$2 );
  36999. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  37000. _chainKeys$2.length = 0;
  37001. if ( groupData.version !== groupNode.version ) {
  37002. groupData.version = groupNode.version;
  37003. return true;
  37004. }
  37005. return false;
  37006. }
  37007. /**
  37008. * Returns the cache key for the given render object.
  37009. *
  37010. * @param {RenderObject} renderObject - The render object.
  37011. * @return {number} The cache key.
  37012. */
  37013. getForRenderCacheKey( renderObject ) {
  37014. return renderObject.initialCacheKey;
  37015. }
  37016. /**
  37017. * Returns a node builder state for the given render object.
  37018. *
  37019. * @param {RenderObject} renderObject - The render object.
  37020. * @return {NodeBuilderState} The node builder state.
  37021. */
  37022. getForRender( renderObject ) {
  37023. const renderObjectData = this.get( renderObject );
  37024. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37025. if ( nodeBuilderState === undefined ) {
  37026. const { nodeBuilderCache } = this;
  37027. const cacheKey = this.getForRenderCacheKey( renderObject );
  37028. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37029. if ( nodeBuilderState === undefined ) {
  37030. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37031. nodeBuilder.scene = renderObject.scene;
  37032. nodeBuilder.material = renderObject.material;
  37033. nodeBuilder.camera = renderObject.camera;
  37034. nodeBuilder.context.material = renderObject.material;
  37035. nodeBuilder.lightsNode = renderObject.lightsNode;
  37036. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37037. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37038. nodeBuilder.clippingContext = renderObject.clippingContext;
  37039. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  37040. nodeBuilder.enableMultiview();
  37041. }
  37042. nodeBuilder.build();
  37043. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37044. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37045. }
  37046. nodeBuilderState.usedTimes ++;
  37047. renderObjectData.nodeBuilderState = nodeBuilderState;
  37048. }
  37049. return nodeBuilderState;
  37050. }
  37051. /**
  37052. * Deletes the given object from the internal data map
  37053. *
  37054. * @param {any} object - The object to delete.
  37055. * @return {?Object} The deleted dictionary.
  37056. */
  37057. delete( object ) {
  37058. if ( object.isRenderObject ) {
  37059. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37060. nodeBuilderState.usedTimes --;
  37061. if ( nodeBuilderState.usedTimes === 0 ) {
  37062. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37063. }
  37064. }
  37065. return super.delete( object );
  37066. }
  37067. /**
  37068. * Returns a node builder state for the given compute node.
  37069. *
  37070. * @param {Node} computeNode - The compute node.
  37071. * @return {NodeBuilderState} The node builder state.
  37072. */
  37073. getForCompute( computeNode ) {
  37074. const computeData = this.get( computeNode );
  37075. let nodeBuilderState = computeData.nodeBuilderState;
  37076. if ( nodeBuilderState === undefined ) {
  37077. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37078. nodeBuilder.build();
  37079. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37080. computeData.nodeBuilderState = nodeBuilderState;
  37081. }
  37082. return nodeBuilderState;
  37083. }
  37084. /**
  37085. * Creates a node builder state for the given node builder.
  37086. *
  37087. * @private
  37088. * @param {NodeBuilder} nodeBuilder - The node builder.
  37089. * @return {NodeBuilderState} The node builder state.
  37090. */
  37091. _createNodeBuilderState( nodeBuilder ) {
  37092. return new NodeBuilderState(
  37093. nodeBuilder.vertexShader,
  37094. nodeBuilder.fragmentShader,
  37095. nodeBuilder.computeShader,
  37096. nodeBuilder.getAttributesArray(),
  37097. nodeBuilder.getBindings(),
  37098. nodeBuilder.updateNodes,
  37099. nodeBuilder.updateBeforeNodes,
  37100. nodeBuilder.updateAfterNodes,
  37101. nodeBuilder.observer,
  37102. nodeBuilder.transforms
  37103. );
  37104. }
  37105. /**
  37106. * Returns an environment node for the current configured
  37107. * scene environment.
  37108. *
  37109. * @param {Scene} scene - The scene.
  37110. * @return {Node} A node representing the current scene environment.
  37111. */
  37112. getEnvironmentNode( scene ) {
  37113. this.updateEnvironment( scene );
  37114. let environmentNode = null;
  37115. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  37116. environmentNode = scene.environmentNode;
  37117. } else {
  37118. const sceneData = this.get( scene );
  37119. if ( sceneData.environmentNode ) {
  37120. environmentNode = sceneData.environmentNode;
  37121. }
  37122. }
  37123. return environmentNode;
  37124. }
  37125. /**
  37126. * Returns a background node for the current configured
  37127. * scene background.
  37128. *
  37129. * @param {Scene} scene - The scene.
  37130. * @return {Node} A node representing the current scene background.
  37131. */
  37132. getBackgroundNode( scene ) {
  37133. this.updateBackground( scene );
  37134. let backgroundNode = null;
  37135. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  37136. backgroundNode = scene.backgroundNode;
  37137. } else {
  37138. const sceneData = this.get( scene );
  37139. if ( sceneData.backgroundNode ) {
  37140. backgroundNode = sceneData.backgroundNode;
  37141. }
  37142. }
  37143. return backgroundNode;
  37144. }
  37145. /**
  37146. * Returns a fog node for the current configured scene fog.
  37147. *
  37148. * @param {Scene} scene - The scene.
  37149. * @return {Node} A node representing the current scene fog.
  37150. */
  37151. getFogNode( scene ) {
  37152. this.updateFog( scene );
  37153. return scene.fogNode || this.get( scene ).fogNode || null;
  37154. }
  37155. /**
  37156. * Returns a cache key for the given scene and lights node.
  37157. * This key is used by `RenderObject` as a part of the dynamic
  37158. * cache key (a key that must be checked every time the render
  37159. * objects is drawn).
  37160. *
  37161. * @param {Scene} scene - The scene.
  37162. * @param {LightsNode} lightsNode - The lights node.
  37163. * @return {number} The cache key.
  37164. */
  37165. getCacheKey( scene, lightsNode ) {
  37166. _chainKeys$2[ 0 ] = scene;
  37167. _chainKeys$2[ 1 ] = lightsNode;
  37168. const callId = this.renderer.info.calls;
  37169. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  37170. if ( cacheKeyData.callId !== callId ) {
  37171. const environmentNode = this.getEnvironmentNode( scene );
  37172. const fogNode = this.getFogNode( scene );
  37173. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  37174. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  37175. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  37176. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  37177. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37178. cacheKeyData.callId = callId;
  37179. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  37180. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  37181. _cacheKeyValues.length = 0;
  37182. }
  37183. _chainKeys$2.length = 0;
  37184. return cacheKeyData.cacheKey;
  37185. }
  37186. /**
  37187. * A boolean that indicates whether tone mapping should be enabled
  37188. * or not.
  37189. *
  37190. * @type {boolean}
  37191. */
  37192. get isToneMappingState() {
  37193. return this.renderer.getRenderTarget() ? false : true;
  37194. }
  37195. /**
  37196. * If a scene background is configured, this method makes sure to
  37197. * represent the background with a corresponding node-based implementation.
  37198. *
  37199. * @param {Scene} scene - The scene.
  37200. */
  37201. updateBackground( scene ) {
  37202. const sceneData = this.get( scene );
  37203. const background = scene.background;
  37204. if ( background ) {
  37205. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37206. if ( sceneData.background !== background || forceUpdate ) {
  37207. const backgroundNode = this.getCacheNode( 'background', background, () => {
  37208. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37209. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37210. return pmremTexture( background );
  37211. } else {
  37212. let envMap;
  37213. if ( background.isCubeTexture === true ) {
  37214. envMap = cubeTexture( background );
  37215. } else {
  37216. envMap = texture( background );
  37217. }
  37218. return cubeMapNode( envMap );
  37219. }
  37220. } else if ( background.isTexture === true ) {
  37221. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37222. } else if ( background.isColor !== true ) {
  37223. error( 'WebGPUNodes: Unsupported background configuration.', background );
  37224. }
  37225. }, forceUpdate );
  37226. sceneData.backgroundNode = backgroundNode;
  37227. sceneData.background = background;
  37228. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37229. }
  37230. } else if ( sceneData.backgroundNode ) {
  37231. delete sceneData.backgroundNode;
  37232. delete sceneData.background;
  37233. }
  37234. }
  37235. /**
  37236. * This method is part of the caching of nodes which are used to represents the
  37237. * scene's background, fog or environment.
  37238. *
  37239. * @param {string} type - The type of object to cache.
  37240. * @param {Object} object - The object.
  37241. * @param {Function} callback - A callback that produces a node representation for the given object.
  37242. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  37243. * @return {Node} The node representation.
  37244. */
  37245. getCacheNode( type, object, callback, forceUpdate = false ) {
  37246. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  37247. let node = nodeCache.get( object );
  37248. if ( node === undefined || forceUpdate ) {
  37249. node = callback();
  37250. nodeCache.set( object, node );
  37251. }
  37252. return node;
  37253. }
  37254. /**
  37255. * If a scene fog is configured, this method makes sure to
  37256. * represent the fog with a corresponding node-based implementation.
  37257. *
  37258. * @param {Scene} scene - The scene.
  37259. */
  37260. updateFog( scene ) {
  37261. const sceneData = this.get( scene );
  37262. const sceneFog = scene.fog;
  37263. if ( sceneFog ) {
  37264. if ( sceneData.fog !== sceneFog ) {
  37265. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  37266. if ( sceneFog.isFogExp2 ) {
  37267. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37268. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  37269. return fog( color, densityFogFactor( density ) );
  37270. } else if ( sceneFog.isFog ) {
  37271. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37272. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  37273. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  37274. return fog( color, rangeFogFactor( near, far ) );
  37275. } else {
  37276. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  37277. }
  37278. } );
  37279. sceneData.fogNode = fogNode;
  37280. sceneData.fog = sceneFog;
  37281. }
  37282. } else {
  37283. delete sceneData.fogNode;
  37284. delete sceneData.fog;
  37285. }
  37286. }
  37287. /**
  37288. * If a scene environment is configured, this method makes sure to
  37289. * represent the environment with a corresponding node-based implementation.
  37290. *
  37291. * @param {Scene} scene - The scene.
  37292. */
  37293. updateEnvironment( scene ) {
  37294. const sceneData = this.get( scene );
  37295. const environment = scene.environment;
  37296. if ( environment ) {
  37297. if ( sceneData.environment !== environment ) {
  37298. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  37299. if ( environment.isCubeTexture === true ) {
  37300. return cubeTexture( environment );
  37301. } else if ( environment.isTexture === true ) {
  37302. return texture( environment );
  37303. } else {
  37304. error( 'Nodes: Unsupported environment configuration.', environment );
  37305. }
  37306. } );
  37307. sceneData.environmentNode = environmentNode;
  37308. sceneData.environment = environment;
  37309. }
  37310. } else if ( sceneData.environmentNode ) {
  37311. delete sceneData.environmentNode;
  37312. delete sceneData.environment;
  37313. }
  37314. }
  37315. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37316. const nodeFrame = this.nodeFrame;
  37317. nodeFrame.renderer = renderer;
  37318. nodeFrame.scene = scene;
  37319. nodeFrame.object = object;
  37320. nodeFrame.camera = camera;
  37321. nodeFrame.material = material;
  37322. return nodeFrame;
  37323. }
  37324. getNodeFrameForRender( renderObject ) {
  37325. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37326. }
  37327. /**
  37328. * Returns the current output cache key.
  37329. *
  37330. * @return {string} The output cache key.
  37331. */
  37332. getOutputCacheKey() {
  37333. const renderer = this.renderer;
  37334. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  37335. }
  37336. /**
  37337. * Checks if the output configuration (tone mapping and color space) for
  37338. * the given target has changed.
  37339. *
  37340. * @param {Texture} outputTarget - The output target.
  37341. * @return {boolean} Whether the output configuration has changed or not.
  37342. */
  37343. hasOutputChange( outputTarget ) {
  37344. const cacheKey = _outputNodeMap.get( outputTarget );
  37345. return cacheKey !== this.getOutputCacheKey();
  37346. }
  37347. /**
  37348. * Returns a node that represents the output configuration (tone mapping and
  37349. * color space) for the current target.
  37350. *
  37351. * @param {Texture} outputTarget - The output target.
  37352. * @return {Node} The output node.
  37353. */
  37354. getOutputNode( outputTarget ) {
  37355. const renderer = this.renderer;
  37356. const cacheKey = this.getOutputCacheKey();
  37357. const output = outputTarget.isArrayTexture ?
  37358. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  37359. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37360. _outputNodeMap.set( outputTarget, cacheKey );
  37361. return output;
  37362. }
  37363. /**
  37364. * Triggers the call of `updateBefore()` methods
  37365. * for all nodes of the given render object.
  37366. *
  37367. * @param {RenderObject} renderObject - The render object.
  37368. */
  37369. updateBefore( renderObject ) {
  37370. const nodeBuilder = renderObject.getNodeBuilderState();
  37371. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37372. // update frame state for each node
  37373. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37374. }
  37375. }
  37376. /**
  37377. * Triggers the call of `updateAfter()` methods
  37378. * for all nodes of the given render object.
  37379. *
  37380. * @param {RenderObject} renderObject - The render object.
  37381. */
  37382. updateAfter( renderObject ) {
  37383. const nodeBuilder = renderObject.getNodeBuilderState();
  37384. for ( const node of nodeBuilder.updateAfterNodes ) {
  37385. // update frame state for each node
  37386. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37387. }
  37388. }
  37389. /**
  37390. * Triggers the call of `update()` methods
  37391. * for all nodes of the given compute node.
  37392. *
  37393. * @param {Node} computeNode - The compute node.
  37394. */
  37395. updateForCompute( computeNode ) {
  37396. const nodeFrame = this.getNodeFrame();
  37397. const nodeBuilder = this.getForCompute( computeNode );
  37398. for ( const node of nodeBuilder.updateNodes ) {
  37399. nodeFrame.updateNode( node );
  37400. }
  37401. }
  37402. /**
  37403. * Triggers the call of `update()` methods
  37404. * for all nodes of the given compute node.
  37405. *
  37406. * @param {RenderObject} renderObject - The render object.
  37407. */
  37408. updateForRender( renderObject ) {
  37409. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37410. const nodeBuilder = renderObject.getNodeBuilderState();
  37411. for ( const node of nodeBuilder.updateNodes ) {
  37412. nodeFrame.updateNode( node );
  37413. }
  37414. }
  37415. /**
  37416. * Returns `true` if the given render object requires a refresh.
  37417. *
  37418. * @param {RenderObject} renderObject - The render object.
  37419. * @return {boolean} Whether the given render object requires a refresh or not.
  37420. */
  37421. needsRefresh( renderObject ) {
  37422. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37423. const monitor = renderObject.getMonitor();
  37424. return monitor.needsRefresh( renderObject, nodeFrame );
  37425. }
  37426. /**
  37427. * Frees the internal resources.
  37428. */
  37429. dispose() {
  37430. super.dispose();
  37431. this.nodeFrame = new NodeFrame();
  37432. this.nodeBuilderCache = new Map();
  37433. this.cacheLib = {};
  37434. }
  37435. }
  37436. const _plane = /*@__PURE__*/ new Plane();
  37437. /**
  37438. * Represents the state that is used to perform clipping via clipping planes.
  37439. * There is a default clipping context for each render context. When the
  37440. * scene holds instances of `ClippingGroup`, there will be a context for each
  37441. * group.
  37442. *
  37443. * @private
  37444. */
  37445. class ClippingContext {
  37446. /**
  37447. * Constructs a new clipping context.
  37448. *
  37449. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  37450. */
  37451. constructor( parentContext = null ) {
  37452. /**
  37453. * The clipping context's version.
  37454. *
  37455. * @type {number}
  37456. * @readonly
  37457. */
  37458. this.version = 0;
  37459. /**
  37460. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  37461. *
  37462. * @type {?boolean}
  37463. * @default null
  37464. */
  37465. this.clipIntersection = null;
  37466. /**
  37467. * The clipping context's cache key.
  37468. *
  37469. * @type {string}
  37470. */
  37471. this.cacheKey = '';
  37472. /**
  37473. * Whether the shadow pass is active or not.
  37474. *
  37475. * @type {boolean}
  37476. * @default false
  37477. */
  37478. this.shadowPass = false;
  37479. /**
  37480. * The view normal matrix.
  37481. *
  37482. * @type {Matrix3}
  37483. */
  37484. this.viewNormalMatrix = new Matrix3();
  37485. /**
  37486. * Internal cache for maintaining clipping contexts.
  37487. *
  37488. * @type {WeakMap<ClippingGroup,ClippingContext>}
  37489. */
  37490. this.clippingGroupContexts = new WeakMap();
  37491. /**
  37492. * The intersection planes.
  37493. *
  37494. * @type {Array<Vector4>}
  37495. */
  37496. this.intersectionPlanes = [];
  37497. /**
  37498. * The intersection planes.
  37499. *
  37500. * @type {Array<Vector4>}
  37501. */
  37502. this.unionPlanes = [];
  37503. /**
  37504. * The version of the clipping context's parent context.
  37505. *
  37506. * @type {?number}
  37507. * @readonly
  37508. */
  37509. this.parentVersion = null;
  37510. if ( parentContext !== null ) {
  37511. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  37512. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  37513. this.shadowPass = parentContext.shadowPass;
  37514. this.viewMatrix = parentContext.viewMatrix;
  37515. }
  37516. }
  37517. /**
  37518. * Projects the given source clipping planes and writes the result into the
  37519. * destination array.
  37520. *
  37521. * @param {Array<Plane>} source - The source clipping planes.
  37522. * @param {Array<Vector4>} destination - The destination.
  37523. * @param {number} offset - The offset.
  37524. */
  37525. projectPlanes( source, destination, offset ) {
  37526. const l = source.length;
  37527. for ( let i = 0; i < l; i ++ ) {
  37528. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  37529. const v = destination[ offset + i ];
  37530. const normal = _plane.normal;
  37531. v.x = - normal.x;
  37532. v.y = - normal.y;
  37533. v.z = - normal.z;
  37534. v.w = _plane.constant;
  37535. }
  37536. }
  37537. /**
  37538. * Updates the root clipping context of a scene.
  37539. *
  37540. * @param {Scene} scene - The scene.
  37541. * @param {Camera} camera - The camera that is used to render the scene.
  37542. */
  37543. updateGlobal( scene, camera ) {
  37544. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  37545. this.viewMatrix = camera.matrixWorldInverse;
  37546. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37547. }
  37548. /**
  37549. * Updates the clipping context.
  37550. *
  37551. * @param {ClippingContext} parentContext - The parent context.
  37552. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  37553. */
  37554. update( parentContext, clippingGroup ) {
  37555. let update = false;
  37556. if ( parentContext.version !== this.parentVersion ) {
  37557. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37558. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37559. this.parentVersion = parentContext.version;
  37560. }
  37561. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37562. this.clipIntersection = clippingGroup.clipIntersection;
  37563. if ( this.clipIntersection ) {
  37564. this.unionPlanes.length = parentContext.unionPlanes.length;
  37565. } else {
  37566. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37567. }
  37568. }
  37569. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37570. const l = srcClippingPlanes.length;
  37571. let dstClippingPlanes;
  37572. let offset;
  37573. if ( this.clipIntersection ) {
  37574. dstClippingPlanes = this.intersectionPlanes;
  37575. offset = parentContext.intersectionPlanes.length;
  37576. } else {
  37577. dstClippingPlanes = this.unionPlanes;
  37578. offset = parentContext.unionPlanes.length;
  37579. }
  37580. if ( dstClippingPlanes.length !== offset + l ) {
  37581. dstClippingPlanes.length = offset + l;
  37582. for ( let i = 0; i < l; i ++ ) {
  37583. dstClippingPlanes[ offset + i ] = new Vector4();
  37584. }
  37585. update = true;
  37586. }
  37587. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37588. if ( update ) {
  37589. this.version ++;
  37590. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37591. }
  37592. }
  37593. /**
  37594. * Returns a clipping context for the given clipping group.
  37595. *
  37596. * @param {ClippingGroup} clippingGroup - The clipping group.
  37597. * @return {ClippingContext} The clipping context.
  37598. */
  37599. getGroupContext( clippingGroup ) {
  37600. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37601. let context = this.clippingGroupContexts.get( clippingGroup );
  37602. if ( context === undefined ) {
  37603. context = new ClippingContext( this );
  37604. this.clippingGroupContexts.set( clippingGroup, context );
  37605. }
  37606. context.update( this, clippingGroup );
  37607. return context;
  37608. }
  37609. /**
  37610. * The count of union clipping planes.
  37611. *
  37612. * @type {number}
  37613. * @readonly
  37614. */
  37615. get unionClippingCount() {
  37616. return this.unionPlanes.length;
  37617. }
  37618. }
  37619. /**
  37620. * This module is used to represent render bundles inside the renderer
  37621. * for further processing.
  37622. *
  37623. * @private
  37624. */
  37625. class RenderBundle {
  37626. /**
  37627. * Constructs a new bundle group.
  37628. *
  37629. * @param {BundleGroup} bundleGroup - The bundle group.
  37630. * @param {Camera} camera - The camera the bundle group is rendered with.
  37631. */
  37632. constructor( bundleGroup, camera ) {
  37633. this.bundleGroup = bundleGroup;
  37634. this.camera = camera;
  37635. }
  37636. }
  37637. const _chainKeys$1 = [];
  37638. /**
  37639. * This renderer module manages render bundles.
  37640. *
  37641. * @private
  37642. */
  37643. class RenderBundles {
  37644. /**
  37645. * Constructs a new render bundle management component.
  37646. */
  37647. constructor() {
  37648. /**
  37649. * A chain map for maintaining the render bundles.
  37650. *
  37651. * @type {ChainMap}
  37652. */
  37653. this.bundles = new ChainMap();
  37654. }
  37655. /**
  37656. * Returns a render bundle for the given bundle group and camera.
  37657. *
  37658. * @param {BundleGroup} bundleGroup - The bundle group.
  37659. * @param {Camera} camera - The camera the bundle group is rendered with.
  37660. * @return {RenderBundle} The render bundle.
  37661. */
  37662. get( bundleGroup, camera ) {
  37663. const bundles = this.bundles;
  37664. _chainKeys$1[ 0 ] = bundleGroup;
  37665. _chainKeys$1[ 1 ] = camera;
  37666. let bundle = bundles.get( _chainKeys$1 );
  37667. if ( bundle === undefined ) {
  37668. bundle = new RenderBundle( bundleGroup, camera );
  37669. bundles.set( _chainKeys$1, bundle );
  37670. }
  37671. _chainKeys$1.length = 0;
  37672. return bundle;
  37673. }
  37674. /**
  37675. * Frees all internal resources.
  37676. */
  37677. dispose() {
  37678. this.bundles = new ChainMap();
  37679. }
  37680. }
  37681. /**
  37682. * The purpose of a node library is to assign node implementations
  37683. * to existing library features. In `WebGPURenderer` lights, materials
  37684. * which are not based on `NodeMaterial` as well as tone mapping techniques
  37685. * are implemented with node-based modules.
  37686. *
  37687. * @private
  37688. */
  37689. class NodeLibrary {
  37690. /**
  37691. * Constructs a new node library.
  37692. */
  37693. constructor() {
  37694. /**
  37695. * A weak map that maps lights to light nodes.
  37696. *
  37697. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  37698. */
  37699. this.lightNodes = new WeakMap();
  37700. /**
  37701. * A map that maps materials to node materials.
  37702. *
  37703. * @type {Map<string,NodeMaterial.constructor>}
  37704. */
  37705. this.materialNodes = new Map();
  37706. /**
  37707. * A map that maps tone mapping techniques (constants)
  37708. * to tone mapping node functions.
  37709. *
  37710. * @type {Map<number,Function>}
  37711. */
  37712. this.toneMappingNodes = new Map();
  37713. }
  37714. /**
  37715. * Returns a matching node material instance for the given material object.
  37716. *
  37717. * This method also assigns/copies the properties of the given material object
  37718. * to the node material. This is done to make sure the current material
  37719. * configuration carries over to the node version.
  37720. *
  37721. * @param {Material} material - A material.
  37722. * @return {NodeMaterial} The corresponding node material.
  37723. */
  37724. fromMaterial( material ) {
  37725. if ( material.isNodeMaterial ) return material;
  37726. let nodeMaterial = null;
  37727. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37728. if ( nodeMaterialClass !== null ) {
  37729. nodeMaterial = new nodeMaterialClass();
  37730. for ( const key in material ) {
  37731. nodeMaterial[ key ] = material[ key ];
  37732. }
  37733. }
  37734. return nodeMaterial;
  37735. }
  37736. /**
  37737. * Adds a tone mapping node function for a tone mapping technique (constant).
  37738. *
  37739. * @param {Function} toneMappingNode - The tone mapping node function.
  37740. * @param {number} toneMapping - The tone mapping.
  37741. */
  37742. addToneMapping( toneMappingNode, toneMapping ) {
  37743. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37744. }
  37745. /**
  37746. * Returns a tone mapping node function for a tone mapping technique (constant).
  37747. *
  37748. * @param {number} toneMapping - The tone mapping.
  37749. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  37750. */
  37751. getToneMappingFunction( toneMapping ) {
  37752. return this.toneMappingNodes.get( toneMapping ) || null;
  37753. }
  37754. /**
  37755. * Returns a node material class definition for a material type.
  37756. *
  37757. * @param {string} materialType - The material type.
  37758. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  37759. */
  37760. getMaterialNodeClass( materialType ) {
  37761. return this.materialNodes.get( materialType ) || null;
  37762. }
  37763. /**
  37764. * Adds a node material class definition for a given material type.
  37765. *
  37766. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  37767. * @param {string} materialClassType - The material type.
  37768. */
  37769. addMaterial( materialNodeClass, materialClassType ) {
  37770. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37771. }
  37772. /**
  37773. * Returns a light node class definition for a light class definition.
  37774. *
  37775. * @param {Light.constructor} light - The light class definition.
  37776. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  37777. */
  37778. getLightNodeClass( light ) {
  37779. return this.lightNodes.get( light ) || null;
  37780. }
  37781. /**
  37782. * Adds a light node class definition for a given light class definition.
  37783. *
  37784. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  37785. * @param {Light.constructor} lightClass - The light class definition.
  37786. */
  37787. addLight( lightNodeClass, lightClass ) {
  37788. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37789. }
  37790. /**
  37791. * Adds a node class definition for the given type to the provided type library.
  37792. *
  37793. * @param {Node.constructor} nodeClass - The node class definition.
  37794. * @param {number|string} type - The object type.
  37795. * @param {Map<number|string,Node.constructor>} library - The type library.
  37796. */
  37797. addType( nodeClass, type, library ) {
  37798. if ( library.has( type ) ) {
  37799. warn( `Redefinition of node ${ type }` );
  37800. return;
  37801. }
  37802. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37803. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37804. library.set( type, nodeClass );
  37805. }
  37806. /**
  37807. * Adds a node class definition for the given class definition to the provided type library.
  37808. *
  37809. * @param {Node.constructor} nodeClass - The node class definition.
  37810. * @param {Node.constructor} baseClass - The class definition.
  37811. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  37812. */
  37813. addClass( nodeClass, baseClass, library ) {
  37814. if ( library.has( baseClass ) ) {
  37815. warn( `Redefinition of node ${ baseClass.name }` );
  37816. return;
  37817. }
  37818. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37819. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37820. library.set( baseClass, nodeClass );
  37821. }
  37822. }
  37823. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37824. const _chainKeys = [];
  37825. /**
  37826. * This renderer module manages the lights nodes which are unique
  37827. * per scene and camera combination.
  37828. *
  37829. * The lights node itself is later configured in the render list
  37830. * with the actual lights from the scene.
  37831. *
  37832. * @private
  37833. * @augments ChainMap
  37834. */
  37835. class Lighting extends ChainMap {
  37836. /**
  37837. * Constructs a lighting management component.
  37838. */
  37839. constructor() {
  37840. super();
  37841. }
  37842. /**
  37843. * Creates a new lights node for the given array of lights.
  37844. *
  37845. * @param {Array<Light>} lights - The render object.
  37846. * @return {LightsNode} The lights node.
  37847. */
  37848. createNode( lights = [] ) {
  37849. return new LightsNode().setLights( lights );
  37850. }
  37851. /**
  37852. * Returns a lights node for the given scene and camera.
  37853. *
  37854. * @param {Scene} scene - The scene.
  37855. * @param {Camera} camera - The camera.
  37856. * @return {LightsNode} The lights node.
  37857. */
  37858. getNode( scene, camera ) {
  37859. // ignore post-processing
  37860. if ( scene.isQuadMesh ) return _defaultLights;
  37861. _chainKeys[ 0 ] = scene;
  37862. _chainKeys[ 1 ] = camera;
  37863. let node = this.get( _chainKeys );
  37864. if ( node === undefined ) {
  37865. node = this.createNode();
  37866. this.set( _chainKeys, node );
  37867. }
  37868. _chainKeys.length = 0;
  37869. return node;
  37870. }
  37871. }
  37872. /**
  37873. * A special type of render target that is used when rendering
  37874. * with the WebXR Device API.
  37875. *
  37876. * @private
  37877. * @augments RenderTarget
  37878. */
  37879. class XRRenderTarget extends RenderTarget {
  37880. /**
  37881. * Constructs a new XR render target.
  37882. *
  37883. * @param {number} [width=1] - The width of the render target.
  37884. * @param {number} [height=1] - The height of the render target.
  37885. * @param {Object} [options={}] - The configuration options.
  37886. */
  37887. constructor( width = 1, height = 1, options = {} ) {
  37888. super( width, height, options );
  37889. /**
  37890. * This flag can be used for type testing.
  37891. *
  37892. * @type {boolean}
  37893. * @readonly
  37894. * @default true
  37895. */
  37896. this.isXRRenderTarget = true;
  37897. /**
  37898. * Whether the attachments of the render target
  37899. * are defined by external textures. This flag is
  37900. * set to `true` when using the WebXR Layers API.
  37901. *
  37902. * @private
  37903. * @type {boolean}
  37904. * @default false
  37905. */
  37906. this._hasExternalTextures = false;
  37907. /**
  37908. * Whether a depth buffer should automatically be allocated
  37909. * for this XR render target or not.
  37910. *
  37911. * Allocating a depth buffer is the default behavior of XR render
  37912. * targets. However, when using the WebXR Layers API, this flag
  37913. * must be set to `false` when the `ignoreDepthValues` property of
  37914. * the projection layers evaluates to `false`.
  37915. *
  37916. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37917. *
  37918. * @private
  37919. * @type {boolean}
  37920. * @default true
  37921. */
  37922. this._autoAllocateDepthBuffer = true;
  37923. /**
  37924. * Whether this render target is associated with a XRWebGLLayer.
  37925. *
  37926. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37927. * this means that you don't have access to its bound color,
  37928. * stencil and depth buffers. We need to handle this framebuffer
  37929. * differently since its textures are always bound.
  37930. *
  37931. * @private
  37932. * @type {boolean}
  37933. * @default false
  37934. * */
  37935. this._isOpaqueFramebuffer = false;
  37936. }
  37937. copy( source ) {
  37938. super.copy( source );
  37939. this._hasExternalTextures = source._hasExternalTextures;
  37940. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37941. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37942. return this;
  37943. }
  37944. }
  37945. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37946. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37947. /**
  37948. * The XR manager is built on top of the WebXR Device API to
  37949. * manage XR sessions with `WebGPURenderer`.
  37950. *
  37951. * XR is currently only supported with a WebGL 2 backend.
  37952. *
  37953. * @augments EventDispatcher
  37954. */
  37955. class XRManager extends EventDispatcher {
  37956. /**
  37957. * Constructs a new XR manager.
  37958. *
  37959. * @param {Renderer} renderer - The renderer.
  37960. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37961. */
  37962. constructor( renderer, multiview = false ) {
  37963. super();
  37964. /**
  37965. * This flag globally enables XR rendering.
  37966. *
  37967. * @type {boolean}
  37968. * @default false
  37969. */
  37970. this.enabled = false;
  37971. /**
  37972. * Whether the XR device is currently presenting or not.
  37973. *
  37974. * @type {boolean}
  37975. * @default false
  37976. * @readonly
  37977. */
  37978. this.isPresenting = false;
  37979. /**
  37980. * Whether the XR camera should automatically be updated or not.
  37981. *
  37982. * @type {boolean}
  37983. * @default true
  37984. */
  37985. this.cameraAutoUpdate = true;
  37986. /**
  37987. * The renderer.
  37988. *
  37989. * @private
  37990. * @type {Renderer}
  37991. */
  37992. this._renderer = renderer;
  37993. // camera
  37994. /**
  37995. * Represents the camera for the left eye.
  37996. *
  37997. * @private
  37998. * @type {PerspectiveCamera}
  37999. */
  38000. this._cameraL = new PerspectiveCamera();
  38001. this._cameraL.viewport = new Vector4();
  38002. /**
  38003. * Represents the camera for the right eye.
  38004. *
  38005. * @private
  38006. * @type {PerspectiveCamera}
  38007. */
  38008. this._cameraR = new PerspectiveCamera();
  38009. this._cameraR.viewport = new Vector4();
  38010. /**
  38011. * A list of cameras used for rendering the XR views.
  38012. *
  38013. * @private
  38014. * @type {Array<Camera>}
  38015. */
  38016. this._cameras = [ this._cameraL, this._cameraR ];
  38017. /**
  38018. * The main XR camera.
  38019. *
  38020. * @private
  38021. * @type {ArrayCamera}
  38022. */
  38023. this._cameraXR = new ArrayCamera();
  38024. /**
  38025. * The current near value of the XR camera.
  38026. *
  38027. * @private
  38028. * @type {?number}
  38029. * @default null
  38030. */
  38031. this._currentDepthNear = null;
  38032. /**
  38033. * The current far value of the XR camera.
  38034. *
  38035. * @private
  38036. * @type {?number}
  38037. * @default null
  38038. */
  38039. this._currentDepthFar = null;
  38040. /**
  38041. * A list of WebXR controllers requested by the application.
  38042. *
  38043. * @private
  38044. * @type {Array<WebXRController>}
  38045. */
  38046. this._controllers = [];
  38047. /**
  38048. * A list of XR input source. Each input source belongs to
  38049. * an instance of WebXRController.
  38050. *
  38051. * @private
  38052. * @type {Array<XRInputSource?>}
  38053. */
  38054. this._controllerInputSources = [];
  38055. /**
  38056. * The XR render target that represents the rendering destination
  38057. * during an active XR session.
  38058. *
  38059. * @private
  38060. * @type {?RenderTarget}
  38061. * @default null
  38062. */
  38063. this._xrRenderTarget = null;
  38064. /**
  38065. * An array holding all the non-projection layers
  38066. *
  38067. * @private
  38068. * @type {Array<Object>}
  38069. * @default []
  38070. */
  38071. this._layers = [];
  38072. /**
  38073. * Whether the XR session uses layers.
  38074. *
  38075. * @type {boolean}
  38076. * @default false
  38077. */
  38078. this._sessionUsesLayers = false;
  38079. /**
  38080. * Whether the device supports binding gl objects.
  38081. *
  38082. * @private
  38083. * @type {boolean}
  38084. * @readonly
  38085. */
  38086. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  38087. this._frameBufferTargets = null;
  38088. /**
  38089. * Helper function to create native WebXR Layer.
  38090. *
  38091. * @private
  38092. * @type {Function}
  38093. */
  38094. this._createXRLayer = createXRLayer.bind( this );
  38095. /**
  38096. * The current WebGL context.
  38097. *
  38098. * @private
  38099. * @type {?WebGL2RenderingContext}
  38100. * @default null
  38101. */
  38102. this._gl = null;
  38103. /**
  38104. * The current animation context.
  38105. *
  38106. * @private
  38107. * @type {?Window}
  38108. * @default null
  38109. */
  38110. this._currentAnimationContext = null;
  38111. /**
  38112. * The current animation loop.
  38113. *
  38114. * @private
  38115. * @type {?Function}
  38116. * @default null
  38117. */
  38118. this._currentAnimationLoop = null;
  38119. /**
  38120. * The current pixel ratio.
  38121. *
  38122. * @private
  38123. * @type {?number}
  38124. * @default null
  38125. */
  38126. this._currentPixelRatio = null;
  38127. /**
  38128. * The current size of the renderer's canvas
  38129. * in logical pixel unit.
  38130. *
  38131. * @private
  38132. * @type {Vector2}
  38133. */
  38134. this._currentSize = new Vector2();
  38135. /**
  38136. * The default event listener for handling events inside a XR session.
  38137. *
  38138. * @private
  38139. * @type {Function}
  38140. */
  38141. this._onSessionEvent = onSessionEvent.bind( this );
  38142. /**
  38143. * The event listener for handling the end of a XR session.
  38144. *
  38145. * @private
  38146. * @type {Function}
  38147. */
  38148. this._onSessionEnd = onSessionEnd.bind( this );
  38149. /**
  38150. * The event listener for handling the `inputsourceschange` event.
  38151. *
  38152. * @private
  38153. * @type {Function}
  38154. */
  38155. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  38156. /**
  38157. * The animation loop which is used as a replacement for the default
  38158. * animation loop of the application. It is only used when a XR session
  38159. * is active.
  38160. *
  38161. * @private
  38162. * @type {Function}
  38163. */
  38164. this._onAnimationFrame = onAnimationFrame.bind( this );
  38165. /**
  38166. * The current XR reference space.
  38167. *
  38168. * @private
  38169. * @type {?XRReferenceSpace}
  38170. * @default null
  38171. */
  38172. this._referenceSpace = null;
  38173. /**
  38174. * The current XR reference space type.
  38175. *
  38176. * @private
  38177. * @type {XRReferenceSpaceType}
  38178. * @default 'local-floor'
  38179. */
  38180. this._referenceSpaceType = 'local-floor';
  38181. /**
  38182. * A custom reference space defined by the application.
  38183. *
  38184. * @private
  38185. * @type {?XRReferenceSpace}
  38186. * @default null
  38187. */
  38188. this._customReferenceSpace = null;
  38189. /**
  38190. * The framebuffer scale factor.
  38191. *
  38192. * @private
  38193. * @type {number}
  38194. * @default 1
  38195. */
  38196. this._framebufferScaleFactor = 1;
  38197. /**
  38198. * The foveation factor.
  38199. *
  38200. * @private
  38201. * @type {number}
  38202. * @default 1
  38203. */
  38204. this._foveation = 1.0;
  38205. /**
  38206. * A reference to the current XR session.
  38207. *
  38208. * @private
  38209. * @type {?XRSession}
  38210. * @default null
  38211. */
  38212. this._session = null;
  38213. /**
  38214. * A reference to the current XR base layer.
  38215. *
  38216. * @private
  38217. * @type {?XRWebGLLayer}
  38218. * @default null
  38219. */
  38220. this._glBaseLayer = null;
  38221. /**
  38222. * A reference to the current XR binding.
  38223. *
  38224. * @private
  38225. * @type {?XRWebGLBinding}
  38226. * @default null
  38227. */
  38228. this._glBinding = null;
  38229. /**
  38230. * A reference to the current XR projection layer.
  38231. *
  38232. * @private
  38233. * @type {?XRProjectionLayer}
  38234. * @default null
  38235. */
  38236. this._glProjLayer = null;
  38237. /**
  38238. * A reference to the current XR frame.
  38239. *
  38240. * @private
  38241. * @type {?XRFrame}
  38242. * @default null
  38243. */
  38244. this._xrFrame = null;
  38245. /**
  38246. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  38247. *
  38248. * Note: this does not represent XRSession explicitly requesting
  38249. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  38250. *
  38251. * @private
  38252. * @type {boolean}
  38253. * @readonly
  38254. */
  38255. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  38256. /**
  38257. * Whether the usage of multiview has been requested by the application or not.
  38258. *
  38259. * @private
  38260. * @type {boolean}
  38261. * @default false
  38262. * @readonly
  38263. */
  38264. this._useMultiviewIfPossible = multiview;
  38265. /**
  38266. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  38267. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  38268. *
  38269. * @private
  38270. * @type {boolean}
  38271. * @readonly
  38272. */
  38273. this._useMultiview = false;
  38274. }
  38275. /**
  38276. * Returns an instance of `THREE.Group` that represents the transformation
  38277. * of a XR controller in target ray space. The requested controller is defined
  38278. * by the given index.
  38279. *
  38280. * @param {number} index - The index of the XR controller.
  38281. * @return {Group} A group that represents the controller's transformation.
  38282. */
  38283. getController( index ) {
  38284. const controller = this._getController( index );
  38285. return controller.getTargetRaySpace();
  38286. }
  38287. /**
  38288. * Returns an instance of `THREE.Group` that represents the transformation
  38289. * of a XR controller in grip space. The requested controller is defined
  38290. * by the given index.
  38291. *
  38292. * @param {number} index - The index of the XR controller.
  38293. * @return {Group} A group that represents the controller's transformation.
  38294. */
  38295. getControllerGrip( index ) {
  38296. const controller = this._getController( index );
  38297. return controller.getGripSpace();
  38298. }
  38299. /**
  38300. * Returns an instance of `THREE.Group` that represents the transformation
  38301. * of a XR controller in hand space. The requested controller is defined
  38302. * by the given index.
  38303. *
  38304. * @param {number} index - The index of the XR controller.
  38305. * @return {Group} A group that represents the controller's transformation.
  38306. */
  38307. getHand( index ) {
  38308. const controller = this._getController( index );
  38309. return controller.getHandSpace();
  38310. }
  38311. /**
  38312. * Returns the foveation value.
  38313. *
  38314. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  38315. */
  38316. getFoveation() {
  38317. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  38318. return undefined;
  38319. }
  38320. return this._foveation;
  38321. }
  38322. /**
  38323. * Sets the foveation value.
  38324. *
  38325. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  38326. * and `1` means maximum foveation (the edges render at lower resolution).
  38327. */
  38328. setFoveation( foveation ) {
  38329. this._foveation = foveation;
  38330. if ( this._glProjLayer !== null ) {
  38331. this._glProjLayer.fixedFoveation = foveation;
  38332. }
  38333. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  38334. this._glBaseLayer.fixedFoveation = foveation;
  38335. }
  38336. }
  38337. /**
  38338. * Returns the framebuffer scale factor.
  38339. *
  38340. * @return {number} The framebuffer scale factor.
  38341. */
  38342. getFramebufferScaleFactor() {
  38343. return this._framebufferScaleFactor;
  38344. }
  38345. /**
  38346. * Sets the framebuffer scale factor.
  38347. *
  38348. * This method can not be used during a XR session.
  38349. *
  38350. * @param {number} factor - The framebuffer scale factor.
  38351. */
  38352. setFramebufferScaleFactor( factor ) {
  38353. this._framebufferScaleFactor = factor;
  38354. if ( this.isPresenting === true ) {
  38355. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  38356. }
  38357. }
  38358. /**
  38359. * Returns the reference space type.
  38360. *
  38361. * @return {XRReferenceSpaceType} The reference space type.
  38362. */
  38363. getReferenceSpaceType() {
  38364. return this._referenceSpaceType;
  38365. }
  38366. /**
  38367. * Sets the reference space type.
  38368. *
  38369. * This method can not be used during a XR session.
  38370. *
  38371. * @param {XRReferenceSpaceType} type - The reference space type.
  38372. */
  38373. setReferenceSpaceType( type ) {
  38374. this._referenceSpaceType = type;
  38375. if ( this.isPresenting === true ) {
  38376. warn( 'XRManager: Cannot change reference space type while presenting.' );
  38377. }
  38378. }
  38379. /**
  38380. * Returns the XR reference space.
  38381. *
  38382. * @return {XRReferenceSpace} The XR reference space.
  38383. */
  38384. getReferenceSpace() {
  38385. return this._customReferenceSpace || this._referenceSpace;
  38386. }
  38387. /**
  38388. * Sets a custom XR reference space.
  38389. *
  38390. * @param {XRReferenceSpace} space - The XR reference space.
  38391. */
  38392. setReferenceSpace( space ) {
  38393. this._customReferenceSpace = space;
  38394. }
  38395. /**
  38396. * Returns the XR camera.
  38397. *
  38398. * @return {ArrayCamera} The XR camera.
  38399. */
  38400. getCamera() {
  38401. return this._cameraXR;
  38402. }
  38403. /**
  38404. * Returns the environment blend mode from the current XR session.
  38405. *
  38406. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  38407. */
  38408. getEnvironmentBlendMode() {
  38409. if ( this._session !== null ) {
  38410. return this._session.environmentBlendMode;
  38411. }
  38412. }
  38413. /**
  38414. * Returns the current XR binding.
  38415. *
  38416. * Creates a new binding if needed and the browser is
  38417. * capable of doing so.
  38418. *
  38419. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  38420. */
  38421. getBinding() {
  38422. if ( this._glBinding === null && this._supportsGlBinding ) {
  38423. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  38424. }
  38425. return this._glBinding;
  38426. }
  38427. /**
  38428. * Returns the current XR frame.
  38429. *
  38430. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  38431. */
  38432. getFrame() {
  38433. return this._xrFrame;
  38434. }
  38435. /**
  38436. * Returns `true` if the engine renders to a multiview target.
  38437. *
  38438. * @return {boolean} Whether the engine renders to a multiview render target or not.
  38439. */
  38440. useMultiview() {
  38441. return this._useMultiview;
  38442. }
  38443. /**
  38444. * This method can be used in XR applications to create a quadratic layer that presents a separate
  38445. * rendered scene.
  38446. *
  38447. * @param {number} width - The width of the layer plane in world units.
  38448. * @param {number} height - The height of the layer plane in world units.
  38449. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38450. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38451. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38452. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38453. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38454. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38455. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38456. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  38457. */
  38458. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38459. const geometry = new PlaneGeometry( width, height );
  38460. const renderTarget = new XRRenderTarget(
  38461. pixelwidth,
  38462. pixelheight,
  38463. {
  38464. format: RGBAFormat,
  38465. type: UnsignedByteType,
  38466. depthTexture: new DepthTexture(
  38467. pixelwidth,
  38468. pixelheight,
  38469. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38470. undefined,
  38471. undefined,
  38472. undefined,
  38473. undefined,
  38474. undefined,
  38475. undefined,
  38476. attributes.stencil ? DepthStencilFormat : DepthFormat
  38477. ),
  38478. stencilBuffer: attributes.stencil,
  38479. resolveDepthBuffer: false,
  38480. resolveStencilBuffer: false
  38481. } );
  38482. renderTarget._autoAllocateDepthBuffer = true;
  38483. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38484. material.map = renderTarget.texture;
  38485. material.map.offset.y = 1;
  38486. material.map.repeat.y = -1;
  38487. const plane = new Mesh( geometry, material );
  38488. plane.position.copy( translation );
  38489. plane.quaternion.copy( quaternion );
  38490. const layer = {
  38491. type: 'quad',
  38492. width: width,
  38493. height: height,
  38494. translation: translation,
  38495. quaternion: quaternion,
  38496. pixelwidth: pixelwidth,
  38497. pixelheight: pixelheight,
  38498. plane: plane,
  38499. material: material,
  38500. rendercall: rendercall,
  38501. renderTarget: renderTarget };
  38502. this._layers.push( layer );
  38503. if ( this._session !== null ) {
  38504. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38505. layer.plane.material.blending = CustomBlending;
  38506. layer.plane.material.blendEquation = AddEquation;
  38507. layer.plane.material.blendSrc = ZeroFactor;
  38508. layer.plane.material.blendDst = ZeroFactor;
  38509. layer.xrlayer = this._createXRLayer( layer );
  38510. const xrlayers = this._session.renderState.layers;
  38511. xrlayers.unshift( layer.xrlayer );
  38512. this._session.updateRenderState( { layers: xrlayers } );
  38513. } else {
  38514. renderTarget.isXRRenderTarget = false;
  38515. }
  38516. return plane;
  38517. }
  38518. /**
  38519. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  38520. * rendered scene.
  38521. *
  38522. * @param {number} radius - The radius of the cylinder in world units.
  38523. * @param {number} centralAngle - The central angle of the cylinder in radians.
  38524. * @param {number} aspectratio - The aspect ratio.
  38525. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38526. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38527. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38528. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38529. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38530. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38531. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38532. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  38533. */
  38534. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38535. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  38536. const renderTarget = new XRRenderTarget(
  38537. pixelwidth,
  38538. pixelheight,
  38539. {
  38540. format: RGBAFormat,
  38541. type: UnsignedByteType,
  38542. depthTexture: new DepthTexture(
  38543. pixelwidth,
  38544. pixelheight,
  38545. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38546. undefined,
  38547. undefined,
  38548. undefined,
  38549. undefined,
  38550. undefined,
  38551. undefined,
  38552. attributes.stencil ? DepthStencilFormat : DepthFormat
  38553. ),
  38554. stencilBuffer: attributes.stencil,
  38555. resolveDepthBuffer: false,
  38556. resolveStencilBuffer: false
  38557. } );
  38558. renderTarget._autoAllocateDepthBuffer = true;
  38559. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38560. material.map = renderTarget.texture;
  38561. material.map.offset.y = 1;
  38562. material.map.repeat.y = -1;
  38563. const plane = new Mesh( geometry, material );
  38564. plane.position.copy( translation );
  38565. plane.quaternion.copy( quaternion );
  38566. const layer = {
  38567. type: 'cylinder',
  38568. radius: radius,
  38569. centralAngle: centralAngle,
  38570. aspectratio: aspectratio,
  38571. translation: translation,
  38572. quaternion: quaternion,
  38573. pixelwidth: pixelwidth,
  38574. pixelheight: pixelheight,
  38575. plane: plane,
  38576. material: material,
  38577. rendercall: rendercall,
  38578. renderTarget: renderTarget };
  38579. this._layers.push( layer );
  38580. if ( this._session !== null ) {
  38581. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38582. layer.plane.material.blending = CustomBlending;
  38583. layer.plane.material.blendEquation = AddEquation;
  38584. layer.plane.material.blendSrc = ZeroFactor;
  38585. layer.plane.material.blendDst = ZeroFactor;
  38586. layer.xrlayer = this._createXRLayer( layer );
  38587. const xrlayers = this._session.renderState.layers;
  38588. xrlayers.unshift( layer.xrlayer );
  38589. this._session.updateRenderState( { layers: xrlayers } );
  38590. } else {
  38591. renderTarget.isXRRenderTarget = false;
  38592. }
  38593. return plane;
  38594. }
  38595. /**
  38596. * Renders the XR layers that have been previously added to the scene.
  38597. *
  38598. * This method is usually called in your animation loop before rendering
  38599. * the actual scene via `renderer.render( scene, camera );`.
  38600. */
  38601. renderLayers( ) {
  38602. const translationObject = new Vector3();
  38603. const quaternionObject = new Quaternion();
  38604. const renderer = this._renderer;
  38605. const wasPresenting = this.isPresenting;
  38606. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38607. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38608. this.isPresenting = false;
  38609. const rendererSize = new Vector2();
  38610. renderer.getSize( rendererSize );
  38611. const rendererQuad = renderer._quad;
  38612. for ( const layer of this._layers ) {
  38613. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38614. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38615. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38616. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38617. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38618. renderer.backend.setXRRenderTargetTextures(
  38619. layer.renderTarget,
  38620. glSubImage.colorTexture,
  38621. undefined );
  38622. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38623. renderer.setOutputRenderTarget( layer.renderTarget );
  38624. renderer.setRenderTarget( null );
  38625. renderer._frameBufferTarget = null;
  38626. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38627. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38628. if ( ! frameBufferTarget ) {
  38629. renderer._quad = new QuadMesh( new NodeMaterial() );
  38630. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38631. } else {
  38632. renderer._frameBufferTarget = frameBufferTarget;
  38633. renderer._quad = quad;
  38634. }
  38635. layer.rendercall();
  38636. renderer._frameBufferTarget = null;
  38637. } else {
  38638. renderer.setRenderTarget( layer.renderTarget );
  38639. layer.rendercall();
  38640. }
  38641. }
  38642. renderer.setRenderTarget( null );
  38643. renderer.setOutputRenderTarget( rendererOutputTarget );
  38644. renderer._frameBufferTarget = rendererFramebufferTarget;
  38645. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38646. renderer._quad = rendererQuad;
  38647. this.isPresenting = wasPresenting;
  38648. }
  38649. /**
  38650. * Returns the current XR session.
  38651. *
  38652. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38653. */
  38654. getSession() {
  38655. return this._session;
  38656. }
  38657. /**
  38658. * After a XR session has been requested usually with one of the `*Button` modules, it
  38659. * is injected into the renderer with this method. This method triggers the start of
  38660. * the actual XR rendering.
  38661. *
  38662. * @async
  38663. * @param {XRSession} session - The XR session to set.
  38664. * @return {Promise} A Promise that resolves when the session has been set.
  38665. */
  38666. async setSession( session ) {
  38667. const renderer = this._renderer;
  38668. const backend = renderer.backend;
  38669. this._gl = renderer.getContext();
  38670. const gl = this._gl;
  38671. const attributes = gl.getContextAttributes();
  38672. this._session = session;
  38673. if ( session !== null ) {
  38674. 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.' );
  38675. session.addEventListener( 'select', this._onSessionEvent );
  38676. session.addEventListener( 'selectstart', this._onSessionEvent );
  38677. session.addEventListener( 'selectend', this._onSessionEvent );
  38678. session.addEventListener( 'squeeze', this._onSessionEvent );
  38679. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38680. session.addEventListener( 'squeezeend', this._onSessionEvent );
  38681. session.addEventListener( 'end', this._onSessionEnd );
  38682. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38683. await backend.makeXRCompatible();
  38684. this._currentPixelRatio = renderer.getPixelRatio();
  38685. renderer.getSize( this._currentSize );
  38686. this._currentAnimationContext = renderer._animation.getContext();
  38687. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  38688. renderer._animation.stop();
  38689. //
  38690. if ( this._supportsLayers === true ) {
  38691. // default path using XRProjectionLayer
  38692. let depthFormat = null;
  38693. let depthType = null;
  38694. let glDepthFormat = null;
  38695. if ( renderer.depth ) {
  38696. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38697. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  38698. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  38699. }
  38700. const projectionlayerInit = {
  38701. colorFormat: gl.RGBA8,
  38702. depthFormat: glDepthFormat,
  38703. scaleFactor: this._framebufferScaleFactor,
  38704. clearOnAccess: false
  38705. };
  38706. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  38707. projectionlayerInit.textureType = 'texture-array';
  38708. this._useMultiview = true;
  38709. }
  38710. this._glBinding = this.getBinding();
  38711. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  38712. const layersArray = [ glProjLayer ];
  38713. this._glProjLayer = glProjLayer;
  38714. renderer.setPixelRatio( 1 );
  38715. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  38716. const depth = this._useMultiview ? 2 : 1;
  38717. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  38718. this._xrRenderTarget = new XRRenderTarget(
  38719. glProjLayer.textureWidth,
  38720. glProjLayer.textureHeight,
  38721. {
  38722. format: RGBAFormat,
  38723. type: UnsignedByteType,
  38724. colorSpace: renderer.outputColorSpace,
  38725. depthTexture: depthTexture,
  38726. stencilBuffer: renderer.stencil,
  38727. samples: attributes.antialias ? 4 : 0,
  38728. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38729. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38730. depth: this._useMultiview ? 2 : 1,
  38731. multiview: this._useMultiview
  38732. } );
  38733. this._xrRenderTarget._hasExternalTextures = true;
  38734. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  38735. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  38736. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38737. if ( this._sessionUsesLayers ) {
  38738. // switch layers to native
  38739. for ( const layer of this._layers ) {
  38740. // change material so it "punches" out a hole to show the XR Layer.
  38741. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  38742. layer.plane.material.blending = CustomBlending;
  38743. layer.plane.material.blendEquation = AddEquation;
  38744. layer.plane.material.blendSrc = ZeroFactor;
  38745. layer.plane.material.blendDst = ZeroFactor;
  38746. layer.xrlayer = this._createXRLayer( layer );
  38747. layersArray.unshift( layer.xrlayer );
  38748. }
  38749. }
  38750. session.updateRenderState( { layers: layersArray } );
  38751. } else {
  38752. // fallback to XRWebGLLayer
  38753. const layerInit = {
  38754. antialias: renderer.currentSamples > 0,
  38755. alpha: true,
  38756. depth: renderer.depth,
  38757. stencil: renderer.stencil,
  38758. framebufferScaleFactor: this.getFramebufferScaleFactor()
  38759. };
  38760. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38761. this._glBaseLayer = glBaseLayer;
  38762. session.updateRenderState( { baseLayer: glBaseLayer } );
  38763. renderer.setPixelRatio( 1 );
  38764. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  38765. this._xrRenderTarget = new XRRenderTarget(
  38766. glBaseLayer.framebufferWidth,
  38767. glBaseLayer.framebufferHeight,
  38768. {
  38769. format: RGBAFormat,
  38770. type: UnsignedByteType,
  38771. colorSpace: renderer.outputColorSpace,
  38772. stencilBuffer: renderer.stencil,
  38773. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38774. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38775. }
  38776. );
  38777. this._xrRenderTarget._isOpaqueFramebuffer = true;
  38778. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38779. }
  38780. //
  38781. this.setFoveation( this.getFoveation() );
  38782. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  38783. renderer._animation.setContext( session );
  38784. renderer._animation.start();
  38785. this.isPresenting = true;
  38786. this.dispatchEvent( { type: 'sessionstart' } );
  38787. }
  38788. }
  38789. /**
  38790. * This method is called by the renderer per frame and updates the XR camera
  38791. * and it sub cameras based on the given camera. The given camera is the "user"
  38792. * camera created on application level and used for non-XR rendering.
  38793. *
  38794. * @param {PerspectiveCamera} camera - The camera.
  38795. */
  38796. updateCamera( camera ) {
  38797. const session = this._session;
  38798. if ( session === null ) return;
  38799. const depthNear = camera.near;
  38800. const depthFar = camera.far;
  38801. const cameraXR = this._cameraXR;
  38802. const cameraL = this._cameraL;
  38803. const cameraR = this._cameraR;
  38804. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38805. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38806. cameraXR.isMultiViewCamera = this._useMultiview;
  38807. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  38808. // Note that the new renderState won't apply until the next frame. See #18320
  38809. session.updateRenderState( {
  38810. depthNear: cameraXR.near,
  38811. depthFar: cameraXR.far
  38812. } );
  38813. this._currentDepthNear = cameraXR.near;
  38814. this._currentDepthFar = cameraXR.far;
  38815. }
  38816. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  38817. cameraXR.layers.mask = camera.layers.mask | 0b110;
  38818. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  38819. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  38820. const parent = camera.parent;
  38821. const cameras = cameraXR.cameras;
  38822. updateCamera( cameraXR, parent );
  38823. for ( let i = 0; i < cameras.length; i ++ ) {
  38824. updateCamera( cameras[ i ], parent );
  38825. }
  38826. // update projection matrix for proper view frustum culling
  38827. if ( cameras.length === 2 ) {
  38828. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38829. } else {
  38830. // assume single camera setup (AR)
  38831. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38832. }
  38833. // update user camera and its children
  38834. updateUserCamera( camera, cameraXR, parent );
  38835. }
  38836. /**
  38837. * Returns a WebXR controller for the given controller index.
  38838. *
  38839. * @private
  38840. * @param {number} index - The controller index.
  38841. * @return {WebXRController} The XR controller.
  38842. */
  38843. _getController( index ) {
  38844. let controller = this._controllers[ index ];
  38845. if ( controller === undefined ) {
  38846. controller = new WebXRController();
  38847. this._controllers[ index ] = controller;
  38848. }
  38849. return controller;
  38850. }
  38851. }
  38852. /**
  38853. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38854. * the cameras' projection and world matrices have already been set.
  38855. * And that near and far planes are identical for both cameras.
  38856. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38857. *
  38858. * @param {ArrayCamera} camera - The camera to update.
  38859. * @param {PerspectiveCamera} cameraL - The left camera.
  38860. * @param {PerspectiveCamera} cameraR - The right camera.
  38861. */
  38862. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38863. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38864. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38865. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  38866. const projL = cameraL.projectionMatrix.elements;
  38867. const projR = cameraR.projectionMatrix.elements;
  38868. // VR systems will have identical far and near planes, and
  38869. // most likely identical top and bottom frustum extents.
  38870. // Use the left camera for these values.
  38871. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38872. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38873. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38874. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38875. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38876. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38877. const left = near * leftFov;
  38878. const right = near * rightFov;
  38879. // Calculate the new camera's position offset from the
  38880. // left camera. xOffset should be roughly half `ipd`.
  38881. const zOffset = ipd / ( - leftFov + rightFov );
  38882. const xOffset = zOffset * - leftFov;
  38883. // TODO: Better way to apply this offset?
  38884. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38885. camera.translateX( xOffset );
  38886. camera.translateZ( zOffset );
  38887. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38888. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38889. // Check if the projection uses an infinite far plane.
  38890. if ( projL[ 10 ] === -1 ) {
  38891. // Use the projection matrix from the left eye.
  38892. // The camera offset is sufficient to include the view volumes
  38893. // of both eyes (assuming symmetric projections).
  38894. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38895. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38896. } else {
  38897. // Find the union of the frustum values of the cameras and scale
  38898. // the values so that the near plane's position does not change in world space,
  38899. // although must now be relative to the new union camera.
  38900. const near2 = near + zOffset;
  38901. const far2 = far + zOffset;
  38902. const left2 = left - xOffset;
  38903. const right2 = right + ( ipd - xOffset );
  38904. const top2 = topFov * far / far2 * near2;
  38905. const bottom2 = bottomFov * far / far2 * near2;
  38906. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38907. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38908. }
  38909. }
  38910. /**
  38911. * Updates the world matrices for the given camera based on the parent 3D object.
  38912. *
  38913. * @inner
  38914. * @param {Camera} camera - The camera to update.
  38915. * @param {Object3D} parent - The parent 3D object.
  38916. */
  38917. function updateCamera( camera, parent ) {
  38918. if ( parent === null ) {
  38919. camera.matrixWorld.copy( camera.matrix );
  38920. } else {
  38921. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38922. }
  38923. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38924. }
  38925. /**
  38926. * Updates the given camera with the transformation of the XR camera and parent object.
  38927. *
  38928. * @inner
  38929. * @param {Camera} camera - The camera to update.
  38930. * @param {ArrayCamera} cameraXR - The XR camera.
  38931. * @param {Object3D} parent - The parent 3D object.
  38932. */
  38933. function updateUserCamera( camera, cameraXR, parent ) {
  38934. if ( parent === null ) {
  38935. camera.matrix.copy( cameraXR.matrixWorld );
  38936. } else {
  38937. camera.matrix.copy( parent.matrixWorld );
  38938. camera.matrix.invert();
  38939. camera.matrix.multiply( cameraXR.matrixWorld );
  38940. }
  38941. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38942. camera.updateMatrixWorld( true );
  38943. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38944. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38945. if ( camera.isPerspectiveCamera ) {
  38946. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38947. camera.zoom = 1;
  38948. }
  38949. }
  38950. function onSessionEvent( event ) {
  38951. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38952. if ( controllerIndex === -1 ) {
  38953. return;
  38954. }
  38955. const controller = this._controllers[ controllerIndex ];
  38956. if ( controller !== undefined ) {
  38957. const referenceSpace = this.getReferenceSpace();
  38958. controller.update( event.inputSource, event.frame, referenceSpace );
  38959. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38960. }
  38961. }
  38962. function onSessionEnd() {
  38963. const session = this._session;
  38964. const renderer = this._renderer;
  38965. session.removeEventListener( 'select', this._onSessionEvent );
  38966. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38967. session.removeEventListener( 'selectend', this._onSessionEvent );
  38968. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38969. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38970. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38971. session.removeEventListener( 'end', this._onSessionEnd );
  38972. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38973. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38974. const inputSource = this._controllerInputSources[ i ];
  38975. if ( inputSource === null ) continue;
  38976. this._controllerInputSources[ i ] = null;
  38977. this._controllers[ i ].disconnect( inputSource );
  38978. }
  38979. this._currentDepthNear = null;
  38980. this._currentDepthFar = null;
  38981. // restore framebuffer/rendering state
  38982. renderer._resetXRState();
  38983. this._session = null;
  38984. this._xrRenderTarget = null;
  38985. this._glBinding = null;
  38986. this._glBaseLayer = null;
  38987. this._glProjLayer = null;
  38988. // switch layers back to emulated
  38989. if ( this._sessionUsesLayers === true ) {
  38990. for ( const layer of this._layers ) {
  38991. // Recreate layer render target to reset state
  38992. layer.renderTarget = new XRRenderTarget(
  38993. layer.pixelwidth,
  38994. layer.pixelheight,
  38995. {
  38996. format: RGBAFormat,
  38997. type: UnsignedByteType,
  38998. depthTexture: new DepthTexture(
  38999. layer.pixelwidth,
  39000. layer.pixelheight,
  39001. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  39002. undefined,
  39003. undefined,
  39004. undefined,
  39005. undefined,
  39006. undefined,
  39007. undefined,
  39008. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  39009. ),
  39010. stencilBuffer: layer.stencilBuffer,
  39011. resolveDepthBuffer: false,
  39012. resolveStencilBuffer: false
  39013. } );
  39014. layer.renderTarget.isXRRenderTarget = false;
  39015. layer.plane.material = layer.material;
  39016. layer.material.map = layer.renderTarget.texture;
  39017. layer.material.map.offset.y = 1;
  39018. layer.material.map.repeat.y = -1;
  39019. delete layer.xrlayer;
  39020. }
  39021. }
  39022. //
  39023. this.isPresenting = false;
  39024. this._useMultiview = false;
  39025. renderer._animation.stop();
  39026. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  39027. renderer._animation.setContext( this._currentAnimationContext );
  39028. renderer._animation.start();
  39029. renderer.setPixelRatio( this._currentPixelRatio );
  39030. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  39031. this.dispatchEvent( { type: 'sessionend' } );
  39032. }
  39033. function onInputSourcesChange( event ) {
  39034. const controllers = this._controllers;
  39035. const controllerInputSources = this._controllerInputSources;
  39036. // Notify disconnected
  39037. for ( let i = 0; i < event.removed.length; i ++ ) {
  39038. const inputSource = event.removed[ i ];
  39039. const index = controllerInputSources.indexOf( inputSource );
  39040. if ( index >= 0 ) {
  39041. controllerInputSources[ index ] = null;
  39042. controllers[ index ].disconnect( inputSource );
  39043. }
  39044. }
  39045. // Notify connected
  39046. for ( let i = 0; i < event.added.length; i ++ ) {
  39047. const inputSource = event.added[ i ];
  39048. let controllerIndex = controllerInputSources.indexOf( inputSource );
  39049. if ( controllerIndex === -1 ) {
  39050. // Assign input source a controller that currently has no input source
  39051. for ( let i = 0; i < controllers.length; i ++ ) {
  39052. if ( i >= controllerInputSources.length ) {
  39053. controllerInputSources.push( inputSource );
  39054. controllerIndex = i;
  39055. break;
  39056. } else if ( controllerInputSources[ i ] === null ) {
  39057. controllerInputSources[ i ] = inputSource;
  39058. controllerIndex = i;
  39059. break;
  39060. }
  39061. }
  39062. // If all controllers do currently receive input we ignore new ones
  39063. if ( controllerIndex === -1 ) break;
  39064. }
  39065. const controller = controllers[ controllerIndex ];
  39066. if ( controller ) {
  39067. controller.connect( inputSource );
  39068. }
  39069. }
  39070. }
  39071. // Creation method for native WebXR layers
  39072. function createXRLayer( layer ) {
  39073. if ( layer.type === 'quad' ) {
  39074. return this._glBinding.createQuadLayer( {
  39075. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39076. width: layer.width / 2,
  39077. height: layer.height / 2,
  39078. space: this._referenceSpace,
  39079. viewPixelWidth: layer.pixelwidth,
  39080. viewPixelHeight: layer.pixelheight,
  39081. clearOnAccess: false
  39082. } );
  39083. } else {
  39084. return this._glBinding.createCylinderLayer( {
  39085. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39086. radius: layer.radius,
  39087. centralAngle: layer.centralAngle,
  39088. aspectRatio: layer.aspectRatio,
  39089. space: this._referenceSpace,
  39090. viewPixelWidth: layer.pixelwidth,
  39091. viewPixelHeight: layer.pixelheight,
  39092. clearOnAccess: false
  39093. } );
  39094. }
  39095. }
  39096. // Animation Loop
  39097. function onAnimationFrame( time, frame ) {
  39098. if ( frame === undefined ) return;
  39099. const cameraXR = this._cameraXR;
  39100. const renderer = this._renderer;
  39101. const backend = renderer.backend;
  39102. const glBaseLayer = this._glBaseLayer;
  39103. const referenceSpace = this.getReferenceSpace();
  39104. const pose = frame.getViewerPose( referenceSpace );
  39105. this._xrFrame = frame;
  39106. if ( pose !== null ) {
  39107. const views = pose.views;
  39108. if ( this._glBaseLayer !== null ) {
  39109. backend.setXRTarget( glBaseLayer.framebuffer );
  39110. }
  39111. let cameraXRNeedsUpdate = false;
  39112. // check if it's necessary to rebuild cameraXR's camera list
  39113. if ( views.length !== cameraXR.cameras.length ) {
  39114. cameraXR.cameras.length = 0;
  39115. cameraXRNeedsUpdate = true;
  39116. }
  39117. for ( let i = 0; i < views.length; i ++ ) {
  39118. const view = views[ i ];
  39119. let viewport;
  39120. if ( this._supportsLayers === true ) {
  39121. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  39122. viewport = glSubImage.viewport;
  39123. // For side-by-side projection, we only produce a single texture for both eyes.
  39124. if ( i === 0 ) {
  39125. backend.setXRRenderTargetTextures(
  39126. this._xrRenderTarget,
  39127. glSubImage.colorTexture,
  39128. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  39129. );
  39130. }
  39131. } else {
  39132. viewport = glBaseLayer.getViewport( view );
  39133. }
  39134. let camera = this._cameras[ i ];
  39135. if ( camera === undefined ) {
  39136. camera = new PerspectiveCamera();
  39137. camera.layers.enable( i );
  39138. camera.viewport = new Vector4();
  39139. this._cameras[ i ] = camera;
  39140. }
  39141. camera.matrix.fromArray( view.transform.matrix );
  39142. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39143. camera.projectionMatrix.fromArray( view.projectionMatrix );
  39144. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39145. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  39146. if ( i === 0 ) {
  39147. cameraXR.matrix.copy( camera.matrix );
  39148. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  39149. }
  39150. if ( cameraXRNeedsUpdate === true ) {
  39151. cameraXR.cameras.push( camera );
  39152. }
  39153. }
  39154. renderer.setOutputRenderTarget( this._xrRenderTarget );
  39155. }
  39156. //
  39157. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39158. const inputSource = this._controllerInputSources[ i ];
  39159. const controller = this._controllers[ i ];
  39160. if ( inputSource !== null && controller !== undefined ) {
  39161. controller.update( inputSource, frame, referenceSpace );
  39162. }
  39163. }
  39164. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  39165. if ( frame.detectedPlanes ) {
  39166. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  39167. }
  39168. this._xrFrame = null;
  39169. }
  39170. /**
  39171. * CanvasTarget is a class that represents the final output destination of the renderer.
  39172. *
  39173. * @augments EventDispatcher
  39174. */
  39175. class CanvasTarget extends EventDispatcher {
  39176. /**
  39177. * Constructs a new CanvasTarget.
  39178. *
  39179. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  39180. */
  39181. constructor( domElement ) {
  39182. super();
  39183. /**
  39184. * A reference to the canvas element the renderer is drawing to.
  39185. * This value of this property will automatically be created by
  39186. * the renderer.
  39187. *
  39188. * @type {HTMLCanvasElement|OffscreenCanvas}
  39189. */
  39190. this.domElement = domElement;
  39191. /**
  39192. * The renderer's pixel ratio.
  39193. *
  39194. * @private
  39195. * @type {number}
  39196. * @default 1
  39197. */
  39198. this._pixelRatio = 1;
  39199. /**
  39200. * The width of the renderer's default framebuffer in logical pixel unit.
  39201. *
  39202. * @private
  39203. * @type {number}
  39204. */
  39205. this._width = this.domElement.width;
  39206. /**
  39207. * The height of the renderer's default framebuffer in logical pixel unit.
  39208. *
  39209. * @private
  39210. * @type {number}
  39211. */
  39212. this._height = this.domElement.height;
  39213. /**
  39214. * The viewport of the renderer in logical pixel unit.
  39215. *
  39216. * @private
  39217. * @type {Vector4}
  39218. */
  39219. this._viewport = new Vector4( 0, 0, this._width, this._height );
  39220. /**
  39221. * The scissor rectangle of the renderer in logical pixel unit.
  39222. *
  39223. * @private
  39224. * @type {Vector4}
  39225. */
  39226. this._scissor = new Vector4( 0, 0, this._width, this._height );
  39227. /**
  39228. * Whether the scissor test should be enabled or not.
  39229. *
  39230. * @private
  39231. * @type {boolean}
  39232. */
  39233. this._scissorTest = false;
  39234. /**
  39235. * The color texture of the default framebuffer.
  39236. *
  39237. * @type {FramebufferTexture}
  39238. */
  39239. this.colorTexture = new FramebufferTexture();
  39240. /**
  39241. * The depth texture of the default framebuffer.
  39242. *
  39243. * @type {DepthTexture}
  39244. */
  39245. this.depthTexture = new DepthTexture();
  39246. }
  39247. /**
  39248. * Returns the pixel ratio.
  39249. *
  39250. * @return {number} The pixel ratio.
  39251. */
  39252. getPixelRatio() {
  39253. return this._pixelRatio;
  39254. }
  39255. /**
  39256. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39257. *
  39258. * @param {Vector2} target - The method writes the result in this target object.
  39259. * @return {Vector2} The drawing buffer size.
  39260. */
  39261. getDrawingBufferSize( target ) {
  39262. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39263. }
  39264. /**
  39265. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39266. *
  39267. * @param {Vector2} target - The method writes the result in this target object.
  39268. * @return {Vector2} The renderer's size in logical pixels.
  39269. */
  39270. getSize( target ) {
  39271. return target.set( this._width, this._height );
  39272. }
  39273. /**
  39274. * Sets the given pixel ratio and resizes the canvas if necessary.
  39275. *
  39276. * @param {number} [value=1] - The pixel ratio.
  39277. */
  39278. setPixelRatio( value = 1 ) {
  39279. if ( this._pixelRatio === value ) return;
  39280. this._pixelRatio = value;
  39281. this.setSize( this._width, this._height, false );
  39282. }
  39283. /**
  39284. * This method allows to define the drawing buffer size by specifying
  39285. * width, height and pixel ratio all at once. The size of the drawing
  39286. * buffer is computed with this formula:
  39287. * ```js
  39288. * size.x = width * pixelRatio;
  39289. * size.y = height * pixelRatio;
  39290. * ```
  39291. *
  39292. * @param {number} width - The width in logical pixels.
  39293. * @param {number} height - The height in logical pixels.
  39294. * @param {number} pixelRatio - The pixel ratio.
  39295. */
  39296. setDrawingBufferSize( width, height, pixelRatio ) {
  39297. // Renderer can't be resized while presenting in XR.
  39298. if ( this.xr && this.xr.isPresenting ) return;
  39299. this._width = width;
  39300. this._height = height;
  39301. this._pixelRatio = pixelRatio;
  39302. this.domElement.width = Math.floor( width * pixelRatio );
  39303. this.domElement.height = Math.floor( height * pixelRatio );
  39304. this.setViewport( 0, 0, width, height );
  39305. this._dispatchResize();
  39306. }
  39307. /**
  39308. * Sets the size of the renderer.
  39309. *
  39310. * @param {number} width - The width in logical pixels.
  39311. * @param {number} height - The height in logical pixels.
  39312. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39313. */
  39314. setSize( width, height, updateStyle = true ) {
  39315. // Renderer can't be resized while presenting in XR.
  39316. if ( this.xr && this.xr.isPresenting ) return;
  39317. this._width = width;
  39318. this._height = height;
  39319. this.domElement.width = Math.floor( width * this._pixelRatio );
  39320. this.domElement.height = Math.floor( height * this._pixelRatio );
  39321. if ( updateStyle === true ) {
  39322. this.domElement.style.width = width + 'px';
  39323. this.domElement.style.height = height + 'px';
  39324. }
  39325. this.setViewport( 0, 0, width, height );
  39326. this._dispatchResize();
  39327. }
  39328. /**
  39329. * Returns the scissor rectangle.
  39330. *
  39331. * @param {Vector4} target - The method writes the result in this target object.
  39332. * @return {Vector4} The scissor rectangle.
  39333. */
  39334. getScissor( target ) {
  39335. const scissor = this._scissor;
  39336. target.x = scissor.x;
  39337. target.y = scissor.y;
  39338. target.width = scissor.width;
  39339. target.height = scissor.height;
  39340. return target;
  39341. }
  39342. /**
  39343. * Defines the scissor rectangle.
  39344. *
  39345. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39346. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39347. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39348. * @param {number} width - The width of the scissor box in logical pixel unit.
  39349. * @param {number} height - The height of the scissor box in logical pixel unit.
  39350. */
  39351. setScissor( x, y, width, height ) {
  39352. const scissor = this._scissor;
  39353. if ( x.isVector4 ) {
  39354. scissor.copy( x );
  39355. } else {
  39356. scissor.set( x, y, width, height );
  39357. }
  39358. }
  39359. /**
  39360. * Returns the scissor test value.
  39361. *
  39362. * @return {boolean} Whether the scissor test should be enabled or not.
  39363. */
  39364. getScissorTest() {
  39365. return this._scissorTest;
  39366. }
  39367. /**
  39368. * Defines the scissor test.
  39369. *
  39370. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39371. */
  39372. setScissorTest( boolean ) {
  39373. this._scissorTest = boolean;
  39374. }
  39375. /**
  39376. * Returns the viewport definition.
  39377. *
  39378. * @param {Vector4} target - The method writes the result in this target object.
  39379. * @return {Vector4} The viewport definition.
  39380. */
  39381. getViewport( target ) {
  39382. return target.copy( this._viewport );
  39383. }
  39384. /**
  39385. * Defines the viewport.
  39386. *
  39387. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39388. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39389. * @param {number} width - The width of the viewport in logical pixel unit.
  39390. * @param {number} height - The height of the viewport in logical pixel unit.
  39391. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39392. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39393. */
  39394. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39395. const viewport = this._viewport;
  39396. if ( x.isVector4 ) {
  39397. viewport.copy( x );
  39398. } else {
  39399. viewport.set( x, y, width, height );
  39400. }
  39401. viewport.minDepth = minDepth;
  39402. viewport.maxDepth = maxDepth;
  39403. }
  39404. /**
  39405. * Dispatches the resize event.
  39406. *
  39407. * @private
  39408. */
  39409. _dispatchResize() {
  39410. this.dispatchEvent( { type: 'resize' } );
  39411. }
  39412. /**
  39413. * Frees the GPU-related resources allocated by this instance. Call this
  39414. * method whenever this instance is no longer used in your app.
  39415. *
  39416. * @fires RenderTarget#dispose
  39417. */
  39418. dispose() {
  39419. this.dispatchEvent( { type: 'dispose' } );
  39420. }
  39421. }
  39422. const _scene = /*@__PURE__*/ new Scene();
  39423. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  39424. const _screen = /*@__PURE__*/ new Vector4();
  39425. const _frustum = /*@__PURE__*/ new Frustum();
  39426. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  39427. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  39428. const _vector4 = /*@__PURE__*/ new Vector4();
  39429. /**
  39430. * Base class for renderers.
  39431. */
  39432. class Renderer {
  39433. /**
  39434. * Renderer options.
  39435. *
  39436. * @typedef {Object} Renderer~Options
  39437. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  39438. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  39439. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  39440. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  39441. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  39442. * @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
  39443. * to overwrite the default.
  39444. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39445. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  39446. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  39447. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  39448. */
  39449. /**
  39450. * Constructs a new renderer.
  39451. *
  39452. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  39453. * @param {Renderer~Options} [parameters] - The configuration parameter.
  39454. */
  39455. constructor( backend, parameters = {} ) {
  39456. /**
  39457. * This flag can be used for type testing.
  39458. *
  39459. * @type {boolean}
  39460. * @readonly
  39461. * @default true
  39462. */
  39463. this.isRenderer = true;
  39464. //
  39465. const {
  39466. logarithmicDepthBuffer = false,
  39467. alpha = true,
  39468. depth = true,
  39469. stencil = false,
  39470. antialias = false,
  39471. samples = 0,
  39472. getFallback = null,
  39473. colorBufferType = HalfFloatType,
  39474. multiview = false
  39475. } = parameters;
  39476. /**
  39477. * A reference to the current backend.
  39478. *
  39479. * @type {Backend}
  39480. */
  39481. this.backend = backend;
  39482. /**
  39483. * Whether the renderer should automatically clear the current rendering target
  39484. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  39485. * or the current bound render target (custom framebuffer).
  39486. *
  39487. * @type {boolean}
  39488. * @default true
  39489. */
  39490. this.autoClear = true;
  39491. /**
  39492. * When `autoClear` is set to `true`, this property defines whether the renderer
  39493. * should clear the color buffer.
  39494. *
  39495. * @type {boolean}
  39496. * @default true
  39497. */
  39498. this.autoClearColor = true;
  39499. /**
  39500. * When `autoClear` is set to `true`, this property defines whether the renderer
  39501. * should clear the depth buffer.
  39502. *
  39503. * @type {boolean}
  39504. * @default true
  39505. */
  39506. this.autoClearDepth = true;
  39507. /**
  39508. * When `autoClear` is set to `true`, this property defines whether the renderer
  39509. * should clear the stencil buffer.
  39510. *
  39511. * @type {boolean}
  39512. * @default true
  39513. */
  39514. this.autoClearStencil = true;
  39515. /**
  39516. * Whether the default framebuffer should be transparent or opaque.
  39517. *
  39518. * @type {boolean}
  39519. * @default true
  39520. */
  39521. this.alpha = alpha;
  39522. /**
  39523. * Whether logarithmic depth buffer is enabled or not.
  39524. *
  39525. * @type {boolean}
  39526. * @default false
  39527. */
  39528. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  39529. /**
  39530. * Defines the output color space of the renderer.
  39531. *
  39532. * @type {string}
  39533. * @default SRGBColorSpace
  39534. */
  39535. this.outputColorSpace = SRGBColorSpace;
  39536. /**
  39537. * Defines the tone mapping of the renderer.
  39538. *
  39539. * @type {number}
  39540. * @default NoToneMapping
  39541. */
  39542. this.toneMapping = NoToneMapping;
  39543. /**
  39544. * Defines the tone mapping exposure.
  39545. *
  39546. * @type {number}
  39547. * @default 1
  39548. */
  39549. this.toneMappingExposure = 1.0;
  39550. /**
  39551. * Whether the renderer should sort its render lists or not.
  39552. *
  39553. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  39554. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  39555. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  39556. * e.g. manually determining each object's rendering order.
  39557. *
  39558. * @type {boolean}
  39559. * @default true
  39560. */
  39561. this.sortObjects = true;
  39562. /**
  39563. * Whether the default framebuffer should have a depth buffer or not.
  39564. *
  39565. * @type {boolean}
  39566. * @default true
  39567. */
  39568. this.depth = depth;
  39569. /**
  39570. * Whether the default framebuffer should have a stencil buffer or not.
  39571. *
  39572. * @type {boolean}
  39573. * @default false
  39574. */
  39575. this.stencil = stencil;
  39576. /**
  39577. * Holds a series of statistical information about the GPU memory
  39578. * and the rendering process. Useful for debugging and monitoring.
  39579. *
  39580. * @type {Info}
  39581. */
  39582. this.info = new Info();
  39583. /**
  39584. * Stores override nodes for specific transformations or calculations.
  39585. * These nodes can be used to replace default behavior in the rendering pipeline.
  39586. *
  39587. * @type {Object}
  39588. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  39589. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  39590. */
  39591. this.overrideNodes = {
  39592. modelViewMatrix: null,
  39593. modelNormalViewMatrix: null
  39594. };
  39595. /**
  39596. * The node library defines how certain library objects like materials, lights
  39597. * or tone mapping functions are mapped to node types. This is required since
  39598. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  39599. * be part of the scene graph, they are internally represented as nodes for
  39600. * further processing.
  39601. *
  39602. * @type {NodeLibrary}
  39603. */
  39604. this.library = new NodeLibrary();
  39605. /**
  39606. * A map-like data structure for managing lights.
  39607. *
  39608. * @type {Lighting}
  39609. */
  39610. this.lighting = new Lighting();
  39611. // internals
  39612. /**
  39613. * The number of MSAA samples.
  39614. *
  39615. * @private
  39616. * @type {number}
  39617. * @default 0
  39618. */
  39619. this._samples = samples || ( antialias === true ) ? 4 : 0;
  39620. /**
  39621. * OnCanvasTargetResize callback function.
  39622. *
  39623. * @private
  39624. * @type {Function}
  39625. */
  39626. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  39627. /**
  39628. * The canvas target for rendering.
  39629. *
  39630. * @private
  39631. * @type {CanvasTarget}
  39632. */
  39633. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  39634. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  39635. this._canvasTarget.isDefaultCanvasTarget = true;
  39636. /**
  39637. * The inspector provides information about the internal renderer state.
  39638. *
  39639. * @private
  39640. * @type {InspectorBase}
  39641. */
  39642. this._inspector = new InspectorBase();
  39643. this._inspector.setRenderer( this );
  39644. /**
  39645. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39646. *
  39647. * @private
  39648. * @type {?Function}
  39649. */
  39650. this._getFallback = getFallback;
  39651. /**
  39652. * A reference to a renderer module for managing shader attributes.
  39653. *
  39654. * @private
  39655. * @type {?Attributes}
  39656. * @default null
  39657. */
  39658. this._attributes = null;
  39659. /**
  39660. * A reference to a renderer module for managing geometries.
  39661. *
  39662. * @private
  39663. * @type {?Geometries}
  39664. * @default null
  39665. */
  39666. this._geometries = null;
  39667. /**
  39668. * A reference to a renderer module for managing node related logic.
  39669. *
  39670. * @private
  39671. * @type {?Nodes}
  39672. * @default null
  39673. */
  39674. this._nodes = null;
  39675. /**
  39676. * A reference to a renderer module for managing the internal animation loop.
  39677. *
  39678. * @private
  39679. * @type {?Animation}
  39680. * @default null
  39681. */
  39682. this._animation = null;
  39683. /**
  39684. * A reference to a renderer module for managing shader program bindings.
  39685. *
  39686. * @private
  39687. * @type {?Bindings}
  39688. * @default null
  39689. */
  39690. this._bindings = null;
  39691. /**
  39692. * A reference to a renderer module for managing render objects.
  39693. *
  39694. * @private
  39695. * @type {?RenderObjects}
  39696. * @default null
  39697. */
  39698. this._objects = null;
  39699. /**
  39700. * A reference to a renderer module for managing render and compute pipelines.
  39701. *
  39702. * @private
  39703. * @type {?Pipelines}
  39704. * @default null
  39705. */
  39706. this._pipelines = null;
  39707. /**
  39708. * A reference to a renderer module for managing render bundles.
  39709. *
  39710. * @private
  39711. * @type {?RenderBundles}
  39712. * @default null
  39713. */
  39714. this._bundles = null;
  39715. /**
  39716. * A reference to a renderer module for managing render lists.
  39717. *
  39718. * @private
  39719. * @type {?RenderLists}
  39720. * @default null
  39721. */
  39722. this._renderLists = null;
  39723. /**
  39724. * A reference to a renderer module for managing render contexts.
  39725. *
  39726. * @private
  39727. * @type {?RenderContexts}
  39728. * @default null
  39729. */
  39730. this._renderContexts = null;
  39731. /**
  39732. * A reference to a renderer module for managing textures.
  39733. *
  39734. * @private
  39735. * @type {?Textures}
  39736. * @default null
  39737. */
  39738. this._textures = null;
  39739. /**
  39740. * A reference to a renderer module for backgrounds.
  39741. *
  39742. * @private
  39743. * @type {?Background}
  39744. * @default null
  39745. */
  39746. this._background = null;
  39747. /**
  39748. * This fullscreen quad is used for internal render passes
  39749. * like the tone mapping and color space output pass.
  39750. *
  39751. * @private
  39752. * @type {QuadMesh}
  39753. */
  39754. this._quad = new QuadMesh( new NodeMaterial() );
  39755. this._quad.name = 'Output Color Transform';
  39756. this._quad.material.name = 'outputColorTransform';
  39757. /**
  39758. * A reference to the current render context.
  39759. *
  39760. * @private
  39761. * @type {?RenderContext}
  39762. * @default null
  39763. */
  39764. this._currentRenderContext = null;
  39765. /**
  39766. * A custom sort function for the opaque render list.
  39767. *
  39768. * @private
  39769. * @type {?Function}
  39770. * @default null
  39771. */
  39772. this._opaqueSort = null;
  39773. /**
  39774. * A custom sort function for the transparent render list.
  39775. *
  39776. * @private
  39777. * @type {?Function}
  39778. * @default null
  39779. */
  39780. this._transparentSort = null;
  39781. /**
  39782. * The framebuffer target.
  39783. *
  39784. * @private
  39785. * @type {?RenderTarget}
  39786. * @default null
  39787. */
  39788. this._frameBufferTarget = null;
  39789. const alphaClear = this.alpha === true ? 0 : 1;
  39790. /**
  39791. * The clear color value.
  39792. *
  39793. * @private
  39794. * @type {Color4}
  39795. */
  39796. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  39797. /**
  39798. * The clear depth value.
  39799. *
  39800. * @private
  39801. * @type {number}
  39802. * @default 1
  39803. */
  39804. this._clearDepth = 1;
  39805. /**
  39806. * The clear stencil value.
  39807. *
  39808. * @private
  39809. * @type {number}
  39810. * @default 0
  39811. */
  39812. this._clearStencil = 0;
  39813. /**
  39814. * The current render target.
  39815. *
  39816. * @private
  39817. * @type {?RenderTarget}
  39818. * @default null
  39819. */
  39820. this._renderTarget = null;
  39821. /**
  39822. * The active cube face.
  39823. *
  39824. * @private
  39825. * @type {number}
  39826. * @default 0
  39827. */
  39828. this._activeCubeFace = 0;
  39829. /**
  39830. * The active mipmap level.
  39831. *
  39832. * @private
  39833. * @type {number}
  39834. * @default 0
  39835. */
  39836. this._activeMipmapLevel = 0;
  39837. /**
  39838. * The current output render target.
  39839. *
  39840. * @private
  39841. * @type {?RenderTarget}
  39842. * @default null
  39843. */
  39844. this._outputRenderTarget = null;
  39845. /**
  39846. * The MRT setting.
  39847. *
  39848. * @private
  39849. * @type {?MRTNode}
  39850. * @default null
  39851. */
  39852. this._mrt = null;
  39853. /**
  39854. * This function defines how a render object is going
  39855. * to be rendered.
  39856. *
  39857. * @private
  39858. * @type {?Function}
  39859. * @default null
  39860. */
  39861. this._renderObjectFunction = null;
  39862. /**
  39863. * Used to keep track of the current render object function.
  39864. *
  39865. * @private
  39866. * @type {?Function}
  39867. * @default null
  39868. */
  39869. this._currentRenderObjectFunction = null;
  39870. /**
  39871. * Used to keep track of the current render bundle.
  39872. *
  39873. * @private
  39874. * @type {?RenderBundle}
  39875. * @default null
  39876. */
  39877. this._currentRenderBundle = null;
  39878. /**
  39879. * Next to `_renderObjectFunction()`, this function provides another hook
  39880. * for influencing the render process of a render object. It is meant for internal
  39881. * use and only relevant for `compileAsync()` right now. Instead of using
  39882. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  39883. * a different function might be used which performs no draw but just the node
  39884. * and pipeline updates.
  39885. *
  39886. * @private
  39887. * @type {?Function}
  39888. * @default null
  39889. */
  39890. this._handleObjectFunction = this._renderObjectDirect;
  39891. /**
  39892. * Indicates whether the device has been lost or not. In WebGL terms, the device
  39893. * lost is considered as a context lost. When this is set to `true`, rendering
  39894. * isn't possible anymore.
  39895. *
  39896. * @private
  39897. * @type {boolean}
  39898. * @default false
  39899. */
  39900. this._isDeviceLost = false;
  39901. /**
  39902. * A callback function that defines what should happen when a device/context lost occurs.
  39903. *
  39904. * @type {Function}
  39905. */
  39906. this.onDeviceLost = this._onDeviceLost;
  39907. /**
  39908. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  39909. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  39910. * This will reduce rendering quality though.
  39911. *
  39912. * @private
  39913. * @type {number}
  39914. * @default HalfFloatType
  39915. */
  39916. this._colorBufferType = colorBufferType;
  39917. /**
  39918. * A cache for shadow nodes per material
  39919. *
  39920. * @private
  39921. * @type {WeakMap<Material, Object>}
  39922. */
  39923. this._cacheShadowNodes = new WeakMap();
  39924. /**
  39925. * Whether the renderer has been initialized or not.
  39926. *
  39927. * @private
  39928. * @type {boolean}
  39929. * @default false
  39930. */
  39931. this._initialized = false;
  39932. /**
  39933. * A reference to the promise which initializes the renderer.
  39934. *
  39935. * @private
  39936. * @type {?Promise<this>}
  39937. * @default null
  39938. */
  39939. this._initPromise = null;
  39940. /**
  39941. * An array of compilation promises which are used in `compileAsync()`.
  39942. *
  39943. * @private
  39944. * @type {?Array<Promise>}
  39945. * @default null
  39946. */
  39947. this._compilationPromises = null;
  39948. /**
  39949. * Whether the renderer should render transparent render objects or not.
  39950. *
  39951. * @type {boolean}
  39952. * @default true
  39953. */
  39954. this.transparent = true;
  39955. /**
  39956. * Whether the renderer should render opaque render objects or not.
  39957. *
  39958. * @type {boolean}
  39959. * @default true
  39960. */
  39961. this.opaque = true;
  39962. /**
  39963. * Shadow map configuration
  39964. * @typedef {Object} ShadowMapConfig
  39965. * @property {boolean} enabled - Whether to globally enable shadows or not.
  39966. * @property {number} type - The shadow map type.
  39967. */
  39968. /**
  39969. * The renderer's shadow configuration.
  39970. *
  39971. * @type {ShadowMapConfig}
  39972. */
  39973. this.shadowMap = {
  39974. enabled: false,
  39975. type: PCFShadowMap
  39976. };
  39977. /**
  39978. * XR configuration.
  39979. * @typedef {Object} XRConfig
  39980. * @property {boolean} enabled - Whether to globally enable XR or not.
  39981. */
  39982. /**
  39983. * The renderer's XR manager.
  39984. *
  39985. * @type {XRManager}
  39986. */
  39987. this.xr = new XRManager( this, multiview );
  39988. /**
  39989. * Debug configuration.
  39990. * @typedef {Object} DebugConfig
  39991. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  39992. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  39993. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  39994. */
  39995. /**
  39996. * The renderer's debug configuration.
  39997. *
  39998. * @type {DebugConfig}
  39999. */
  40000. this.debug = {
  40001. checkShaderErrors: true,
  40002. onShaderError: null,
  40003. getShaderAsync: async ( scene, camera, object ) => {
  40004. await this.compileAsync( scene, camera );
  40005. const renderList = this._renderLists.get( scene, camera );
  40006. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  40007. const material = scene.overrideMaterial || object.material;
  40008. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  40009. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  40010. return { fragmentShader, vertexShader };
  40011. }
  40012. };
  40013. }
  40014. /**
  40015. * Initializes the renderer so it is ready for usage.
  40016. *
  40017. * @async
  40018. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  40019. */
  40020. async init() {
  40021. if ( this._initPromise !== null ) {
  40022. return this._initPromise;
  40023. }
  40024. this._initPromise = new Promise( async ( resolve, reject ) => {
  40025. let backend = this.backend;
  40026. try {
  40027. await backend.init( this );
  40028. } catch ( error ) {
  40029. if ( this._getFallback !== null ) {
  40030. // try the fallback
  40031. try {
  40032. this.backend = backend = this._getFallback( error );
  40033. await backend.init( this );
  40034. } catch ( error ) {
  40035. reject( error );
  40036. return;
  40037. }
  40038. } else {
  40039. reject( error );
  40040. return;
  40041. }
  40042. }
  40043. this._nodes = new Nodes( this, backend );
  40044. this._animation = new Animation( this, this._nodes, this.info );
  40045. this._attributes = new Attributes( backend );
  40046. this._background = new Background( this, this._nodes );
  40047. this._geometries = new Geometries( this._attributes, this.info );
  40048. this._textures = new Textures( this, backend, this.info );
  40049. this._pipelines = new Pipelines( backend, this._nodes );
  40050. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  40051. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  40052. this._renderLists = new RenderLists( this.lighting );
  40053. this._bundles = new RenderBundles();
  40054. this._renderContexts = new RenderContexts();
  40055. //
  40056. this._animation.start();
  40057. this._initialized = true;
  40058. //
  40059. this._inspector.init();
  40060. //
  40061. resolve( this );
  40062. } );
  40063. return this._initPromise;
  40064. }
  40065. /**
  40066. * A reference to the canvas element the renderer is drawing to.
  40067. * This value of this property will automatically be created by
  40068. * the renderer.
  40069. *
  40070. * @type {HTMLCanvasElement|OffscreenCanvas}
  40071. */
  40072. get domElement() {
  40073. return this._canvasTarget.domElement;
  40074. }
  40075. /**
  40076. * The coordinate system of the renderer. The value of this property
  40077. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  40078. * `THREE.WebGPUCoordinateSystem`.
  40079. *
  40080. * @readonly
  40081. * @type {number}
  40082. */
  40083. get coordinateSystem() {
  40084. return this.backend.coordinateSystem;
  40085. }
  40086. /**
  40087. * Compiles all materials in the given scene. This can be useful to avoid a
  40088. * phenomenon which is called "shader compilation stutter", which occurs when
  40089. * rendering an object with a new shader for the first time.
  40090. *
  40091. * If you want to add a 3D object to an existing scene, use the third optional
  40092. * parameter for applying the target scene. Note that the (target) scene's lighting
  40093. * and environment must be configured before calling this method.
  40094. *
  40095. * @async
  40096. * @param {Object3D} scene - The scene or 3D object to precompile.
  40097. * @param {Camera} camera - The camera that is used to render the scene.
  40098. * @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.
  40099. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  40100. */
  40101. async compileAsync( scene, camera, targetScene = null ) {
  40102. if ( this._isDeviceLost === true ) return;
  40103. if ( this._initialized === false ) await this.init();
  40104. // preserve render tree
  40105. const nodeFrame = this._nodes.nodeFrame;
  40106. const previousRenderId = nodeFrame.renderId;
  40107. const previousRenderContext = this._currentRenderContext;
  40108. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40109. const previousCompilationPromises = this._compilationPromises;
  40110. //
  40111. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40112. if ( targetScene === null ) targetScene = scene;
  40113. const renderTarget = this._renderTarget;
  40114. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  40115. const activeMipmapLevel = this._activeMipmapLevel;
  40116. const compilationPromises = [];
  40117. this._currentRenderContext = renderContext;
  40118. this._currentRenderObjectFunction = this.renderObject;
  40119. this._handleObjectFunction = this._createObjectPipeline;
  40120. this._compilationPromises = compilationPromises;
  40121. nodeFrame.renderId ++;
  40122. //
  40123. nodeFrame.update();
  40124. //
  40125. renderContext.depth = this.depth;
  40126. renderContext.stencil = this.stencil;
  40127. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40128. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40129. //
  40130. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40131. //
  40132. const renderList = this._renderLists.get( scene, camera );
  40133. renderList.begin();
  40134. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40135. // include lights from target scene
  40136. if ( targetScene !== scene ) {
  40137. targetScene.traverseVisible( function ( object ) {
  40138. if ( object.isLight && object.layers.test( camera.layers ) ) {
  40139. renderList.pushLight( object );
  40140. }
  40141. } );
  40142. }
  40143. renderList.finish();
  40144. //
  40145. if ( renderTarget !== null ) {
  40146. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40147. const renderTargetData = this._textures.get( renderTarget );
  40148. renderContext.textures = renderTargetData.textures;
  40149. renderContext.depthTexture = renderTargetData.depthTexture;
  40150. } else {
  40151. renderContext.textures = null;
  40152. renderContext.depthTexture = null;
  40153. }
  40154. //
  40155. this._background.update( sceneRef, renderList, renderContext );
  40156. // process render lists
  40157. const opaqueObjects = renderList.opaque;
  40158. const transparentObjects = renderList.transparent;
  40159. const transparentDoublePassObjects = renderList.transparentDoublePass;
  40160. const lightsNode = renderList.lightsNode;
  40161. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40162. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40163. // restore render tree
  40164. nodeFrame.renderId = previousRenderId;
  40165. this._currentRenderContext = previousRenderContext;
  40166. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40167. this._compilationPromises = previousCompilationPromises;
  40168. this._handleObjectFunction = this._renderObjectDirect;
  40169. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  40170. await Promise.all( compilationPromises );
  40171. }
  40172. /**
  40173. * Renders the scene in an async fashion.
  40174. *
  40175. * @async
  40176. * @deprecated
  40177. * @param {Object3D} scene - The scene or 3D object to render.
  40178. * @param {Camera} camera - The camera.
  40179. * @return {Promise} A Promise that resolves when the render has been finished.
  40180. */
  40181. async renderAsync( scene, camera ) {
  40182. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40183. await this.init();
  40184. this.render( scene, camera );
  40185. }
  40186. /**
  40187. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40188. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40189. *
  40190. * @async
  40191. * @deprecated
  40192. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40193. */
  40194. async waitForGPU() {
  40195. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  40196. }
  40197. //
  40198. /**
  40199. * Sets the inspector instance. The inspector can be any class that extends from `InspectorBase`.
  40200. *
  40201. * @param {InspectorBase} value - The new inspector.
  40202. */
  40203. set inspector( value ) {
  40204. if ( this._inspector !== null ) {
  40205. this._inspector.setRenderer( null );
  40206. }
  40207. this._inspector = value;
  40208. this._inspector.setRenderer( this );
  40209. }
  40210. get inspector() {
  40211. return this._inspector;
  40212. }
  40213. /**
  40214. * Enables or disables high precision for model-view and normal-view matrices.
  40215. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  40216. *
  40217. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  40218. *
  40219. * @param {boolean} value - Whether to enable or disable high precision.
  40220. * @type {boolean}
  40221. */
  40222. set highPrecision( value ) {
  40223. if ( value === true ) {
  40224. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  40225. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  40226. } else if ( this.highPrecision ) {
  40227. this.overrideNodes.modelViewMatrix = null;
  40228. this.overrideNodes.modelNormalViewMatrix = null;
  40229. }
  40230. }
  40231. /**
  40232. * Returns whether high precision is enabled or not.
  40233. *
  40234. * @return {boolean} Whether high precision is enabled or not.
  40235. * @type {boolean}
  40236. */
  40237. get highPrecision() {
  40238. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  40239. }
  40240. /**
  40241. * Sets the given MRT configuration.
  40242. *
  40243. * @param {MRTNode} mrt - The MRT node to set.
  40244. * @return {Renderer} A reference to this renderer.
  40245. */
  40246. setMRT( mrt ) {
  40247. this._mrt = mrt;
  40248. return this;
  40249. }
  40250. /**
  40251. * Returns the MRT configuration.
  40252. *
  40253. * @return {MRTNode} The MRT configuration.
  40254. */
  40255. getMRT() {
  40256. return this._mrt;
  40257. }
  40258. /**
  40259. * Returns the color buffer type.
  40260. *
  40261. * @return {number} The color buffer type.
  40262. */
  40263. getColorBufferType() {
  40264. return this._colorBufferType;
  40265. }
  40266. /**
  40267. * Default implementation of the device lost callback.
  40268. *
  40269. * @private
  40270. * @param {Object} info - Information about the context lost.
  40271. */
  40272. _onDeviceLost( info ) {
  40273. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  40274. if ( info.reason ) {
  40275. errorMessage += `\nReason: ${info.reason}`;
  40276. }
  40277. error( errorMessage );
  40278. this._isDeviceLost = true;
  40279. }
  40280. /**
  40281. * Renders the given render bundle.
  40282. *
  40283. * @private
  40284. * @param {Object} bundle - Render bundle data.
  40285. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  40286. * @param {LightsNode} lightsNode - The lights node.
  40287. */
  40288. _renderBundle( bundle, sceneRef, lightsNode ) {
  40289. const { bundleGroup, camera, renderList } = bundle;
  40290. const renderContext = this._currentRenderContext;
  40291. //
  40292. const renderBundle = this._bundles.get( bundleGroup, camera );
  40293. const renderBundleData = this.backend.get( renderBundle );
  40294. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  40295. //
  40296. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  40297. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  40298. renderBundleData.renderContexts.add( renderContext );
  40299. if ( renderBundleNeedsUpdate ) {
  40300. this.backend.beginBundle( renderContext );
  40301. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  40302. renderBundleData.renderObjects = [];
  40303. }
  40304. this._currentRenderBundle = renderBundle;
  40305. const {
  40306. transparentDoublePass: transparentDoublePassObjects,
  40307. transparent: transparentObjects,
  40308. opaque: opaqueObjects
  40309. } = renderList;
  40310. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40311. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40312. this._currentRenderBundle = null;
  40313. //
  40314. this.backend.finishBundle( renderContext, renderBundle );
  40315. renderBundleData.version = bundleGroup.version;
  40316. } else {
  40317. const { renderObjects } = renderBundleData;
  40318. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  40319. const renderObject = renderObjects[ i ];
  40320. if ( this._nodes.needsRefresh( renderObject ) ) {
  40321. this._nodes.updateBefore( renderObject );
  40322. this._nodes.updateForRender( renderObject );
  40323. this._bindings.updateForRender( renderObject );
  40324. this._nodes.updateAfter( renderObject );
  40325. }
  40326. }
  40327. }
  40328. this.backend.addBundle( renderContext, renderBundle );
  40329. }
  40330. /**
  40331. * Renders the scene or 3D object with the given camera. This method can only be called
  40332. * if the renderer has been initialized. When using `render()` inside an animation loop,
  40333. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  40334. * with {@link Renderer#setAnimationLoop} though.
  40335. *
  40336. * For all other use cases (like when using on-demand rendering), you must call
  40337. * {@link Renderer#init} before rendering.
  40338. *
  40339. * The target of the method is the default framebuffer (meaning the canvas)
  40340. * or alternatively a render target when specified via `setRenderTarget()`.
  40341. *
  40342. * @param {Object3D} scene - The scene or 3D object to render.
  40343. * @param {Camera} camera - The camera to render the scene with.
  40344. */
  40345. render( scene, camera ) {
  40346. if ( this._initialized === false ) {
  40347. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  40348. }
  40349. this._renderScene( scene, camera );
  40350. }
  40351. /**
  40352. * Returns whether the renderer has been initialized or not.
  40353. *
  40354. * @readonly
  40355. * @return {boolean} Whether the renderer has been initialized or not.
  40356. */
  40357. get initialized() {
  40358. return this._initialized;
  40359. }
  40360. /**
  40361. * Returns an internal render target which is used when computing the output tone mapping
  40362. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  40363. * pass and not inline to achieve more correct results.
  40364. *
  40365. * @private
  40366. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  40367. */
  40368. _getFrameBufferTarget() {
  40369. const { currentToneMapping, currentColorSpace } = this;
  40370. const useToneMapping = currentToneMapping !== NoToneMapping;
  40371. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  40372. if ( useToneMapping === false && useColorSpace === false ) return null;
  40373. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  40374. const { depth, stencil } = this;
  40375. let frameBufferTarget = this._frameBufferTarget;
  40376. if ( frameBufferTarget === null ) {
  40377. frameBufferTarget = new RenderTarget( width, height, {
  40378. depthBuffer: depth,
  40379. stencilBuffer: stencil,
  40380. type: this._colorBufferType,
  40381. format: RGBAFormat,
  40382. colorSpace: ColorManagement.workingColorSpace,
  40383. generateMipmaps: false,
  40384. minFilter: LinearFilter,
  40385. magFilter: LinearFilter,
  40386. samples: this.samples
  40387. } );
  40388. frameBufferTarget.isPostProcessingRenderTarget = true;
  40389. this._frameBufferTarget = frameBufferTarget;
  40390. }
  40391. const outputRenderTarget = this.getOutputRenderTarget();
  40392. frameBufferTarget.depthBuffer = depth;
  40393. frameBufferTarget.stencilBuffer = stencil;
  40394. if ( outputRenderTarget !== null ) {
  40395. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  40396. } else {
  40397. frameBufferTarget.setSize( width, height, 1 );
  40398. }
  40399. const canvasTarget = this._canvasTarget;
  40400. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  40401. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  40402. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  40403. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  40404. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  40405. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  40406. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  40407. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  40408. return frameBufferTarget;
  40409. }
  40410. /**
  40411. * Renders the scene or 3D object with the given camera.
  40412. *
  40413. * @private
  40414. * @param {Object3D} scene - The scene or 3D object to render.
  40415. * @param {Camera} camera - The camera to render the scene with.
  40416. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  40417. * @return {RenderContext} The current render context.
  40418. */
  40419. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  40420. if ( this._isDeviceLost === true ) return;
  40421. //
  40422. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  40423. // preserve render tree
  40424. const nodeFrame = this._nodes.nodeFrame;
  40425. const previousRenderId = nodeFrame.renderId;
  40426. const previousRenderContext = this._currentRenderContext;
  40427. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40428. //
  40429. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40430. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  40431. const activeCubeFace = this._activeCubeFace;
  40432. const activeMipmapLevel = this._activeMipmapLevel;
  40433. //
  40434. let renderTarget;
  40435. if ( frameBufferTarget !== null ) {
  40436. renderTarget = frameBufferTarget;
  40437. this.setRenderTarget( renderTarget );
  40438. } else {
  40439. renderTarget = outputRenderTarget;
  40440. }
  40441. //
  40442. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  40443. this._currentRenderContext = renderContext;
  40444. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  40445. //
  40446. this.info.calls ++;
  40447. this.info.render.calls ++;
  40448. this.info.render.frameCalls ++;
  40449. nodeFrame.renderId = this.info.calls;
  40450. //
  40451. this.backend.updateTimeStampUID( renderContext );
  40452. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  40453. //
  40454. const coordinateSystem = this.coordinateSystem;
  40455. const xr = this.xr;
  40456. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  40457. camera.coordinateSystem = coordinateSystem;
  40458. camera.updateProjectionMatrix();
  40459. if ( camera.isArrayCamera ) {
  40460. for ( const subCamera of camera.cameras ) {
  40461. subCamera.coordinateSystem = coordinateSystem;
  40462. subCamera.updateProjectionMatrix();
  40463. }
  40464. }
  40465. }
  40466. //
  40467. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  40468. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  40469. if ( xr.enabled === true && xr.isPresenting === true ) {
  40470. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  40471. camera = xr.getCamera(); // use XR camera for rendering
  40472. }
  40473. //
  40474. const canvasTarget = this._canvasTarget;
  40475. let viewport = canvasTarget._viewport;
  40476. let scissor = canvasTarget._scissor;
  40477. let pixelRatio = canvasTarget._pixelRatio;
  40478. if ( renderTarget !== null ) {
  40479. viewport = renderTarget.viewport;
  40480. scissor = renderTarget.scissor;
  40481. pixelRatio = 1;
  40482. }
  40483. this.getDrawingBufferSize( _drawingBufferSize );
  40484. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  40485. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  40486. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  40487. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  40488. renderContext.viewportValue.width >>= activeMipmapLevel;
  40489. renderContext.viewportValue.height >>= activeMipmapLevel;
  40490. renderContext.viewportValue.minDepth = minDepth;
  40491. renderContext.viewportValue.maxDepth = maxDepth;
  40492. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  40493. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  40494. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  40495. renderContext.scissorValue.width >>= activeMipmapLevel;
  40496. renderContext.scissorValue.height >>= activeMipmapLevel;
  40497. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40498. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40499. //
  40500. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40501. //
  40502. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40503. if ( ! camera.isArrayCamera ) {
  40504. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  40505. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  40506. }
  40507. const renderList = this._renderLists.get( scene, camera );
  40508. renderList.begin();
  40509. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40510. renderList.finish();
  40511. if ( this.sortObjects === true ) {
  40512. renderList.sort( this._opaqueSort, this._transparentSort );
  40513. }
  40514. //
  40515. if ( renderTarget !== null ) {
  40516. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40517. const renderTargetData = this._textures.get( renderTarget );
  40518. renderContext.textures = renderTargetData.textures;
  40519. renderContext.depthTexture = renderTargetData.depthTexture;
  40520. renderContext.width = renderTargetData.width;
  40521. renderContext.height = renderTargetData.height;
  40522. renderContext.renderTarget = renderTarget;
  40523. renderContext.depth = renderTarget.depthBuffer;
  40524. renderContext.stencil = renderTarget.stencilBuffer;
  40525. } else {
  40526. renderContext.textures = null;
  40527. renderContext.depthTexture = null;
  40528. renderContext.width = _drawingBufferSize.width;
  40529. renderContext.height = _drawingBufferSize.height;
  40530. renderContext.depth = this.depth;
  40531. renderContext.stencil = this.stencil;
  40532. }
  40533. renderContext.width >>= activeMipmapLevel;
  40534. renderContext.height >>= activeMipmapLevel;
  40535. renderContext.activeCubeFace = activeCubeFace;
  40536. renderContext.activeMipmapLevel = activeMipmapLevel;
  40537. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  40538. //
  40539. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  40540. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  40541. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  40542. }
  40543. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  40544. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  40545. }
  40546. //
  40547. this._background.update( sceneRef, renderList, renderContext );
  40548. //
  40549. renderContext.camera = camera;
  40550. this.backend.beginRender( renderContext );
  40551. // process render lists
  40552. const {
  40553. bundles,
  40554. lightsNode,
  40555. transparentDoublePass: transparentDoublePassObjects,
  40556. transparent: transparentObjects,
  40557. opaque: opaqueObjects
  40558. } = renderList;
  40559. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  40560. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40561. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40562. // finish render pass
  40563. this.backend.finishRender( renderContext );
  40564. // restore render tree
  40565. nodeFrame.renderId = previousRenderId;
  40566. this._currentRenderContext = previousRenderContext;
  40567. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40568. //
  40569. if ( frameBufferTarget !== null ) {
  40570. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  40571. this._renderOutput( renderTarget );
  40572. }
  40573. //
  40574. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  40575. //
  40576. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  40577. //
  40578. return renderContext;
  40579. }
  40580. _setXRLayerSize( width, height ) {
  40581. // TODO: Find a better solution to resize the canvas when in XR.
  40582. this._canvasTarget._width = width;
  40583. this._canvasTarget._height = height;
  40584. this.setViewport( 0, 0, width, height );
  40585. }
  40586. /**
  40587. * The output pass performs tone mapping and color space conversion.
  40588. *
  40589. * @private
  40590. * @param {RenderTarget} renderTarget - The current render target.
  40591. */
  40592. _renderOutput( renderTarget ) {
  40593. const quad = this._quad;
  40594. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  40595. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  40596. quad.material.needsUpdate = true;
  40597. }
  40598. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  40599. const currentAutoClear = this.autoClear;
  40600. const currentXR = this.xr.enabled;
  40601. this.autoClear = false;
  40602. this.xr.enabled = false;
  40603. this._renderScene( quad, quad.camera, false );
  40604. this.autoClear = currentAutoClear;
  40605. this.xr.enabled = currentXR;
  40606. }
  40607. /**
  40608. * Returns the maximum available anisotropy for texture filtering.
  40609. *
  40610. * @return {number} The maximum available anisotropy.
  40611. */
  40612. getMaxAnisotropy() {
  40613. return this.backend.getMaxAnisotropy();
  40614. }
  40615. /**
  40616. * Returns the active cube face.
  40617. *
  40618. * @return {number} The active cube face.
  40619. */
  40620. getActiveCubeFace() {
  40621. return this._activeCubeFace;
  40622. }
  40623. /**
  40624. * Returns the active mipmap level.
  40625. *
  40626. * @return {number} The active mipmap level.
  40627. */
  40628. getActiveMipmapLevel() {
  40629. return this._activeMipmapLevel;
  40630. }
  40631. /**
  40632. * Applications are advised to always define the animation loop
  40633. * with this method and not manually with `requestAnimationFrame()`
  40634. * for best compatibility.
  40635. *
  40636. * @async
  40637. * @param {?onAnimationCallback} callback - The application's animation loop.
  40638. * @return {Promise} A Promise that resolves when the set has been executed.
  40639. */
  40640. async setAnimationLoop( callback ) {
  40641. if ( this._initialized === false ) await this.init();
  40642. this._animation.setAnimationLoop( callback );
  40643. }
  40644. /**
  40645. * Returns the current animation loop callback.
  40646. *
  40647. * @return {?Function} The current animation loop callback.
  40648. */
  40649. getAnimationLoop() {
  40650. return this._animation.getAnimationLoop();
  40651. }
  40652. /**
  40653. * Can be used to transfer buffer data from a storage buffer attribute
  40654. * from the GPU to the CPU in context of compute shaders.
  40655. *
  40656. * @async
  40657. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40658. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40659. */
  40660. async getArrayBufferAsync( attribute ) {
  40661. return await this.backend.getArrayBufferAsync( attribute );
  40662. }
  40663. /**
  40664. * Returns the rendering context.
  40665. *
  40666. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  40667. */
  40668. getContext() {
  40669. return this.backend.getContext();
  40670. }
  40671. /**
  40672. * Returns the pixel ratio.
  40673. *
  40674. * @return {number} The pixel ratio.
  40675. */
  40676. getPixelRatio() {
  40677. return this._canvasTarget.getPixelRatio();
  40678. }
  40679. /**
  40680. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40681. *
  40682. * @param {Vector2} target - The method writes the result in this target object.
  40683. * @return {Vector2} The drawing buffer size.
  40684. */
  40685. getDrawingBufferSize( target ) {
  40686. return this._canvasTarget.getDrawingBufferSize( target );
  40687. }
  40688. /**
  40689. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40690. *
  40691. * @param {Vector2} target - The method writes the result in this target object.
  40692. * @return {Vector2} The renderer's size in logical pixels.
  40693. */
  40694. getSize( target ) {
  40695. return this._canvasTarget.getSize( target );
  40696. }
  40697. /**
  40698. * Sets the given pixel ratio and resizes the canvas if necessary.
  40699. *
  40700. * @param {number} [value=1] - The pixel ratio.
  40701. */
  40702. setPixelRatio( value = 1 ) {
  40703. this._canvasTarget.setPixelRatio( value );
  40704. }
  40705. /**
  40706. * This method allows to define the drawing buffer size by specifying
  40707. * width, height and pixel ratio all at once. The size of the drawing
  40708. * buffer is computed with this formula:
  40709. * ```js
  40710. * size.x = width * pixelRatio;
  40711. * size.y = height * pixelRatio;
  40712. * ```
  40713. *
  40714. * @param {number} width - The width in logical pixels.
  40715. * @param {number} height - The height in logical pixels.
  40716. * @param {number} pixelRatio - The pixel ratio.
  40717. */
  40718. setDrawingBufferSize( width, height, pixelRatio ) {
  40719. // Renderer can't be resized while presenting in XR.
  40720. if ( this.xr && this.xr.isPresenting ) return;
  40721. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  40722. }
  40723. /**
  40724. * Sets the size of the renderer.
  40725. *
  40726. * @param {number} width - The width in logical pixels.
  40727. * @param {number} height - The height in logical pixels.
  40728. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40729. */
  40730. setSize( width, height, updateStyle = true ) {
  40731. // Renderer can't be resized while presenting in XR.
  40732. if ( this.xr && this.xr.isPresenting ) return;
  40733. this._canvasTarget.setSize( width, height, updateStyle );
  40734. }
  40735. /**
  40736. * Defines a manual sort function for the opaque render list.
  40737. * Pass `null` to use the default sort.
  40738. *
  40739. * @param {Function} method - The sort function.
  40740. */
  40741. setOpaqueSort( method ) {
  40742. this._opaqueSort = method;
  40743. }
  40744. /**
  40745. * Defines a manual sort function for the transparent render list.
  40746. * Pass `null` to use the default sort.
  40747. *
  40748. * @param {Function} method - The sort function.
  40749. */
  40750. setTransparentSort( method ) {
  40751. this._transparentSort = method;
  40752. }
  40753. /**
  40754. * Returns the scissor rectangle.
  40755. *
  40756. * @param {Vector4} target - The method writes the result in this target object.
  40757. * @return {Vector4} The scissor rectangle.
  40758. */
  40759. getScissor( target ) {
  40760. return this._canvasTarget.getScissor( target );
  40761. }
  40762. /**
  40763. * Defines the scissor rectangle.
  40764. *
  40765. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40766. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40767. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40768. * @param {number} width - The width of the scissor box in logical pixel unit.
  40769. * @param {number} height - The height of the scissor box in logical pixel unit.
  40770. */
  40771. setScissor( x, y, width, height ) {
  40772. this._canvasTarget.setScissor( x, y, width, height );
  40773. }
  40774. /**
  40775. * Returns the scissor test value.
  40776. *
  40777. * @return {boolean} Whether the scissor test should be enabled or not.
  40778. */
  40779. getScissorTest() {
  40780. return this._canvasTarget.getScissorTest();
  40781. }
  40782. /**
  40783. * Defines the scissor test.
  40784. *
  40785. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40786. */
  40787. setScissorTest( boolean ) {
  40788. this._canvasTarget.setScissorTest( boolean );
  40789. // TODO: Move it to CanvasTarget event listener.
  40790. this.backend.setScissorTest( boolean );
  40791. }
  40792. /**
  40793. * Returns the viewport definition.
  40794. *
  40795. * @param {Vector4} target - The method writes the result in this target object.
  40796. * @return {Vector4} The viewport definition.
  40797. */
  40798. getViewport( target ) {
  40799. return this._canvasTarget.getViewport( target );
  40800. }
  40801. /**
  40802. * Defines the viewport.
  40803. *
  40804. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40805. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40806. * @param {number} width - The width of the viewport in logical pixel unit.
  40807. * @param {number} height - The height of the viewport in logical pixel unit.
  40808. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40809. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40810. */
  40811. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40812. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  40813. }
  40814. /**
  40815. * Returns the clear color.
  40816. *
  40817. * @param {Color} target - The method writes the result in this target object.
  40818. * @return {Color} The clear color.
  40819. */
  40820. getClearColor( target ) {
  40821. return target.copy( this._clearColor );
  40822. }
  40823. /**
  40824. * Defines the clear color and optionally the clear alpha.
  40825. *
  40826. * @param {Color} color - The clear color.
  40827. * @param {number} [alpha=1] - The clear alpha.
  40828. */
  40829. setClearColor( color, alpha = 1 ) {
  40830. this._clearColor.set( color );
  40831. this._clearColor.a = alpha;
  40832. }
  40833. /**
  40834. * Returns the clear alpha.
  40835. *
  40836. * @return {number} The clear alpha.
  40837. */
  40838. getClearAlpha() {
  40839. return this._clearColor.a;
  40840. }
  40841. /**
  40842. * Defines the clear alpha.
  40843. *
  40844. * @param {number} alpha - The clear alpha.
  40845. */
  40846. setClearAlpha( alpha ) {
  40847. this._clearColor.a = alpha;
  40848. }
  40849. /**
  40850. * Returns the clear depth.
  40851. *
  40852. * @return {number} The clear depth.
  40853. */
  40854. getClearDepth() {
  40855. return this._clearDepth;
  40856. }
  40857. /**
  40858. * Defines the clear depth.
  40859. *
  40860. * @param {number} depth - The clear depth.
  40861. */
  40862. setClearDepth( depth ) {
  40863. this._clearDepth = depth;
  40864. }
  40865. /**
  40866. * Returns the clear stencil.
  40867. *
  40868. * @return {number} The clear stencil.
  40869. */
  40870. getClearStencil() {
  40871. return this._clearStencil;
  40872. }
  40873. /**
  40874. * Defines the clear stencil.
  40875. *
  40876. * @param {number} stencil - The clear stencil.
  40877. */
  40878. setClearStencil( stencil ) {
  40879. this._clearStencil = stencil;
  40880. }
  40881. /**
  40882. * This method performs an occlusion query for the given 3D object.
  40883. * It returns `true` if the given 3D object is fully occluded by other
  40884. * 3D objects in the scene.
  40885. *
  40886. * @param {Object3D} object - The 3D object to test.
  40887. * @return {boolean} Whether the 3D object is fully occluded or not.
  40888. */
  40889. isOccluded( object ) {
  40890. const renderContext = this._currentRenderContext;
  40891. return renderContext && this.backend.isOccluded( renderContext, object );
  40892. }
  40893. /**
  40894. * Performs a manual clear operation. This method ignores `autoClear` properties.
  40895. *
  40896. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40897. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40898. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40899. */
  40900. clear( color = true, depth = true, stencil = true ) {
  40901. if ( this._initialized === false ) {
  40902. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  40903. }
  40904. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40905. let renderContext = null;
  40906. if ( renderTarget !== null ) {
  40907. this._textures.updateRenderTarget( renderTarget );
  40908. const renderTargetData = this._textures.get( renderTarget );
  40909. renderContext = this._renderContexts.getForClear( renderTarget );
  40910. renderContext.textures = renderTargetData.textures;
  40911. renderContext.depthTexture = renderTargetData.depthTexture;
  40912. renderContext.width = renderTargetData.width;
  40913. renderContext.height = renderTargetData.height;
  40914. renderContext.renderTarget = renderTarget;
  40915. renderContext.depth = renderTarget.depthBuffer;
  40916. renderContext.stencil = renderTarget.stencilBuffer;
  40917. // #30329
  40918. renderContext.clearColorValue = this.backend.getClearColor();
  40919. renderContext.activeCubeFace = this.getActiveCubeFace();
  40920. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  40921. }
  40922. this.backend.clear( color, depth, stencil, renderContext );
  40923. if ( renderTarget !== null && this._renderTarget === null ) {
  40924. this._renderOutput( renderTarget );
  40925. }
  40926. }
  40927. /**
  40928. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  40929. */
  40930. clearColor() {
  40931. this.clear( true, false, false );
  40932. }
  40933. /**
  40934. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  40935. */
  40936. clearDepth() {
  40937. this.clear( false, true, false );
  40938. }
  40939. /**
  40940. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  40941. */
  40942. clearStencil() {
  40943. this.clear( false, false, true );
  40944. }
  40945. /**
  40946. * Async version of {@link Renderer#clear}.
  40947. *
  40948. * @async
  40949. * @deprecated
  40950. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40951. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40952. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40953. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40954. */
  40955. async clearAsync( color = true, depth = true, stencil = true ) {
  40956. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40957. await this.init();
  40958. this.clear( color, depth, stencil );
  40959. }
  40960. /**
  40961. * Async version of {@link Renderer#clearColor}.
  40962. *
  40963. * @async
  40964. * @deprecated
  40965. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40966. */
  40967. async clearColorAsync() {
  40968. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40969. this.clear( true, false, false );
  40970. }
  40971. /**
  40972. * Async version of {@link Renderer#clearDepth}.
  40973. *
  40974. * @async
  40975. * @deprecated
  40976. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40977. */
  40978. async clearDepthAsync() {
  40979. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40980. this.clear( false, true, false );
  40981. }
  40982. /**
  40983. * Async version of {@link Renderer#clearStencil}.
  40984. *
  40985. * @async
  40986. * @deprecated
  40987. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40988. */
  40989. async clearStencilAsync() {
  40990. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40991. this.clear( false, false, true );
  40992. }
  40993. /**
  40994. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  40995. * If this is the case, the renderer allocates an internal render target for that purpose.
  40996. *
  40997. */
  40998. get needsFrameBufferTarget() {
  40999. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  41000. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  41001. return useToneMapping || useColorSpace;
  41002. }
  41003. /**
  41004. * The number of samples used for multi-sample anti-aliasing (MSAA).
  41005. *
  41006. * @type {number}
  41007. * @default 0
  41008. */
  41009. get samples() {
  41010. return this._samples;
  41011. }
  41012. /**
  41013. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  41014. *
  41015. * When rendering to a custom render target, the number of samples of that render target is used.
  41016. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  41017. * the number of samples is set to 0.
  41018. *
  41019. * @type {number}
  41020. */
  41021. get currentSamples() {
  41022. let samples = this._samples;
  41023. if ( this._renderTarget !== null ) {
  41024. samples = this._renderTarget.samples;
  41025. } else if ( this.needsFrameBufferTarget ) {
  41026. samples = 0;
  41027. }
  41028. return samples;
  41029. }
  41030. /**
  41031. * The current tone mapping of the renderer. When not producing screen output,
  41032. * the tone mapping is always `NoToneMapping`.
  41033. *
  41034. * @type {number}
  41035. */
  41036. get currentToneMapping() {
  41037. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  41038. }
  41039. /**
  41040. * The current color space of the renderer. When not producing screen output,
  41041. * the color space is always the working color space.
  41042. *
  41043. * @type {string}
  41044. */
  41045. get currentColorSpace() {
  41046. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  41047. }
  41048. /**
  41049. * Returns `true` if the rendering settings are set to screen output.
  41050. *
  41051. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  41052. */
  41053. get isOutputTarget() {
  41054. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  41055. }
  41056. /**
  41057. * Frees all internal resources of the renderer. Call this method if the renderer
  41058. * is no longer in use by your app.
  41059. */
  41060. dispose() {
  41061. if ( this._initialized === true ) {
  41062. this.info.dispose();
  41063. this.backend.dispose();
  41064. this._animation.dispose();
  41065. this._objects.dispose();
  41066. this._geometries.dispose();
  41067. this._pipelines.dispose();
  41068. this._nodes.dispose();
  41069. this._bindings.dispose();
  41070. this._renderLists.dispose();
  41071. this._renderContexts.dispose();
  41072. this._textures.dispose();
  41073. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  41074. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  41075. if ( queryPool !== null ) queryPool.dispose();
  41076. } );
  41077. }
  41078. this.setRenderTarget( null );
  41079. this.setAnimationLoop( null );
  41080. }
  41081. /**
  41082. * Sets the given render target. Calling this method means the renderer does not
  41083. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  41084. * Use `null` as the first argument to reset the state.
  41085. *
  41086. * @param {?RenderTarget} renderTarget - The render target to set.
  41087. * @param {number} [activeCubeFace=0] - The active cube face.
  41088. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  41089. */
  41090. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  41091. this._renderTarget = renderTarget;
  41092. this._activeCubeFace = activeCubeFace;
  41093. this._activeMipmapLevel = activeMipmapLevel;
  41094. }
  41095. /**
  41096. * Returns the current render target.
  41097. *
  41098. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  41099. */
  41100. getRenderTarget() {
  41101. return this._renderTarget;
  41102. }
  41103. /**
  41104. * Sets the output render target for the renderer.
  41105. *
  41106. * @param {Object} renderTarget - The render target to set as the output target.
  41107. */
  41108. setOutputRenderTarget( renderTarget ) {
  41109. this._outputRenderTarget = renderTarget;
  41110. }
  41111. /**
  41112. * Returns the current output target.
  41113. *
  41114. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  41115. */
  41116. getOutputRenderTarget() {
  41117. return this._outputRenderTarget;
  41118. }
  41119. /**
  41120. * Sets the canvas target. The canvas target manages the HTML canvas
  41121. * or the offscreen canvas the renderer draws into.
  41122. *
  41123. * @param {CanvasTarget} canvasTarget - The canvas target.
  41124. */
  41125. setCanvasTarget( canvasTarget ) {
  41126. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  41127. this._canvasTarget = canvasTarget;
  41128. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41129. }
  41130. /**
  41131. * Returns the current canvas target.
  41132. *
  41133. * @return {CanvasTarget} The current canvas target.
  41134. */
  41135. getCanvasTarget() {
  41136. return this._canvasTarget;
  41137. }
  41138. /**
  41139. * Resets the renderer to the initial state before WebXR started.
  41140. *
  41141. */
  41142. _resetXRState() {
  41143. this.backend.setXRTarget( null );
  41144. this.setOutputRenderTarget( null );
  41145. this.setRenderTarget( null );
  41146. this._frameBufferTarget.dispose();
  41147. this._frameBufferTarget = null;
  41148. }
  41149. /**
  41150. * Callback for {@link Renderer#setRenderObjectFunction}.
  41151. *
  41152. * @callback renderObjectFunction
  41153. * @param {Object3D} object - The 3D object.
  41154. * @param {Scene} scene - The scene the 3D object belongs to.
  41155. * @param {Camera} camera - The camera the object should be rendered with.
  41156. * @param {BufferGeometry} geometry - The object's geometry.
  41157. * @param {Material} material - The object's material.
  41158. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41159. * @param {LightsNode} lightsNode - The current lights node.
  41160. * @param {ClippingContext} clippingContext - The clipping context.
  41161. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41162. */
  41163. /**
  41164. * Sets the given render object function. Calling this method overwrites the default implementation
  41165. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  41166. * if you want to modify the way objects are rendered. For example you can define things like "every
  41167. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  41168. * The custom function must always call `renderObject()` in its implementation.
  41169. *
  41170. * Use `null` as the first argument to reset the state.
  41171. *
  41172. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  41173. */
  41174. setRenderObjectFunction( renderObjectFunction ) {
  41175. this._renderObjectFunction = renderObjectFunction;
  41176. }
  41177. /**
  41178. * Returns the current render object function.
  41179. *
  41180. * @return {?Function} The current render object function. Returns `null` if no function is set.
  41181. */
  41182. getRenderObjectFunction() {
  41183. return this._renderObjectFunction;
  41184. }
  41185. /**
  41186. * Execute a single or an array of compute nodes. This method can only be called
  41187. * if the renderer has been initialized.
  41188. *
  41189. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41190. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41191. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  41192. */
  41193. compute( computeNodes, dispatchSizeOrCount = null ) {
  41194. if ( this._isDeviceLost === true ) return;
  41195. if ( this._initialized === false ) {
  41196. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  41197. return this.computeAsync( computeNodes );
  41198. }
  41199. //
  41200. const nodeFrame = this._nodes.nodeFrame;
  41201. const previousRenderId = nodeFrame.renderId;
  41202. //
  41203. this.info.calls ++;
  41204. this.info.compute.calls ++;
  41205. this.info.compute.frameCalls ++;
  41206. nodeFrame.renderId = this.info.calls;
  41207. //
  41208. this.backend.updateTimeStampUID( computeNodes );
  41209. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  41210. //
  41211. const backend = this.backend;
  41212. const pipelines = this._pipelines;
  41213. const bindings = this._bindings;
  41214. const nodes = this._nodes;
  41215. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  41216. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  41217. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  41218. }
  41219. backend.beginCompute( computeNodes );
  41220. for ( const computeNode of computeList ) {
  41221. // onInit
  41222. if ( pipelines.has( computeNode ) === false ) {
  41223. const dispose = () => {
  41224. computeNode.removeEventListener( 'dispose', dispose );
  41225. pipelines.delete( computeNode );
  41226. bindings.deleteForCompute( computeNode );
  41227. nodes.delete( computeNode );
  41228. };
  41229. computeNode.addEventListener( 'dispose', dispose );
  41230. //
  41231. const onInitFn = computeNode.onInitFunction;
  41232. if ( onInitFn !== null ) {
  41233. onInitFn.call( computeNode, { renderer: this } );
  41234. }
  41235. }
  41236. nodes.updateForCompute( computeNode );
  41237. bindings.updateForCompute( computeNode );
  41238. const computeBindings = bindings.getForCompute( computeNode );
  41239. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  41240. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  41241. }
  41242. backend.finishCompute( computeNodes );
  41243. //
  41244. nodeFrame.renderId = previousRenderId;
  41245. //
  41246. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  41247. }
  41248. /**
  41249. * Execute a single or an array of compute nodes.
  41250. *
  41251. * @async
  41252. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41253. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41254. * @return {Promise} A Promise that resolve when the compute has finished.
  41255. */
  41256. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  41257. warnOnce( 'Renderer: "computeAsync()" has been deprecated. Use "compute()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41258. await this.init();
  41259. this.compute( computeNodes, dispatchSizeOrCount );
  41260. }
  41261. /**
  41262. * Checks if the given feature is supported by the selected backend.
  41263. *
  41264. * @async
  41265. * @deprecated
  41266. * @param {string} name - The feature's name.
  41267. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41268. */
  41269. async hasFeatureAsync( name ) {
  41270. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41271. await this.init();
  41272. return this.hasFeature( name );
  41273. }
  41274. async resolveTimestampsAsync( type = 'render' ) {
  41275. if ( this._initialized === false ) await this.init();
  41276. return this.backend.resolveTimestampsAsync( type );
  41277. }
  41278. /**
  41279. * Checks if the given feature is supported by the selected backend. If the
  41280. * renderer has not been initialized, this method always returns `false`.
  41281. *
  41282. * @param {string} name - The feature's name.
  41283. * @return {boolean} Whether the feature is supported or not.
  41284. */
  41285. hasFeature( name ) {
  41286. if ( this._initialized === false ) {
  41287. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41288. }
  41289. return this.backend.hasFeature( name );
  41290. }
  41291. /**
  41292. * Returns `true` when the renderer has been initialized.
  41293. *
  41294. * @return {boolean} Whether the renderer has been initialized or not.
  41295. */
  41296. hasInitialized() {
  41297. return this._initialized;
  41298. }
  41299. /**
  41300. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  41301. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41302. *
  41303. * @async
  41304. * @deprecated
  41305. * @param {Texture} texture - The texture.
  41306. * @return {Promise} A Promise that resolves when the texture has been initialized.
  41307. */
  41308. async initTextureAsync( texture ) {
  41309. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41310. await this.init();
  41311. this.initTexture( texture );
  41312. }
  41313. /**
  41314. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  41315. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41316. *
  41317. * This method can only be used if the renderer has been initialized.
  41318. *
  41319. * @param {Texture} texture - The texture.
  41320. */
  41321. initTexture( texture ) {
  41322. if ( this._initialized === false ) {
  41323. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41324. }
  41325. this._textures.updateTexture( texture );
  41326. }
  41327. /**
  41328. * Copies the current bound framebuffer into the given texture.
  41329. *
  41330. * @param {FramebufferTexture} framebufferTexture - The texture.
  41331. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  41332. */
  41333. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  41334. if ( rectangle !== null ) {
  41335. if ( rectangle.isVector2 ) {
  41336. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  41337. } else if ( rectangle.isVector4 ) {
  41338. rectangle = _vector4.copy( rectangle ).floor();
  41339. } else {
  41340. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  41341. return;
  41342. }
  41343. } else {
  41344. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  41345. }
  41346. //
  41347. let renderContext = this._currentRenderContext;
  41348. let renderTarget;
  41349. if ( renderContext !== null ) {
  41350. renderTarget = renderContext.renderTarget;
  41351. } else {
  41352. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41353. if ( renderTarget !== null ) {
  41354. this._textures.updateRenderTarget( renderTarget );
  41355. renderContext = this._textures.get( renderTarget );
  41356. }
  41357. }
  41358. //
  41359. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  41360. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  41361. this._inspector.copyFramebufferToTexture( framebufferTexture );
  41362. }
  41363. /**
  41364. * Copies data of the given source texture into a destination texture.
  41365. *
  41366. * @param {Texture} srcTexture - The source texture.
  41367. * @param {Texture} dstTexture - The destination texture.
  41368. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  41369. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  41370. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41371. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41372. */
  41373. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41374. this._textures.updateTexture( srcTexture );
  41375. this._textures.updateTexture( dstTexture );
  41376. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  41377. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  41378. }
  41379. /**
  41380. * Reads pixel data from the given render target.
  41381. *
  41382. * @async
  41383. * @param {RenderTarget} renderTarget - The render target to read from.
  41384. * @param {number} x - The `x` coordinate of the copy region's origin.
  41385. * @param {number} y - The `y` coordinate of the copy region's origin.
  41386. * @param {number} width - The width of the copy region.
  41387. * @param {number} height - The height of the copy region.
  41388. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  41389. * @param {number} [faceIndex=0] - The active cube face index.
  41390. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  41391. */
  41392. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  41393. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  41394. }
  41395. /**
  41396. * Analyzes the given 3D object's hierarchy and builds render lists from the
  41397. * processed hierarchy.
  41398. *
  41399. * @param {Object3D} object - The 3D object to process (usually a scene).
  41400. * @param {Camera} camera - The camera the object is rendered with.
  41401. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  41402. * @param {RenderList} renderList - The current render list.
  41403. * @param {ClippingContext} clippingContext - The current clipping context.
  41404. */
  41405. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  41406. if ( object.visible === false ) return;
  41407. const visible = object.layers.test( camera.layers );
  41408. if ( visible ) {
  41409. if ( object.isGroup ) {
  41410. groupOrder = object.renderOrder;
  41411. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  41412. } else if ( object.isLOD ) {
  41413. if ( object.autoUpdate === true ) object.update( camera );
  41414. } else if ( object.isLight ) {
  41415. renderList.pushLight( object );
  41416. } else if ( object.isSprite ) {
  41417. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41418. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  41419. if ( this.sortObjects === true ) {
  41420. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  41421. }
  41422. const { geometry, material } = object;
  41423. if ( material.visible ) {
  41424. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41425. }
  41426. }
  41427. } else if ( object.isLineLoop ) {
  41428. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  41429. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  41430. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41431. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  41432. const { geometry, material } = object;
  41433. if ( this.sortObjects === true ) {
  41434. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  41435. _vector4
  41436. .copy( geometry.boundingSphere.center )
  41437. .applyMatrix4( object.matrixWorld )
  41438. .applyMatrix4( _projScreenMatrix );
  41439. }
  41440. if ( Array.isArray( material ) ) {
  41441. const groups = geometry.groups;
  41442. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  41443. const group = groups[ i ];
  41444. const groupMaterial = material[ group.materialIndex ];
  41445. if ( groupMaterial && groupMaterial.visible ) {
  41446. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  41447. }
  41448. }
  41449. } else if ( material.visible ) {
  41450. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41451. }
  41452. }
  41453. }
  41454. }
  41455. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  41456. const baseRenderList = renderList;
  41457. // replace render list
  41458. renderList = this._renderLists.get( object, camera );
  41459. renderList.begin();
  41460. baseRenderList.pushBundle( {
  41461. bundleGroup: object,
  41462. camera,
  41463. renderList,
  41464. } );
  41465. renderList.finish();
  41466. }
  41467. const children = object.children;
  41468. for ( let i = 0, l = children.length; i < l; i ++ ) {
  41469. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  41470. }
  41471. }
  41472. /**
  41473. * Renders the given render bundles.
  41474. *
  41475. * @private
  41476. * @param {Array<Object>} bundles - Array with render bundle data.
  41477. * @param {Scene} sceneRef - The scene the render bundles belong to.
  41478. * @param {LightsNode} lightsNode - The current lights node.
  41479. */
  41480. _renderBundles( bundles, sceneRef, lightsNode ) {
  41481. for ( const bundle of bundles ) {
  41482. this._renderBundle( bundle, sceneRef, lightsNode );
  41483. }
  41484. }
  41485. /**
  41486. * Renders the transparent objects from the given render lists.
  41487. *
  41488. * @private
  41489. * @param {Array<Object>} renderList - The transparent render list.
  41490. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  41491. * @param {Camera} camera - The camera the render list should be rendered with.
  41492. * @param {Scene} scene - The scene the render list belongs to.
  41493. * @param {LightsNode} lightsNode - The current lights node.
  41494. */
  41495. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  41496. if ( doublePassList.length > 0 ) {
  41497. // render back side
  41498. for ( const { material } of doublePassList ) {
  41499. material.side = BackSide;
  41500. }
  41501. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  41502. // render front side
  41503. for ( const { material } of doublePassList ) {
  41504. material.side = FrontSide;
  41505. }
  41506. this._renderObjects( renderList, camera, scene, lightsNode );
  41507. // restore
  41508. for ( const { material } of doublePassList ) {
  41509. material.side = DoubleSide;
  41510. }
  41511. } else {
  41512. this._renderObjects( renderList, camera, scene, lightsNode );
  41513. }
  41514. }
  41515. /**
  41516. * Renders the objects from the given render list.
  41517. *
  41518. * @private
  41519. * @param {Array<Object>} renderList - The render list.
  41520. * @param {Camera} camera - The camera the render list should be rendered with.
  41521. * @param {Scene} scene - The scene the render list belongs to.
  41522. * @param {LightsNode} lightsNode - The current lights node.
  41523. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41524. */
  41525. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  41526. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  41527. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  41528. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  41529. }
  41530. }
  41531. /**
  41532. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  41533. * The result is cached per material and updated when the material's version changes.
  41534. *
  41535. * @param {Material} material
  41536. * @returns {Object} - The shadow nodes for the material.
  41537. */
  41538. _getShadowNodes( material ) {
  41539. const version = material.version;
  41540. let cache = this._cacheShadowNodes.get( material );
  41541. if ( cache === undefined || cache.version !== version ) {
  41542. const hasMap = material.map !== null;
  41543. const hasColorNode = material.colorNode && material.colorNode.isNode;
  41544. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  41545. let positionNode = null;
  41546. let colorNode = null;
  41547. let depthNode = null;
  41548. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  41549. let shadowRGB;
  41550. let shadowAlpha;
  41551. if ( hasCastShadowNode ) {
  41552. shadowRGB = material.castShadowNode.rgb;
  41553. shadowAlpha = material.castShadowNode.a;
  41554. } else {
  41555. shadowRGB = vec3( 0 );
  41556. shadowAlpha = float( 1 );
  41557. }
  41558. if ( hasMap ) {
  41559. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  41560. }
  41561. if ( hasColorNode ) {
  41562. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  41563. }
  41564. colorNode = vec4( shadowRGB, shadowAlpha );
  41565. }
  41566. if ( material.depthNode && material.depthNode.isNode ) {
  41567. depthNode = material.depthNode;
  41568. }
  41569. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  41570. positionNode = material.castShadowPositionNode;
  41571. } else if ( material.positionNode && material.positionNode.isNode ) {
  41572. positionNode = material.positionNode;
  41573. }
  41574. cache = {
  41575. version,
  41576. colorNode,
  41577. depthNode,
  41578. positionNode
  41579. };
  41580. this._cacheShadowNodes.set( material, cache );
  41581. }
  41582. return cache;
  41583. }
  41584. /**
  41585. * This method represents the default render object function that manages the render lifecycle
  41586. * of the object.
  41587. *
  41588. * @param {Object3D} object - The 3D object.
  41589. * @param {Scene} scene - The scene the 3D object belongs to.
  41590. * @param {Camera} camera - The camera the object should be rendered with.
  41591. * @param {BufferGeometry} geometry - The object's geometry.
  41592. * @param {Material} material - The object's material.
  41593. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41594. * @param {LightsNode} lightsNode - The current lights node.
  41595. * @param {?ClippingContext} clippingContext - The clipping context.
  41596. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41597. */
  41598. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  41599. let materialOverride = false;
  41600. let materialColorNode;
  41601. let materialDepthNode;
  41602. let materialPositionNode;
  41603. let materialSide;
  41604. //
  41605. object.onBeforeRender( this, scene, camera, geometry, material, group );
  41606. //
  41607. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  41608. const overrideMaterial = scene.overrideMaterial;
  41609. materialOverride = true;
  41610. // store original nodes
  41611. materialColorNode = scene.overrideMaterial.colorNode;
  41612. materialDepthNode = scene.overrideMaterial.depthNode;
  41613. materialPositionNode = scene.overrideMaterial.positionNode;
  41614. materialSide = scene.overrideMaterial.side;
  41615. if ( material.positionNode && material.positionNode.isNode ) {
  41616. overrideMaterial.positionNode = material.positionNode;
  41617. }
  41618. overrideMaterial.alphaTest = material.alphaTest;
  41619. overrideMaterial.alphaMap = material.alphaMap;
  41620. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  41621. if ( overrideMaterial.isShadowPassMaterial ) {
  41622. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  41623. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  41624. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  41625. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  41626. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  41627. }
  41628. material = overrideMaterial;
  41629. }
  41630. //
  41631. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  41632. material.side = BackSide;
  41633. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  41634. material.side = FrontSide;
  41635. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  41636. material.side = DoubleSide;
  41637. } else {
  41638. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  41639. }
  41640. //
  41641. if ( materialOverride ) {
  41642. scene.overrideMaterial.colorNode = materialColorNode;
  41643. scene.overrideMaterial.depthNode = materialDepthNode;
  41644. scene.overrideMaterial.positionNode = materialPositionNode;
  41645. scene.overrideMaterial.side = materialSide;
  41646. }
  41647. //
  41648. object.onAfterRender( this, scene, camera, geometry, material, group );
  41649. }
  41650. /**
  41651. * This method represents the default `_handleObjectFunction` implementation which creates
  41652. * a render object from the given data and performs the draw command with the selected backend.
  41653. *
  41654. * @private
  41655. * @param {Object3D} object - The 3D object.
  41656. * @param {Material} material - The object's material.
  41657. * @param {Scene} scene - The scene the 3D object belongs to.
  41658. * @param {Camera} camera - The camera the object should be rendered with.
  41659. * @param {LightsNode} lightsNode - The current lights node.
  41660. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41661. * @param {ClippingContext} clippingContext - The clipping context.
  41662. * @param {string} [passId] - An optional ID for identifying the pass.
  41663. */
  41664. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41665. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41666. renderObject.drawRange = object.geometry.drawRange;
  41667. renderObject.group = group;
  41668. //
  41669. const needsRefresh = this._nodes.needsRefresh( renderObject );
  41670. if ( needsRefresh ) {
  41671. this._nodes.updateBefore( renderObject );
  41672. this._geometries.updateForRender( renderObject );
  41673. this._nodes.updateForRender( renderObject );
  41674. this._bindings.updateForRender( renderObject );
  41675. }
  41676. this._pipelines.updateForRender( renderObject );
  41677. //
  41678. if ( this._currentRenderBundle !== null ) {
  41679. const renderBundleData = this.backend.get( this._currentRenderBundle );
  41680. renderBundleData.renderObjects.push( renderObject );
  41681. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  41682. }
  41683. this.backend.draw( renderObject, this.info );
  41684. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  41685. }
  41686. /**
  41687. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  41688. * Used in `compileAsync()`.
  41689. *
  41690. * @private
  41691. * @param {Object3D} object - The 3D object.
  41692. * @param {Material} material - The object's material.
  41693. * @param {Scene} scene - The scene the 3D object belongs to.
  41694. * @param {Camera} camera - The camera the object should be rendered with.
  41695. * @param {LightsNode} lightsNode - The current lights node.
  41696. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41697. * @param {ClippingContext} clippingContext - The clipping context.
  41698. * @param {string} [passId] - An optional ID for identifying the pass.
  41699. */
  41700. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41701. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41702. renderObject.drawRange = object.geometry.drawRange;
  41703. renderObject.group = group;
  41704. //
  41705. this._nodes.updateBefore( renderObject );
  41706. this._geometries.updateForRender( renderObject );
  41707. this._nodes.updateForRender( renderObject );
  41708. this._bindings.updateForRender( renderObject );
  41709. this._pipelines.getForRender( renderObject, this._compilationPromises );
  41710. this._nodes.updateAfter( renderObject );
  41711. }
  41712. /**
  41713. * Callback when the canvas has been resized.
  41714. *
  41715. * @private
  41716. */
  41717. _onCanvasTargetResize() {
  41718. if ( this._initialized ) this.backend.updateSize();
  41719. }
  41720. /**
  41721. * Alias for `compileAsync()`.
  41722. *
  41723. * @method
  41724. * @param {Object3D} scene - The scene or 3D object to precompile.
  41725. * @param {Camera} camera - The camera that is used to render the scene.
  41726. * @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.
  41727. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  41728. */
  41729. get compile() {
  41730. return this.compileAsync;
  41731. }
  41732. }
  41733. /**
  41734. * A binding represents the connection between a resource (like a texture, sampler
  41735. * or uniform buffer) and the resource definition in a shader stage.
  41736. *
  41737. * This module is an abstract base class for all concrete bindings types.
  41738. *
  41739. * @abstract
  41740. * @private
  41741. */
  41742. class Binding {
  41743. /**
  41744. * Constructs a new binding.
  41745. *
  41746. * @param {string} [name=''] - The binding's name.
  41747. */
  41748. constructor( name = '' ) {
  41749. /**
  41750. * The binding's name.
  41751. *
  41752. * @type {string}
  41753. */
  41754. this.name = name;
  41755. /**
  41756. * A bitmask that defines in what shader stages the
  41757. * binding's resource is accessible.
  41758. *
  41759. * @type {number}
  41760. */
  41761. this.visibility = 0;
  41762. }
  41763. /**
  41764. * Makes sure binding's resource is visible for the given shader stage.
  41765. *
  41766. * @param {number} visibility - The shader stage.
  41767. */
  41768. setVisibility( visibility ) {
  41769. this.visibility |= visibility;
  41770. }
  41771. /**
  41772. * Clones the binding.
  41773. *
  41774. * @return {Binding} The cloned binding.
  41775. */
  41776. clone() {
  41777. return Object.assign( new this.constructor(), this );
  41778. }
  41779. }
  41780. /**
  41781. * This function is usually called with the length in bytes of an array buffer.
  41782. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  41783. *
  41784. * @function
  41785. * @param {number} floatLength - The buffer length.
  41786. * @return {number} The padded length.
  41787. */
  41788. function getFloatLength( floatLength ) {
  41789. // ensure chunk size alignment (STD140 layout)
  41790. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  41791. }
  41792. /**
  41793. * Represents a buffer binding type.
  41794. *
  41795. * @private
  41796. * @abstract
  41797. * @augments Binding
  41798. */
  41799. class Buffer extends Binding {
  41800. /**
  41801. * Constructs a new buffer.
  41802. *
  41803. * @param {string} name - The buffer's name.
  41804. * @param {TypedArray} [buffer=null] - The buffer.
  41805. */
  41806. constructor( name, buffer = null ) {
  41807. super( name );
  41808. /**
  41809. * This flag can be used for type testing.
  41810. *
  41811. * @type {boolean}
  41812. * @readonly
  41813. * @default true
  41814. */
  41815. this.isBuffer = true;
  41816. /**
  41817. * The bytes per element.
  41818. *
  41819. * @type {number}
  41820. */
  41821. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  41822. /**
  41823. * A reference to the internal buffer.
  41824. *
  41825. * @private
  41826. * @type {TypedArray}
  41827. */
  41828. this._buffer = buffer;
  41829. }
  41830. /**
  41831. * The buffer's byte length.
  41832. *
  41833. * @type {number}
  41834. * @readonly
  41835. */
  41836. get byteLength() {
  41837. return getFloatLength( this._buffer.byteLength );
  41838. }
  41839. /**
  41840. * A reference to the internal buffer.
  41841. *
  41842. * @type {Float32Array}
  41843. * @readonly
  41844. */
  41845. get buffer() {
  41846. return this._buffer;
  41847. }
  41848. /**
  41849. * Updates the binding.
  41850. *
  41851. * @return {boolean} Whether the buffer has been updated and must be
  41852. * uploaded to the GPU.
  41853. */
  41854. update() {
  41855. return true;
  41856. }
  41857. }
  41858. /**
  41859. * Represents a uniform buffer binding type.
  41860. *
  41861. * @private
  41862. * @augments Buffer
  41863. */
  41864. class UniformBuffer extends Buffer {
  41865. /**
  41866. * Constructs a new uniform buffer.
  41867. *
  41868. * @param {string} name - The buffer's name.
  41869. * @param {TypedArray} [buffer=null] - The buffer.
  41870. */
  41871. constructor( name, buffer = null ) {
  41872. super( name, buffer );
  41873. /**
  41874. * This flag can be used for type testing.
  41875. *
  41876. * @type {boolean}
  41877. * @readonly
  41878. * @default true
  41879. */
  41880. this.isUniformBuffer = true;
  41881. }
  41882. }
  41883. let _id$4 = 0;
  41884. /**
  41885. * A special form of uniform buffer binding type.
  41886. * It's buffer value is managed by a node object.
  41887. *
  41888. * @private
  41889. * @augments UniformBuffer
  41890. */
  41891. class NodeUniformBuffer extends UniformBuffer {
  41892. /**
  41893. * Constructs a new node-based uniform buffer.
  41894. *
  41895. * @param {BufferNode} nodeUniform - The uniform buffer node.
  41896. * @param {UniformGroupNode} groupNode - The uniform group node.
  41897. */
  41898. constructor( nodeUniform, groupNode ) {
  41899. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  41900. /**
  41901. * The uniform buffer node.
  41902. *
  41903. * @type {BufferNode}
  41904. */
  41905. this.nodeUniform = nodeUniform;
  41906. /**
  41907. * The uniform group node.
  41908. *
  41909. * @type {UniformGroupNode}
  41910. */
  41911. this.groupNode = groupNode;
  41912. }
  41913. /**
  41914. * The uniform buffer.
  41915. *
  41916. * @type {Float32Array}
  41917. */
  41918. get buffer() {
  41919. return this.nodeUniform.value;
  41920. }
  41921. }
  41922. /**
  41923. * This class represents a uniform buffer binding but with
  41924. * an API that allows to maintain individual uniform objects.
  41925. *
  41926. * @private
  41927. * @augments UniformBuffer
  41928. */
  41929. class UniformsGroup extends UniformBuffer {
  41930. /**
  41931. * Constructs a new uniforms group.
  41932. *
  41933. * @param {string} name - The group's name.
  41934. */
  41935. constructor( name ) {
  41936. super( name );
  41937. /**
  41938. * This flag can be used for type testing.
  41939. *
  41940. * @type {boolean}
  41941. * @readonly
  41942. * @default true
  41943. */
  41944. this.isUniformsGroup = true;
  41945. /**
  41946. * An array with the raw uniform values.
  41947. *
  41948. * @private
  41949. * @type {?Array<number>}
  41950. * @default null
  41951. */
  41952. this._values = null;
  41953. /**
  41954. * An array of uniform objects.
  41955. *
  41956. * The order of uniforms in this array must match the order of uniforms in the shader.
  41957. *
  41958. * @type {Array<Uniform>}
  41959. */
  41960. this.uniforms = [];
  41961. }
  41962. /**
  41963. * Adds a uniform to this group.
  41964. *
  41965. * @param {Uniform} uniform - The uniform to add.
  41966. * @return {UniformsGroup} A reference to this group.
  41967. */
  41968. addUniform( uniform ) {
  41969. this.uniforms.push( uniform );
  41970. return this;
  41971. }
  41972. /**
  41973. * Removes a uniform from this group.
  41974. *
  41975. * @param {Uniform} uniform - The uniform to remove.
  41976. * @return {UniformsGroup} A reference to this group.
  41977. */
  41978. removeUniform( uniform ) {
  41979. const index = this.uniforms.indexOf( uniform );
  41980. if ( index !== -1 ) {
  41981. this.uniforms.splice( index, 1 );
  41982. }
  41983. return this;
  41984. }
  41985. /**
  41986. * An array with the raw uniform values.
  41987. *
  41988. * @type {Array<number>}
  41989. */
  41990. get values() {
  41991. if ( this._values === null ) {
  41992. this._values = Array.from( this.buffer );
  41993. }
  41994. return this._values;
  41995. }
  41996. /**
  41997. * A Float32 array buffer with the uniform values.
  41998. *
  41999. * @type {Float32Array}
  42000. */
  42001. get buffer() {
  42002. let buffer = this._buffer;
  42003. if ( buffer === null ) {
  42004. const byteLength = this.byteLength;
  42005. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  42006. this._buffer = buffer;
  42007. }
  42008. return buffer;
  42009. }
  42010. /**
  42011. * The byte length of the buffer with correct buffer alignment.
  42012. *
  42013. * @type {number}
  42014. */
  42015. get byteLength() {
  42016. const bytesPerElement = this.bytesPerElement;
  42017. let offset = 0; // global buffer offset in bytes
  42018. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  42019. const uniform = this.uniforms[ i ];
  42020. const boundary = uniform.boundary;
  42021. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  42022. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  42023. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  42024. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  42025. offset += chunkPadding;
  42026. // Check for chunk overflow
  42027. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  42028. // Add padding to the end of the chunk
  42029. offset += ( GPU_CHUNK_BYTES - chunkStart );
  42030. }
  42031. uniform.offset = offset / bytesPerElement;
  42032. offset += itemSize;
  42033. }
  42034. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  42035. }
  42036. /**
  42037. * Updates this group by updating each uniform object of
  42038. * the internal uniform list. The uniform objects check if their
  42039. * values has actually changed so this method only returns
  42040. * `true` if there is a real value change.
  42041. *
  42042. * @return {boolean} Whether the uniforms have been updated and
  42043. * must be uploaded to the GPU.
  42044. */
  42045. update() {
  42046. let updated = false;
  42047. for ( const uniform of this.uniforms ) {
  42048. if ( this.updateByType( uniform ) === true ) {
  42049. updated = true;
  42050. }
  42051. }
  42052. return updated;
  42053. }
  42054. /**
  42055. * Updates a given uniform by calling an update method matching
  42056. * the uniforms type.
  42057. *
  42058. * @param {Uniform} uniform - The uniform to update.
  42059. * @return {boolean} Whether the uniform has been updated or not.
  42060. */
  42061. updateByType( uniform ) {
  42062. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  42063. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  42064. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  42065. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  42066. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  42067. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  42068. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  42069. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  42070. }
  42071. /**
  42072. * Updates a given Number uniform.
  42073. *
  42074. * @param {NumberUniform} uniform - The Number uniform.
  42075. * @return {boolean} Whether the uniform has been updated or not.
  42076. */
  42077. updateNumber( uniform ) {
  42078. let updated = false;
  42079. const a = this.values;
  42080. const v = uniform.getValue();
  42081. const offset = uniform.offset;
  42082. const type = uniform.getType();
  42083. if ( a[ offset ] !== v ) {
  42084. const b = this._getBufferForType( type );
  42085. b[ offset ] = a[ offset ] = v;
  42086. updated = true;
  42087. }
  42088. return updated;
  42089. }
  42090. /**
  42091. * Updates a given Vector2 uniform.
  42092. *
  42093. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  42094. * @return {boolean} Whether the uniform has been updated or not.
  42095. */
  42096. updateVector2( uniform ) {
  42097. let updated = false;
  42098. const a = this.values;
  42099. const v = uniform.getValue();
  42100. const offset = uniform.offset;
  42101. const type = uniform.getType();
  42102. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  42103. const b = this._getBufferForType( type );
  42104. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42105. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42106. updated = true;
  42107. }
  42108. return updated;
  42109. }
  42110. /**
  42111. * Updates a given Vector3 uniform.
  42112. *
  42113. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  42114. * @return {boolean} Whether the uniform has been updated or not.
  42115. */
  42116. updateVector3( uniform ) {
  42117. let updated = false;
  42118. const a = this.values;
  42119. const v = uniform.getValue();
  42120. const offset = uniform.offset;
  42121. const type = uniform.getType();
  42122. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  42123. const b = this._getBufferForType( type );
  42124. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42125. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42126. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42127. updated = true;
  42128. }
  42129. return updated;
  42130. }
  42131. /**
  42132. * Updates a given Vector4 uniform.
  42133. *
  42134. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  42135. * @return {boolean} Whether the uniform has been updated or not.
  42136. */
  42137. updateVector4( uniform ) {
  42138. let updated = false;
  42139. const a = this.values;
  42140. const v = uniform.getValue();
  42141. const offset = uniform.offset;
  42142. const type = uniform.getType();
  42143. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  42144. const b = this._getBufferForType( type );
  42145. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42146. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42147. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42148. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  42149. updated = true;
  42150. }
  42151. return updated;
  42152. }
  42153. /**
  42154. * Updates a given Color uniform.
  42155. *
  42156. * @param {ColorUniform} uniform - The Color uniform.
  42157. * @return {boolean} Whether the uniform has been updated or not.
  42158. */
  42159. updateColor( uniform ) {
  42160. let updated = false;
  42161. const a = this.values;
  42162. const c = uniform.getValue();
  42163. const offset = uniform.offset;
  42164. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  42165. const b = this.buffer;
  42166. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  42167. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  42168. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  42169. updated = true;
  42170. }
  42171. return updated;
  42172. }
  42173. /**
  42174. * Updates a given Matrix3 uniform.
  42175. *
  42176. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  42177. * @return {boolean} Whether the uniform has been updated or not.
  42178. */
  42179. updateMatrix3( uniform ) {
  42180. let updated = false;
  42181. const a = this.values;
  42182. const e = uniform.getValue().elements;
  42183. const offset = uniform.offset;
  42184. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  42185. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  42186. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  42187. const b = this.buffer;
  42188. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  42189. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  42190. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  42191. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  42192. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  42193. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  42194. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  42195. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  42196. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  42197. updated = true;
  42198. }
  42199. return updated;
  42200. }
  42201. /**
  42202. * Updates a given Matrix4 uniform.
  42203. *
  42204. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  42205. * @return {boolean} Whether the uniform has been updated or not.
  42206. */
  42207. updateMatrix4( uniform ) {
  42208. let updated = false;
  42209. const a = this.values;
  42210. const e = uniform.getValue().elements;
  42211. const offset = uniform.offset;
  42212. if ( arraysEqual( a, e, offset ) === false ) {
  42213. const b = this.buffer;
  42214. b.set( e, offset );
  42215. setArray( a, e, offset );
  42216. updated = true;
  42217. }
  42218. return updated;
  42219. }
  42220. /**
  42221. * Returns a typed array that matches the given data type.
  42222. *
  42223. * @param {string} type - The data type.
  42224. * @return {TypedArray} The typed array.
  42225. */
  42226. _getBufferForType( type ) {
  42227. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  42228. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  42229. return this.buffer;
  42230. }
  42231. }
  42232. /**
  42233. * Sets the values of the second array to the first array.
  42234. *
  42235. * @private
  42236. * @param {TypedArray} a - The first array.
  42237. * @param {TypedArray} b - The second array.
  42238. * @param {number} offset - An index offset for the first array.
  42239. */
  42240. function setArray( a, b, offset ) {
  42241. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42242. a[ offset + i ] = b[ i ];
  42243. }
  42244. }
  42245. /**
  42246. * Returns `true` if the given arrays are equal.
  42247. *
  42248. * @private
  42249. * @param {TypedArray} a - The first array.
  42250. * @param {TypedArray} b - The second array.
  42251. * @param {number} offset - An index offset for the first array.
  42252. * @return {boolean} Whether the given arrays are equal or not.
  42253. */
  42254. function arraysEqual( a, b, offset ) {
  42255. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42256. if ( a[ offset + i ] !== b[ i ] ) return false;
  42257. }
  42258. return true;
  42259. }
  42260. let _id$3 = 0;
  42261. /**
  42262. * A special form of uniforms group that represents
  42263. * the individual uniforms as node-based uniforms.
  42264. *
  42265. * @private
  42266. * @augments UniformsGroup
  42267. */
  42268. class NodeUniformsGroup extends UniformsGroup {
  42269. /**
  42270. * Constructs a new node-based uniforms group.
  42271. *
  42272. * @param {string} name - The group's name.
  42273. * @param {UniformGroupNode} groupNode - The uniform group node.
  42274. */
  42275. constructor( name, groupNode ) {
  42276. super( name );
  42277. /**
  42278. * The group's ID.
  42279. *
  42280. * @type {number}
  42281. */
  42282. this.id = _id$3 ++;
  42283. /**
  42284. * The uniform group node.
  42285. *
  42286. * @type {UniformGroupNode}
  42287. */
  42288. this.groupNode = groupNode;
  42289. /**
  42290. * This flag can be used for type testing.
  42291. *
  42292. * @type {boolean}
  42293. * @readonly
  42294. * @default true
  42295. */
  42296. this.isNodeUniformsGroup = true;
  42297. }
  42298. }
  42299. /**
  42300. * Represents a sampler binding type.
  42301. *
  42302. * @private
  42303. * @augments Binding
  42304. */
  42305. class Sampler extends Binding {
  42306. /**
  42307. * Constructs a new sampler.
  42308. *
  42309. * @param {string} name - The samplers's name.
  42310. * @param {?Texture} texture - The texture this binding is referring to.
  42311. */
  42312. constructor( name, texture ) {
  42313. super( name );
  42314. /**
  42315. * The texture the sampler is referring to.
  42316. *
  42317. * @private
  42318. * @type {?Texture}
  42319. */
  42320. this._texture = null;
  42321. /**
  42322. * An event listener which is added to {@link texture}'s dispose event.
  42323. *
  42324. * @private
  42325. * @type {Function}
  42326. */
  42327. this._onTextureDispose = () => {
  42328. this.generation = null;
  42329. this.version = 0;
  42330. };
  42331. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  42332. this.texture = texture;
  42333. /**
  42334. * The binding's version.
  42335. *
  42336. * @type {number}
  42337. */
  42338. this.version = texture ? texture.version : 0;
  42339. /**
  42340. * The binding's generation which is an additional version
  42341. * qualifier.
  42342. *
  42343. * @type {?number}
  42344. * @default null
  42345. */
  42346. this.generation = null;
  42347. /**
  42348. * The binding's sampler key.
  42349. *
  42350. * @type {string}
  42351. * @default ''
  42352. */
  42353. this.samplerKey = '';
  42354. /**
  42355. * This flag can be used for type testing.
  42356. *
  42357. * @type {boolean}
  42358. * @readonly
  42359. * @default true
  42360. */
  42361. this.isSampler = true;
  42362. }
  42363. /**
  42364. * Sets the texture of this sampler.
  42365. *
  42366. * @param {Texture} value - The texture to set.
  42367. */
  42368. set texture( value ) {
  42369. if ( this._texture === value ) return;
  42370. if ( this._texture ) {
  42371. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  42372. }
  42373. this._texture = value;
  42374. this.generation = null;
  42375. this.version = 0;
  42376. if ( this._texture ) {
  42377. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  42378. }
  42379. }
  42380. /**
  42381. * Gets the texture of this sampler.
  42382. * @return {?Texture} The texture.
  42383. */
  42384. get texture() {
  42385. return this._texture;
  42386. }
  42387. /**
  42388. * Updates the binding.
  42389. *
  42390. * @return {boolean} Whether the texture has been updated and must be
  42391. * uploaded to the GPU.
  42392. */
  42393. update() {
  42394. const { texture, version } = this;
  42395. if ( version !== texture.version ) {
  42396. this.version = texture.version;
  42397. return true;
  42398. }
  42399. return false;
  42400. }
  42401. clone() {
  42402. const clonedSampler = super.clone();
  42403. // fix dispose handler for cloned instances
  42404. // TODO: Find better solution, see #31747
  42405. clonedSampler._texture = null;
  42406. clonedSampler._onTextureDispose = () => {
  42407. clonedSampler.generation = null;
  42408. clonedSampler.version = 0;
  42409. };
  42410. clonedSampler.texture = this.texture;
  42411. return clonedSampler;
  42412. }
  42413. }
  42414. let _id$2 = 0;
  42415. /**
  42416. * Represents a sampled texture binding type.
  42417. *
  42418. * @private
  42419. * @augments Sampler
  42420. */
  42421. class SampledTexture extends Sampler {
  42422. /**
  42423. * Constructs a new sampled texture.
  42424. *
  42425. * @param {string} name - The sampled texture's name.
  42426. * @param {?Texture} texture - The texture this binding is referring to.
  42427. */
  42428. constructor( name, texture ) {
  42429. super( name, texture );
  42430. /**
  42431. * This identifier.
  42432. *
  42433. * @type {number}
  42434. */
  42435. this.id = _id$2 ++;
  42436. /**
  42437. * Whether the texture is a storage texture or not.
  42438. *
  42439. * @type {boolean}
  42440. * @default false
  42441. */
  42442. this.store = false;
  42443. /**
  42444. * The mip level to bind for storage textures.
  42445. *
  42446. * @type {number}
  42447. * @default 0
  42448. */
  42449. this.mipLevel = 0;
  42450. /**
  42451. * This flag can be used for type testing.
  42452. *
  42453. * @type {boolean}
  42454. * @readonly
  42455. * @default true
  42456. */
  42457. this.isSampledTexture = true;
  42458. }
  42459. }
  42460. /**
  42461. * A special form of sampled texture binding type.
  42462. * It's texture value is managed by a node object.
  42463. *
  42464. * @private
  42465. * @augments SampledTexture
  42466. */
  42467. class NodeSampledTexture extends SampledTexture {
  42468. /**
  42469. * Constructs a new node-based sampled texture.
  42470. *
  42471. * @param {string} name - The textures's name.
  42472. * @param {TextureNode} textureNode - The texture node.
  42473. * @param {UniformGroupNode} groupNode - The uniform group node.
  42474. * @param {?string} [access=null] - The access type.
  42475. */
  42476. constructor( name, textureNode, groupNode, access = null ) {
  42477. super( name, textureNode ? textureNode.value : null );
  42478. /**
  42479. * The texture node.
  42480. *
  42481. * @type {TextureNode}
  42482. */
  42483. this.textureNode = textureNode;
  42484. /**
  42485. * The uniform group node.
  42486. *
  42487. * @type {UniformGroupNode}
  42488. */
  42489. this.groupNode = groupNode;
  42490. /**
  42491. * The access type.
  42492. *
  42493. * @type {?string}
  42494. * @default null
  42495. */
  42496. this.access = access;
  42497. }
  42498. /**
  42499. * Updates the binding.
  42500. *
  42501. * @return {boolean} Whether the texture has been updated and must be
  42502. * uploaded to the GPU.
  42503. */
  42504. update() {
  42505. const { textureNode } = this;
  42506. if ( this.texture !== textureNode.value ) {
  42507. this.texture = textureNode.value;
  42508. return true;
  42509. }
  42510. return super.update();
  42511. }
  42512. }
  42513. /**
  42514. * A special form of sampled cube texture binding type.
  42515. * It's texture value is managed by a node object.
  42516. *
  42517. * @private
  42518. * @augments NodeSampledTexture
  42519. */
  42520. class NodeSampledCubeTexture extends NodeSampledTexture {
  42521. /**
  42522. * Constructs a new node-based sampled cube texture.
  42523. *
  42524. * @param {string} name - The textures's name.
  42525. * @param {TextureNode} textureNode - The texture node.
  42526. * @param {UniformGroupNode} groupNode - The uniform group node.
  42527. * @param {?string} [access=null] - The access type.
  42528. */
  42529. constructor( name, textureNode, groupNode, access = null ) {
  42530. super( name, textureNode, groupNode, access );
  42531. /**
  42532. * This flag can be used for type testing.
  42533. *
  42534. * @type {boolean}
  42535. * @readonly
  42536. * @default true
  42537. */
  42538. this.isSampledCubeTexture = true;
  42539. }
  42540. }
  42541. /**
  42542. * A special form of sampled 3D texture binding type.
  42543. * It's texture value is managed by a node object.
  42544. *
  42545. * @private
  42546. * @augments NodeSampledTexture
  42547. */
  42548. class NodeSampledTexture3D extends NodeSampledTexture {
  42549. /**
  42550. * Constructs a new node-based sampled 3D texture.
  42551. *
  42552. * @param {string} name - The textures's name.
  42553. * @param {TextureNode} textureNode - The texture node.
  42554. * @param {UniformGroupNode} groupNode - The uniform group node.
  42555. * @param {?string} [access=null] - The access type.
  42556. */
  42557. constructor( name, textureNode, groupNode, access = null ) {
  42558. super( name, textureNode, groupNode, access );
  42559. /**
  42560. * This flag can be used for type testing.
  42561. *
  42562. * @type {boolean}
  42563. * @readonly
  42564. * @default true
  42565. */
  42566. this.isSampledTexture3D = true;
  42567. }
  42568. }
  42569. const glslPolyfills = {
  42570. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( int x ) { return floatBitsToInt( uintBitsToFloat( x ) ); }' ),
  42571. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' )
  42572. };
  42573. const glslMethods = {
  42574. textureDimensions: 'textureSize',
  42575. equals: 'equal',
  42576. bitcast_float_int: 'floatBitsToInt',
  42577. bitcast_int_float: 'intBitsToFloat',
  42578. bitcast_uint_float: 'uintBitsToFloat',
  42579. bitcast_float_uint: 'floatBitsToUint',
  42580. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  42581. bitcast_int_uint: 'tsl_bitcast_int_to_uint'
  42582. };
  42583. const precisionLib = {
  42584. low: 'lowp',
  42585. medium: 'mediump',
  42586. high: 'highp'
  42587. };
  42588. const supports$1 = {
  42589. swizzleAssign: true,
  42590. storageBuffer: false
  42591. };
  42592. const interpolationTypeMap = {
  42593. perspective: 'smooth',
  42594. linear: 'noperspective'
  42595. };
  42596. const interpolationModeMap = {
  42597. 'centroid': 'centroid'
  42598. };
  42599. const defaultPrecisions = `
  42600. precision highp float;
  42601. precision highp int;
  42602. precision highp sampler2D;
  42603. precision highp sampler3D;
  42604. precision highp samplerCube;
  42605. precision highp sampler2DArray;
  42606. precision highp usampler2D;
  42607. precision highp usampler3D;
  42608. precision highp usamplerCube;
  42609. precision highp usampler2DArray;
  42610. precision highp isampler2D;
  42611. precision highp isampler3D;
  42612. precision highp isamplerCube;
  42613. precision highp isampler2DArray;
  42614. precision lowp sampler2DShadow;
  42615. precision lowp sampler2DArrayShadow;
  42616. precision lowp samplerCubeShadow;
  42617. `;
  42618. /**
  42619. * A node builder targeting GLSL.
  42620. *
  42621. * This module generates GLSL shader code from node materials and also
  42622. * generates the respective bindings and vertex buffer definitions. These
  42623. * data are later used by the renderer to create render and compute pipelines
  42624. * for render objects.
  42625. *
  42626. * @augments NodeBuilder
  42627. */
  42628. class GLSLNodeBuilder extends NodeBuilder {
  42629. /**
  42630. * Constructs a new GLSL node builder renderer.
  42631. *
  42632. * @param {Object3D} object - The 3D object.
  42633. * @param {Renderer} renderer - The renderer.
  42634. */
  42635. constructor( object, renderer ) {
  42636. super( object, renderer, new GLSLNodeParser() );
  42637. /**
  42638. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  42639. * another dictionary which manages UBOs per group ('render','frame','object').
  42640. *
  42641. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  42642. */
  42643. this.uniformGroups = {};
  42644. /**
  42645. * An array that holds objects defining the varying and attribute data in
  42646. * context of Transform Feedback.
  42647. *
  42648. * @type {Array<Object<string,AttributeNode|string>>}
  42649. */
  42650. this.transforms = [];
  42651. /**
  42652. * A dictionary that holds for each shader stage a Map of used extensions.
  42653. *
  42654. * @type {Object<string,Map<string,Object>>}
  42655. */
  42656. this.extensions = {};
  42657. /**
  42658. * A dictionary that holds for each shader stage an Array of used builtins.
  42659. *
  42660. * @type {Object<string,Array<string>>}
  42661. */
  42662. this.builtins = { vertex: [], fragment: [], compute: [] };
  42663. }
  42664. /**
  42665. * Checks if the given texture requires a manual conversion to the working color space.
  42666. *
  42667. * @param {Texture} texture - The texture to check.
  42668. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  42669. */
  42670. needsToWorkingColorSpace( texture ) {
  42671. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42672. }
  42673. /**
  42674. * Includes the given method name into the current
  42675. * function node.
  42676. *
  42677. * @private
  42678. * @param {string} name - The method name to include.
  42679. * @return {CodeNode} The respective code node.
  42680. */
  42681. _include( name ) {
  42682. const codeNode = glslPolyfills[ name ];
  42683. codeNode.build( this );
  42684. this.addInclude( codeNode );
  42685. return codeNode;
  42686. }
  42687. /**
  42688. * Returns the native shader method name for a given generic name.
  42689. *
  42690. * @param {string} method - The method name to resolve.
  42691. * @return {string} The resolved GLSL method name.
  42692. */
  42693. getMethod( method ) {
  42694. if ( glslPolyfills[ method ] !== undefined ) {
  42695. this._include( method );
  42696. }
  42697. return glslMethods[ method ] || method;
  42698. }
  42699. /**
  42700. * Returns the bitcast method name for a given input and outputType.
  42701. *
  42702. * @param {string} type - The output type to bitcast to.
  42703. * @param {string} inputType - The input type of the.
  42704. * @return {string} The resolved WGSL bitcast invocation.
  42705. */
  42706. getBitcastMethod( type, inputType ) {
  42707. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  42708. }
  42709. /**
  42710. * Returns the native snippet for a ternary operation.
  42711. *
  42712. * @param {string} condSnippet - The condition determining which expression gets resolved.
  42713. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  42714. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  42715. * @return {string} The resolved method name.
  42716. */
  42717. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  42718. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  42719. }
  42720. /**
  42721. * Returns the output struct name. Not relevant for GLSL.
  42722. *
  42723. * @return {string}
  42724. */
  42725. getOutputStructName() {
  42726. return '';
  42727. }
  42728. /**
  42729. * Builds the given shader node.
  42730. *
  42731. * @param {ShaderNodeInternal} shaderNode - The shader node.
  42732. * @return {string} The GLSL function code.
  42733. */
  42734. buildFunctionCode( shaderNode ) {
  42735. const layout = shaderNode.layout;
  42736. const flowData = this.flowShaderNode( shaderNode );
  42737. const parameters = [];
  42738. for ( const input of layout.inputs ) {
  42739. parameters.push( this.getType( input.type ) + ' ' + input.name );
  42740. }
  42741. //
  42742. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  42743. ${ flowData.vars }
  42744. ${ flowData.code }
  42745. return ${ flowData.result };
  42746. }`;
  42747. //
  42748. return code;
  42749. }
  42750. /**
  42751. * Setups the Pixel Buffer Object (PBO) for the given storage
  42752. * buffer node.
  42753. *
  42754. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  42755. */
  42756. setupPBO( storageBufferNode ) {
  42757. const attribute = storageBufferNode.value;
  42758. if ( attribute.pbo === undefined ) {
  42759. const originalArray = attribute.array;
  42760. const numElements = attribute.count * attribute.itemSize;
  42761. const { itemSize } = attribute;
  42762. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  42763. let format = isInteger ? RedIntegerFormat : RedFormat;
  42764. if ( itemSize === 2 ) {
  42765. format = isInteger ? RGIntegerFormat : RGFormat;
  42766. } else if ( itemSize === 3 ) {
  42767. format = isInteger ? RGBIntegerFormat : RGBFormat;
  42768. } else if ( itemSize === 4 ) {
  42769. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  42770. }
  42771. const typeMap = {
  42772. Float32Array: FloatType,
  42773. Uint8Array: UnsignedByteType,
  42774. Uint16Array: UnsignedShortType,
  42775. Uint32Array: UnsignedIntType,
  42776. Int8Array: ByteType,
  42777. Int16Array: ShortType,
  42778. Int32Array: IntType,
  42779. Uint8ClampedArray: UnsignedByteType,
  42780. };
  42781. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  42782. let height = Math.ceil( ( numElements / itemSize ) / width );
  42783. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  42784. const newSize = width * height * itemSize;
  42785. const newArray = new originalArray.constructor( newSize );
  42786. newArray.set( originalArray, 0 );
  42787. attribute.array = newArray;
  42788. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  42789. pboTexture.needsUpdate = true;
  42790. pboTexture.isPBOTexture = true;
  42791. const pbo = new TextureNode( pboTexture, null, null );
  42792. pbo.setPrecision( 'high' );
  42793. attribute.pboNode = pbo;
  42794. attribute.pbo = pbo.value;
  42795. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42796. }
  42797. }
  42798. /**
  42799. * Returns a GLSL snippet that represents the property name of the given node.
  42800. *
  42801. * @param {Node} node - The node.
  42802. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42803. * @return {string} The property name.
  42804. */
  42805. getPropertyName( node, shaderStage = this.shaderStage ) {
  42806. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  42807. return shaderStage.charAt( 0 ) + '_' + node.name;
  42808. }
  42809. return super.getPropertyName( node, shaderStage );
  42810. }
  42811. /**
  42812. * Setups the Pixel Buffer Object (PBO) for the given storage
  42813. * buffer node.
  42814. *
  42815. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  42816. * @return {string} The property name.
  42817. */
  42818. generatePBO( storageArrayElementNode ) {
  42819. const { node, indexNode } = storageArrayElementNode;
  42820. const attribute = node.value;
  42821. if ( this.renderer.backend.has( attribute ) ) {
  42822. const attributeData = this.renderer.backend.get( attribute );
  42823. attributeData.pbo = attribute.pbo;
  42824. }
  42825. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42826. const textureName = this.getPropertyName( nodeUniform );
  42827. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  42828. const indexSnippet = indexNode.build( this, 'uint' );
  42829. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  42830. let propertyName = elementNodeData.propertyName;
  42831. if ( propertyName === undefined ) {
  42832. // property element
  42833. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  42834. propertyName = this.getPropertyName( nodeVar );
  42835. // property size
  42836. const bufferNodeData = this.getDataFromNode( node );
  42837. let propertySizeName = bufferNodeData.propertySizeName;
  42838. if ( propertySizeName === undefined ) {
  42839. propertySizeName = propertyName + 'Size';
  42840. this.getVarFromNode( node, propertySizeName, 'uint' );
  42841. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  42842. bufferNodeData.propertySizeName = propertySizeName;
  42843. }
  42844. //
  42845. const { itemSize } = attribute;
  42846. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  42847. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  42848. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  42849. //
  42850. let prefix = 'vec4';
  42851. if ( attribute.pbo.type === UnsignedIntType ) {
  42852. prefix = 'uvec4';
  42853. } else if ( attribute.pbo.type === IntType ) {
  42854. prefix = 'ivec4';
  42855. }
  42856. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  42857. elementNodeData.propertyName = propertyName;
  42858. }
  42859. return propertyName;
  42860. }
  42861. /**
  42862. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  42863. *
  42864. * @param {?Texture} texture - The texture.
  42865. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42866. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42867. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42868. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42869. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42870. * @return {string} The GLSL snippet.
  42871. */
  42872. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  42873. if ( levelSnippet === null ) levelSnippet = '0';
  42874. let snippet;
  42875. if ( depthSnippet ) {
  42876. if ( offsetSnippet ) {
  42877. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  42878. } else {
  42879. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  42880. }
  42881. } else {
  42882. if ( offsetSnippet ) {
  42883. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42884. } else {
  42885. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42886. }
  42887. }
  42888. if ( texture !== null && texture.isDepthTexture ) {
  42889. snippet += '.x';
  42890. }
  42891. return snippet;
  42892. }
  42893. /**
  42894. * Generates the GLSL snippet for sampling/loading the given texture.
  42895. *
  42896. * @param {Texture} texture - The texture.
  42897. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42898. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42899. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42900. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42901. * @return {string} The GLSL snippet.
  42902. */
  42903. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  42904. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  42905. if ( texture.isDepthTexture ) {
  42906. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  42907. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  42908. }
  42909. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  42910. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  42911. }
  42912. /**
  42913. * Generates the GLSL snippet when sampling textures with explicit mip level.
  42914. *
  42915. * @param {Texture} texture - The texture.
  42916. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42917. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42918. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42919. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42920. * @return {string} The GLSL snippet.
  42921. */
  42922. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  42923. if ( offsetSnippet ) {
  42924. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42925. }
  42926. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  42927. }
  42928. /**
  42929. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  42930. *
  42931. * @param {Texture} texture - The texture.
  42932. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42933. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42934. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  42935. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42936. * @return {string} The GLSL snippet.
  42937. */
  42938. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  42939. if ( offsetSnippet ) {
  42940. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  42941. }
  42942. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  42943. }
  42944. /**
  42945. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  42946. *
  42947. * @param {Texture} texture - The texture.
  42948. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42949. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42950. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  42951. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42952. * @return {string} The GLSL snippet.
  42953. */
  42954. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  42955. if ( offsetSnippet ) {
  42956. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  42957. }
  42958. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42959. }
  42960. /**
  42961. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  42962. * against a reference value.
  42963. *
  42964. * @param {Texture} texture - The texture.
  42965. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42966. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42967. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  42968. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  42969. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42970. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42971. * @return {string} The GLSL snippet.
  42972. */
  42973. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  42974. if ( shaderStage === 'fragment' ) {
  42975. if ( depthSnippet ) {
  42976. if ( offsetSnippet ) {
  42977. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42978. }
  42979. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  42980. }
  42981. if ( offsetSnippet ) {
  42982. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42983. }
  42984. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  42985. } else {
  42986. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42987. }
  42988. }
  42989. /**
  42990. * Returns the variables of the given shader stage as a GLSL string.
  42991. *
  42992. * @param {string} shaderStage - The shader stage.
  42993. * @return {string} The GLSL snippet that defines the variables.
  42994. */
  42995. getVars( shaderStage ) {
  42996. const snippets = [];
  42997. const vars = this.vars[ shaderStage ];
  42998. if ( vars !== undefined ) {
  42999. for ( const variable of vars ) {
  43000. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  43001. }
  43002. }
  43003. return snippets.join( '\n\t' );
  43004. }
  43005. /**
  43006. * Returns the uniforms of the given shader stage as a GLSL string.
  43007. *
  43008. * @param {string} shaderStage - The shader stage.
  43009. * @return {string} The GLSL snippet that defines the uniforms.
  43010. */
  43011. getUniforms( shaderStage ) {
  43012. const uniforms = this.uniforms[ shaderStage ];
  43013. const bindingSnippets = [];
  43014. const uniformGroups = {};
  43015. for ( const uniform of uniforms ) {
  43016. let snippet = null;
  43017. let group = false;
  43018. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  43019. const texture = uniform.node.value;
  43020. let typePrefix = '';
  43021. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  43022. if ( texture.type === UnsignedIntType ) {
  43023. typePrefix = 'u';
  43024. } else if ( texture.type === IntType ) {
  43025. typePrefix = 'i';
  43026. }
  43027. }
  43028. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  43029. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  43030. } else if ( texture.compareFunction ) {
  43031. if ( texture.isArrayTexture === true ) {
  43032. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  43033. } else {
  43034. snippet = `sampler2DShadow ${ uniform.name };`;
  43035. }
  43036. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43037. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  43038. } else {
  43039. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  43040. }
  43041. } else if ( uniform.type === 'cubeTexture' ) {
  43042. snippet = `samplerCube ${ uniform.name };`;
  43043. } else if ( uniform.type === 'buffer' ) {
  43044. const bufferNode = uniform.node;
  43045. const bufferType = this.getType( bufferNode.bufferType );
  43046. const bufferCount = bufferNode.bufferCount;
  43047. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  43048. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  43049. } else {
  43050. const vectorType = this.getVectorType( uniform.type );
  43051. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  43052. group = true;
  43053. }
  43054. const precision = uniform.node.precision;
  43055. if ( precision !== null ) {
  43056. snippet = precisionLib[ precision ] + ' ' + snippet;
  43057. }
  43058. if ( group ) {
  43059. snippet = '\t' + snippet;
  43060. const groupName = uniform.groupNode.name;
  43061. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  43062. groupSnippets.push( snippet );
  43063. } else {
  43064. snippet = 'uniform ' + snippet;
  43065. bindingSnippets.push( snippet );
  43066. }
  43067. }
  43068. let output = '';
  43069. for ( const name in uniformGroups ) {
  43070. const groupSnippets = uniformGroups[ name ];
  43071. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  43072. }
  43073. output += bindingSnippets.join( '\n' );
  43074. return output;
  43075. }
  43076. /**
  43077. * Returns the type for a given buffer attribute.
  43078. *
  43079. * @param {BufferAttribute} attribute - The buffer attribute.
  43080. * @return {string} The type.
  43081. */
  43082. getTypeFromAttribute( attribute ) {
  43083. let nodeType = super.getTypeFromAttribute( attribute );
  43084. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  43085. let dataAttribute = attribute;
  43086. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  43087. const array = dataAttribute.array;
  43088. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  43089. nodeType = nodeType.slice( 1 );
  43090. }
  43091. }
  43092. return nodeType;
  43093. }
  43094. /**
  43095. * Returns the shader attributes of the given shader stage as a GLSL string.
  43096. *
  43097. * @param {string} shaderStage - The shader stage.
  43098. * @return {string} The GLSL snippet that defines the shader attributes.
  43099. */
  43100. getAttributes( shaderStage ) {
  43101. let snippet = '';
  43102. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43103. const attributes = this.getAttributesArray();
  43104. let location = 0;
  43105. for ( const attribute of attributes ) {
  43106. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  43107. }
  43108. }
  43109. return snippet;
  43110. }
  43111. /**
  43112. * Returns the members of the given struct type node as a GLSL string.
  43113. *
  43114. * @param {StructTypeNode} struct - The struct type node.
  43115. * @return {string} The GLSL snippet that defines the struct members.
  43116. */
  43117. getStructMembers( struct ) {
  43118. const snippets = [];
  43119. for ( const member of struct.members ) {
  43120. snippets.push( `\t${ member.type } ${ member.name };` );
  43121. }
  43122. return snippets.join( '\n' );
  43123. }
  43124. /**
  43125. * Returns the structs of the given shader stage as a GLSL string.
  43126. *
  43127. * @param {string} shaderStage - The shader stage.
  43128. * @return {string} The GLSL snippet that defines the structs.
  43129. */
  43130. getStructs( shaderStage ) {
  43131. const snippets = [];
  43132. const structs = this.structs[ shaderStage ];
  43133. const outputSnippet = [];
  43134. for ( const struct of structs ) {
  43135. if ( struct.output ) {
  43136. for ( const member of struct.members ) {
  43137. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  43138. }
  43139. } else {
  43140. let snippet = 'struct ' + struct.name + ' {\n';
  43141. snippet += this.getStructMembers( struct );
  43142. snippet += '\n};\n';
  43143. snippets.push( snippet );
  43144. }
  43145. }
  43146. if ( outputSnippet.length === 0 ) {
  43147. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  43148. }
  43149. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  43150. }
  43151. /**
  43152. * Returns the varyings of the given shader stage as a GLSL string.
  43153. *
  43154. * @param {string} shaderStage - The shader stage.
  43155. * @return {string} The GLSL snippet that defines the varyings.
  43156. */
  43157. getVaryings( shaderStage ) {
  43158. let snippet = '';
  43159. const varyings = this.varyings;
  43160. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43161. for ( const varying of varyings ) {
  43162. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  43163. const type = this.getType( varying.type );
  43164. if ( varying.needsInterpolation ) {
  43165. if ( varying.interpolationType ) {
  43166. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43167. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43168. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  43169. } else {
  43170. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43171. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  43172. }
  43173. } else {
  43174. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  43175. }
  43176. }
  43177. } else if ( shaderStage === 'fragment' ) {
  43178. for ( const varying of varyings ) {
  43179. if ( varying.needsInterpolation ) {
  43180. const type = this.getType( varying.type );
  43181. if ( varying.interpolationType ) {
  43182. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43183. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43184. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  43185. } else {
  43186. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43187. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  43188. }
  43189. }
  43190. }
  43191. }
  43192. for ( const builtin of this.builtins[ shaderStage ] ) {
  43193. snippet += `${builtin};\n`;
  43194. }
  43195. return snippet;
  43196. }
  43197. /**
  43198. * Returns the vertex index builtin.
  43199. *
  43200. * @return {string} The vertex index.
  43201. */
  43202. getVertexIndex() {
  43203. return 'uint( gl_VertexID )';
  43204. }
  43205. /**
  43206. * Contextually returns either the vertex stage instance index builtin
  43207. * or the linearized index of an compute invocation within a grid of workgroups.
  43208. *
  43209. * @return {string} The instance index.
  43210. */
  43211. getInstanceIndex() {
  43212. return 'uint( gl_InstanceID )';
  43213. }
  43214. /**
  43215. * Returns a builtin representing the index of an invocation within its workgroup.
  43216. *
  43217. * @return {string} The invocation local index.
  43218. */
  43219. getInvocationLocalIndex() {
  43220. const workgroupSize = this.object.workgroupSize;
  43221. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  43222. return `uint( gl_InstanceID ) % ${size}u`;
  43223. }
  43224. /**
  43225. * Returns a builtin representing the size of a subgroup within the current shader.
  43226. */
  43227. getSubgroupSize() {
  43228. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  43229. }
  43230. /**
  43231. * Returns a builtin representing the index of an invocation within its subgroup.
  43232. */
  43233. getInvocationSubgroupIndex() {
  43234. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  43235. }
  43236. /**
  43237. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  43238. */
  43239. getSubgroupIndex() {
  43240. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  43241. }
  43242. /**
  43243. * Returns the draw index builtin.
  43244. *
  43245. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  43246. */
  43247. getDrawIndex() {
  43248. const extensions = this.renderer.backend.extensions;
  43249. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  43250. return 'uint( gl_DrawID )';
  43251. }
  43252. return null;
  43253. }
  43254. /**
  43255. * Returns the front facing builtin.
  43256. *
  43257. * @return {string} The front facing builtin.
  43258. */
  43259. getFrontFacing() {
  43260. return 'gl_FrontFacing';
  43261. }
  43262. /**
  43263. * Returns the frag coord builtin.
  43264. *
  43265. * @return {string} The frag coord builtin.
  43266. */
  43267. getFragCoord() {
  43268. return 'gl_FragCoord.xy';
  43269. }
  43270. /**
  43271. * Returns the frag depth builtin.
  43272. *
  43273. * @return {string} The frag depth builtin.
  43274. */
  43275. getFragDepth() {
  43276. return 'gl_FragDepth';
  43277. }
  43278. /**
  43279. * Enables the given extension.
  43280. *
  43281. * @param {string} name - The extension name.
  43282. * @param {string} behavior - The extension behavior.
  43283. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  43284. */
  43285. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  43286. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  43287. if ( map.has( name ) === false ) {
  43288. map.set( name, {
  43289. name,
  43290. behavior
  43291. } );
  43292. }
  43293. }
  43294. /**
  43295. * Returns the enabled extensions of the given shader stage as a GLSL string.
  43296. *
  43297. * @param {string} shaderStage - The shader stage.
  43298. * @return {string} The GLSL snippet that defines the enabled extensions.
  43299. */
  43300. getExtensions( shaderStage ) {
  43301. const snippets = [];
  43302. if ( shaderStage === 'vertex' ) {
  43303. const ext = this.renderer.backend.extensions;
  43304. const isBatchedMesh = this.object.isBatchedMesh;
  43305. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  43306. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  43307. }
  43308. }
  43309. const extensions = this.extensions[ shaderStage ];
  43310. if ( extensions !== undefined ) {
  43311. for ( const { name, behavior } of extensions.values() ) {
  43312. snippets.push( `#extension ${name} : ${behavior}` );
  43313. }
  43314. }
  43315. return snippets.join( '\n' );
  43316. }
  43317. /**
  43318. * Returns the clip distances builtin.
  43319. *
  43320. * @return {string} The clip distances builtin.
  43321. */
  43322. getClipDistance() {
  43323. return 'gl_ClipDistance';
  43324. }
  43325. /**
  43326. * Whether the requested feature is available or not.
  43327. *
  43328. * @param {string} name - The requested feature.
  43329. * @return {boolean} Whether the requested feature is supported or not.
  43330. */
  43331. isAvailable( name ) {
  43332. let result = supports$1[ name ];
  43333. if ( result === undefined ) {
  43334. let extensionName;
  43335. result = false;
  43336. switch ( name ) {
  43337. case 'float32Filterable':
  43338. extensionName = 'OES_texture_float_linear';
  43339. break;
  43340. case 'clipDistance':
  43341. extensionName = 'WEBGL_clip_cull_distance';
  43342. break;
  43343. }
  43344. if ( extensionName !== undefined ) {
  43345. const extensions = this.renderer.backend.extensions;
  43346. if ( extensions.has( extensionName ) ) {
  43347. extensions.get( extensionName );
  43348. result = true;
  43349. }
  43350. }
  43351. supports$1[ name ] = result;
  43352. }
  43353. return result;
  43354. }
  43355. /**
  43356. * Whether to flip texture data along its vertical axis or not.
  43357. *
  43358. * @return {boolean} Returns always `true` in context of GLSL.
  43359. */
  43360. isFlipY() {
  43361. return true;
  43362. }
  43363. /**
  43364. * Enables hardware clipping.
  43365. *
  43366. * @param {string} planeCount - The clipping plane count.
  43367. */
  43368. enableHardwareClipping( planeCount ) {
  43369. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  43370. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  43371. }
  43372. /**
  43373. * Enables multiview.
  43374. */
  43375. enableMultiview() {
  43376. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  43377. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  43378. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  43379. }
  43380. /**
  43381. * Registers a transform in context of Transform Feedback.
  43382. *
  43383. * @param {string} varyingName - The varying name.
  43384. * @param {AttributeNode} attributeNode - The attribute node.
  43385. */
  43386. registerTransform( varyingName, attributeNode ) {
  43387. this.transforms.push( { varyingName, attributeNode } );
  43388. }
  43389. /**
  43390. * Returns the transforms of the given shader stage as a GLSL string.
  43391. *
  43392. * @param {string} shaderStage - The shader stage.
  43393. * @return {string} The GLSL snippet that defines the transforms.
  43394. */
  43395. getTransforms( /* shaderStage */ ) {
  43396. const transforms = this.transforms;
  43397. let snippet = '';
  43398. for ( let i = 0; i < transforms.length; i ++ ) {
  43399. const transform = transforms[ i ];
  43400. const attributeName = this.getPropertyName( transform.attributeNode );
  43401. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  43402. }
  43403. return snippet;
  43404. }
  43405. /**
  43406. * Returns a GLSL struct based on the given name and variables.
  43407. *
  43408. * @private
  43409. * @param {string} name - The struct name.
  43410. * @param {string} vars - The struct variables.
  43411. * @return {string} The GLSL snippet representing a struct.
  43412. */
  43413. _getGLSLUniformStruct( name, vars ) {
  43414. return `
  43415. layout( std140 ) uniform ${name} {
  43416. ${vars}
  43417. };`;
  43418. }
  43419. /**
  43420. * Returns a GLSL vertex shader based on the given shader data.
  43421. *
  43422. * @private
  43423. * @param {Object} shaderData - The shader data.
  43424. * @return {string} The vertex shader.
  43425. */
  43426. _getGLSLVertexCode( shaderData ) {
  43427. return `#version 300 es
  43428. ${ this.getSignature() }
  43429. // extensions
  43430. ${shaderData.extensions}
  43431. // precision
  43432. ${ defaultPrecisions }
  43433. // uniforms
  43434. ${shaderData.uniforms}
  43435. // varyings
  43436. ${shaderData.varyings}
  43437. // attributes
  43438. ${shaderData.attributes}
  43439. // codes
  43440. ${shaderData.codes}
  43441. void main() {
  43442. // vars
  43443. ${shaderData.vars}
  43444. // transforms
  43445. ${shaderData.transforms}
  43446. // flow
  43447. ${shaderData.flow}
  43448. gl_PointSize = 1.0;
  43449. }
  43450. `;
  43451. }
  43452. /**
  43453. * Returns a GLSL fragment shader based on the given shader data.
  43454. *
  43455. * @private
  43456. * @param {Object} shaderData - The shader data.
  43457. * @return {string} The vertex shader.
  43458. */
  43459. _getGLSLFragmentCode( shaderData ) {
  43460. return `#version 300 es
  43461. ${ this.getSignature() }
  43462. // extensions
  43463. ${shaderData.extensions}
  43464. // precision
  43465. ${ defaultPrecisions }
  43466. // structs
  43467. ${shaderData.structs}
  43468. // uniforms
  43469. ${shaderData.uniforms}
  43470. // varyings
  43471. ${shaderData.varyings}
  43472. // codes
  43473. ${shaderData.codes}
  43474. void main() {
  43475. // vars
  43476. ${shaderData.vars}
  43477. // flow
  43478. ${shaderData.flow}
  43479. }
  43480. `;
  43481. }
  43482. /**
  43483. * Controls the code build of the shader stages.
  43484. */
  43485. buildCode() {
  43486. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43487. this.sortBindingGroups();
  43488. for ( const shaderStage in shadersData ) {
  43489. let flow = '// code\n\n';
  43490. flow += this.flowCode[ shaderStage ];
  43491. const flowNodes = this.flowNodes[ shaderStage ];
  43492. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43493. for ( const node of flowNodes ) {
  43494. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43495. const slotName = node.name;
  43496. if ( slotName ) {
  43497. if ( flow.length > 0 ) flow += '\n';
  43498. flow += `\t// flow -> ${ slotName }\n\t`;
  43499. }
  43500. flow += `${ flowSlotData.code }\n\t`;
  43501. if ( node === mainNode && shaderStage !== 'compute' ) {
  43502. flow += '// result\n\t';
  43503. if ( shaderStage === 'vertex' ) {
  43504. flow += 'gl_Position = ';
  43505. flow += `${ flowSlotData.result };`;
  43506. } else if ( shaderStage === 'fragment' ) {
  43507. if ( ! node.outputNode.isOutputStructNode ) {
  43508. flow += 'fragColor = ';
  43509. flow += `${ flowSlotData.result };`;
  43510. }
  43511. }
  43512. }
  43513. }
  43514. const stageData = shadersData[ shaderStage ];
  43515. stageData.extensions = this.getExtensions( shaderStage );
  43516. stageData.uniforms = this.getUniforms( shaderStage );
  43517. stageData.attributes = this.getAttributes( shaderStage );
  43518. stageData.varyings = this.getVaryings( shaderStage );
  43519. stageData.vars = this.getVars( shaderStage );
  43520. stageData.structs = this.getStructs( shaderStage );
  43521. stageData.codes = this.getCodes( shaderStage );
  43522. stageData.transforms = this.getTransforms( shaderStage );
  43523. stageData.flow = flow;
  43524. }
  43525. if ( this.material !== null ) {
  43526. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  43527. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  43528. } else {
  43529. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  43530. }
  43531. }
  43532. /**
  43533. * This method is one of the more important ones since it's responsible
  43534. * for generating a matching binding instance for the given uniform node.
  43535. *
  43536. * These bindings are later used in the renderer to create bind groups
  43537. * and layouts.
  43538. *
  43539. * @param {UniformNode} node - The uniform node.
  43540. * @param {string} type - The node data type.
  43541. * @param {string} shaderStage - The shader stage.
  43542. * @param {?string} [name=null] - An optional uniform name.
  43543. * @return {NodeUniform} The node uniform object.
  43544. */
  43545. getUniformFromNode( node, type, shaderStage, name = null ) {
  43546. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43547. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43548. let uniformGPU = nodeData.uniformGPU;
  43549. if ( uniformGPU === undefined ) {
  43550. const group = node.groupNode;
  43551. const groupName = group.name;
  43552. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43553. if ( type === 'texture' ) {
  43554. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  43555. bindings.push( uniformGPU );
  43556. } else if ( type === 'cubeTexture' ) {
  43557. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  43558. bindings.push( uniformGPU );
  43559. } else if ( type === 'texture3D' ) {
  43560. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  43561. bindings.push( uniformGPU );
  43562. } else if ( type === 'buffer' ) {
  43563. node.name = `NodeBuffer_${ node.id }`;
  43564. uniformNode.name = `buffer${ node.id }`;
  43565. const buffer = new NodeUniformBuffer( node, group );
  43566. buffer.name = node.name;
  43567. bindings.push( buffer );
  43568. uniformGPU = buffer;
  43569. } else {
  43570. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43571. let uniformsGroup = uniformsStage[ groupName ];
  43572. if ( uniformsGroup === undefined ) {
  43573. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  43574. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43575. uniformsStage[ groupName ] = uniformsGroup;
  43576. bindings.push( uniformsGroup );
  43577. }
  43578. uniformGPU = this.getNodeUniform( uniformNode, type );
  43579. uniformsGroup.addUniform( uniformGPU );
  43580. }
  43581. nodeData.uniformGPU = uniformGPU;
  43582. }
  43583. return uniformNode;
  43584. }
  43585. }
  43586. let _vector2 = null;
  43587. let _color4 = null;
  43588. /**
  43589. * Most of the rendering related logic is implemented in the
  43590. * {@link Renderer} module and related management components.
  43591. * Sometimes it is required though to execute commands which are
  43592. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  43593. * This abstract base class defines an interface that encapsulates
  43594. * all backend-related logic. Derived classes for each backend must
  43595. * implement the interface.
  43596. *
  43597. * @abstract
  43598. * @private
  43599. */
  43600. class Backend {
  43601. /**
  43602. * Constructs a new backend.
  43603. *
  43604. * @param {Object} parameters - An object holding parameters for the backend.
  43605. */
  43606. constructor( parameters = {} ) {
  43607. /**
  43608. * The parameters of the backend.
  43609. *
  43610. * @type {Object}
  43611. */
  43612. this.parameters = Object.assign( {}, parameters );
  43613. /**
  43614. * This weak map holds backend-specific data of objects
  43615. * like textures, attributes or render targets.
  43616. *
  43617. * @type {WeakMap<Object, Object>}
  43618. */
  43619. this.data = new WeakMap();
  43620. /**
  43621. * A reference to the renderer.
  43622. *
  43623. * @type {?Renderer}
  43624. * @default null
  43625. */
  43626. this.renderer = null;
  43627. /**
  43628. * A reference to the canvas element the renderer is drawing to.
  43629. *
  43630. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  43631. * @default null
  43632. */
  43633. this.domElement = null;
  43634. /**
  43635. * A reference to the timestamp query pool.
  43636. *
  43637. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  43638. */
  43639. this.timestampQueryPool = {
  43640. [ TimestampQuery.RENDER ]: null,
  43641. [ TimestampQuery.COMPUTE ]: null
  43642. };
  43643. /**
  43644. * Whether to track timestamps with a Timestamp Query API or not.
  43645. *
  43646. * @type {boolean}
  43647. * @default false
  43648. */
  43649. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43650. }
  43651. /**
  43652. * Initializes the backend so it is ready for usage. Concrete backends
  43653. * are supposed to implement their rendering context creation and related
  43654. * operations in this method.
  43655. *
  43656. * @async
  43657. * @param {Renderer} renderer - The renderer.
  43658. * @return {Promise} A Promise that resolves when the backend has been initialized.
  43659. */
  43660. async init( renderer ) {
  43661. this.renderer = renderer;
  43662. }
  43663. /**
  43664. * The coordinate system of the backend.
  43665. *
  43666. * @abstract
  43667. * @type {number}
  43668. * @readonly
  43669. */
  43670. get coordinateSystem() {}
  43671. // render context
  43672. /**
  43673. * This method is executed at the beginning of a render call and
  43674. * can be used by the backend to prepare the state for upcoming
  43675. * draw calls.
  43676. *
  43677. * @abstract
  43678. * @param {RenderContext} renderContext - The render context.
  43679. */
  43680. beginRender( /*renderContext*/ ) {}
  43681. /**
  43682. * This method is executed at the end of a render call and
  43683. * can be used by the backend to finalize work after draw
  43684. * calls.
  43685. *
  43686. * @abstract
  43687. * @param {RenderContext} renderContext - The render context.
  43688. */
  43689. finishRender( /*renderContext*/ ) {}
  43690. /**
  43691. * This method is executed at the beginning of a compute call and
  43692. * can be used by the backend to prepare the state for upcoming
  43693. * compute tasks.
  43694. *
  43695. * @abstract
  43696. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43697. */
  43698. beginCompute( /*computeGroup*/ ) {}
  43699. /**
  43700. * This method is executed at the end of a compute call and
  43701. * can be used by the backend to finalize work after compute
  43702. * tasks.
  43703. *
  43704. * @abstract
  43705. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43706. */
  43707. finishCompute( /*computeGroup*/ ) {}
  43708. // render object
  43709. /**
  43710. * Executes a draw command for the given render object.
  43711. *
  43712. * @abstract
  43713. * @param {RenderObject} renderObject - The render object to draw.
  43714. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43715. */
  43716. draw( /*renderObject, info*/ ) { }
  43717. // compute node
  43718. /**
  43719. * Executes a compute command for the given compute node.
  43720. *
  43721. * @abstract
  43722. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43723. * @param {Node} computeNode - The compute node.
  43724. * @param {Array<BindGroup>} bindings - The bindings.
  43725. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43726. */
  43727. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  43728. // program
  43729. /**
  43730. * Creates a shader program from the given programmable stage.
  43731. *
  43732. * @abstract
  43733. * @param {ProgrammableStage} program - The programmable stage.
  43734. */
  43735. createProgram( /*program*/ ) { }
  43736. /**
  43737. * Destroys the shader program of the given programmable stage.
  43738. *
  43739. * @abstract
  43740. * @param {ProgrammableStage} program - The programmable stage.
  43741. */
  43742. destroyProgram( /*program*/ ) { }
  43743. // bindings
  43744. /**
  43745. * Creates bindings from the given bind group definition.
  43746. *
  43747. * @abstract
  43748. * @param {BindGroup} bindGroup - The bind group.
  43749. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43750. * @param {number} cacheIndex - The cache index.
  43751. * @param {number} version - The version.
  43752. */
  43753. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43754. /**
  43755. * Updates the given bind group definition.
  43756. *
  43757. * @abstract
  43758. * @param {BindGroup} bindGroup - The bind group.
  43759. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43760. * @param {number} cacheIndex - The cache index.
  43761. * @param {number} version - The version.
  43762. */
  43763. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43764. /**
  43765. * Updates a buffer binding.
  43766. *
  43767. * @abstract
  43768. * @param {Buffer} binding - The buffer binding to update.
  43769. */
  43770. updateBinding( /*binding*/ ) { }
  43771. // pipeline
  43772. /**
  43773. * Creates a render pipeline for the given render object.
  43774. *
  43775. * @abstract
  43776. * @param {RenderObject} renderObject - The render object.
  43777. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43778. */
  43779. createRenderPipeline( /*renderObject, promises*/ ) { }
  43780. /**
  43781. * Creates a compute pipeline for the given compute node.
  43782. *
  43783. * @abstract
  43784. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43785. * @param {Array<BindGroup>} bindings - The bindings.
  43786. */
  43787. createComputePipeline( /*computePipeline, bindings*/ ) { }
  43788. // cache key
  43789. /**
  43790. * Returns `true` if the render pipeline requires an update.
  43791. *
  43792. * @abstract
  43793. * @param {RenderObject} renderObject - The render object.
  43794. * @return {boolean} Whether the render pipeline requires an update or not.
  43795. */
  43796. needsRenderUpdate( /*renderObject*/ ) { }
  43797. /**
  43798. * Returns a cache key that is used to identify render pipelines.
  43799. *
  43800. * @abstract
  43801. * @param {RenderObject} renderObject - The render object.
  43802. * @return {string} The cache key.
  43803. */
  43804. getRenderCacheKey( /*renderObject*/ ) { }
  43805. // node builder
  43806. /**
  43807. * Returns a node builder for the given render object.
  43808. *
  43809. * @abstract
  43810. * @param {RenderObject} renderObject - The render object.
  43811. * @param {Renderer} renderer - The renderer.
  43812. * @return {NodeBuilder} The node builder.
  43813. */
  43814. createNodeBuilder( /*renderObject, renderer*/ ) { }
  43815. // textures
  43816. /**
  43817. * Updates a GPU sampler for the given texture.
  43818. *
  43819. * @abstract
  43820. * @param {Texture} texture - The texture to update the sampler for.
  43821. * @return {string} The current sampler key.
  43822. */
  43823. updateSampler( /*texture*/ ) { }
  43824. /**
  43825. * Creates a default texture for the given texture that can be used
  43826. * as a placeholder until the actual texture is ready for usage.
  43827. *
  43828. * @abstract
  43829. * @param {Texture} texture - The texture to create a default texture for.
  43830. */
  43831. createDefaultTexture( /*texture*/ ) { }
  43832. /**
  43833. * Defines a texture on the GPU for the given texture object.
  43834. *
  43835. * @abstract
  43836. * @param {Texture} texture - The texture.
  43837. * @param {Object} [options={}] - Optional configuration parameter.
  43838. */
  43839. createTexture( /*texture, options={}*/ ) { }
  43840. /**
  43841. * Uploads the updated texture data to the GPU.
  43842. *
  43843. * @abstract
  43844. * @param {Texture} texture - The texture.
  43845. * @param {Object} [options={}] - Optional configuration parameter.
  43846. */
  43847. updateTexture( /*texture, options = {}*/ ) { }
  43848. /**
  43849. * Generates mipmaps for the given texture.
  43850. *
  43851. * @abstract
  43852. * @param {Texture} texture - The texture.
  43853. */
  43854. generateMipmaps( /*texture*/ ) { }
  43855. /**
  43856. * Destroys the GPU data for the given texture object.
  43857. *
  43858. * @abstract
  43859. * @param {Texture} texture - The texture.
  43860. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  43861. */
  43862. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  43863. /**
  43864. * Returns texture data as a typed array.
  43865. *
  43866. * @abstract
  43867. * @async
  43868. * @param {Texture} texture - The texture to copy.
  43869. * @param {number} x - The x coordinate of the copy origin.
  43870. * @param {number} y - The y coordinate of the copy origin.
  43871. * @param {number} width - The width of the copy.
  43872. * @param {number} height - The height of the copy.
  43873. * @param {number} faceIndex - The face index.
  43874. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43875. */
  43876. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  43877. /**
  43878. * Copies data of the given source texture to the given destination texture.
  43879. *
  43880. * @abstract
  43881. * @param {Texture} srcTexture - The source texture.
  43882. * @param {Texture} dstTexture - The destination texture.
  43883. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43884. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43885. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43886. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43887. */
  43888. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  43889. /**
  43890. * Copies the current bound framebuffer to the given texture.
  43891. *
  43892. * @abstract
  43893. * @param {Texture} texture - The destination texture.
  43894. * @param {RenderContext} renderContext - The render context.
  43895. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43896. */
  43897. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  43898. // attributes
  43899. /**
  43900. * Creates the GPU buffer of a shader attribute.
  43901. *
  43902. * @abstract
  43903. * @param {BufferAttribute} attribute - The buffer attribute.
  43904. */
  43905. createAttribute( /*attribute*/ ) { }
  43906. /**
  43907. * Creates the GPU buffer of an indexed shader attribute.
  43908. *
  43909. * @abstract
  43910. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43911. */
  43912. createIndexAttribute( /*attribute*/ ) { }
  43913. /**
  43914. * Creates the GPU buffer of a storage attribute.
  43915. *
  43916. * @abstract
  43917. * @param {BufferAttribute} attribute - The buffer attribute.
  43918. */
  43919. createStorageAttribute( /*attribute*/ ) { }
  43920. /**
  43921. * Updates the GPU buffer of a shader attribute.
  43922. *
  43923. * @abstract
  43924. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43925. */
  43926. updateAttribute( /*attribute*/ ) { }
  43927. /**
  43928. * Destroys the GPU buffer of a shader attribute.
  43929. *
  43930. * @abstract
  43931. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43932. */
  43933. destroyAttribute( /*attribute*/ ) { }
  43934. // canvas
  43935. /**
  43936. * Returns the backend's rendering context.
  43937. *
  43938. * @abstract
  43939. * @return {Object} The rendering context.
  43940. */
  43941. getContext() { }
  43942. /**
  43943. * Backends can use this method if they have to run
  43944. * logic when the renderer gets resized.
  43945. *
  43946. * @abstract
  43947. */
  43948. updateSize() { }
  43949. /**
  43950. * Updates the viewport with the values from the given render context.
  43951. *
  43952. * @abstract
  43953. * @param {RenderContext} renderContext - The render context.
  43954. */
  43955. updateViewport( /*renderContext*/ ) {}
  43956. // utils
  43957. /**
  43958. * Updates a unique identifier for the given render context that can be used
  43959. * to allocate resources like occlusion queries or timestamp queries.
  43960. *
  43961. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43962. */
  43963. updateTimeStampUID( abstractRenderContext ) {
  43964. const contextData = this.get( abstractRenderContext );
  43965. const frame = this.renderer.info.frame;
  43966. let prefix;
  43967. if ( abstractRenderContext.isComputeNode === true ) {
  43968. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  43969. } else {
  43970. prefix = 'r:' + this.renderer.info.render.frameCalls;
  43971. }
  43972. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  43973. }
  43974. /**
  43975. * Returns a unique identifier for the given render context that can be used
  43976. * to allocate resources like occlusion queries or timestamp queries.
  43977. *
  43978. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43979. * @return {string} The unique identifier.
  43980. */
  43981. getTimestampUID( abstractRenderContext ) {
  43982. return this.get( abstractRenderContext ).timestampUID;
  43983. }
  43984. /**
  43985. * Returns all timestamp frames for the given type.
  43986. *
  43987. * @param {string} type - The type of the time stamp.
  43988. * @return {Array<number>} The timestamp frames.
  43989. */
  43990. getTimestampFrames( type ) {
  43991. const queryPool = this.timestampQueryPool[ type ];
  43992. return queryPool ? queryPool.getTimestampFrames() : [];
  43993. }
  43994. /**
  43995. * Returns the query pool for the given uid.
  43996. *
  43997. * @param {string} uid - The unique identifier.
  43998. * @return {TimestampQueryPool} The query pool.
  43999. */
  44000. _getQueryPool( uid ) {
  44001. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  44002. const queryPool = this.timestampQueryPool[ type ];
  44003. return queryPool;
  44004. }
  44005. /**
  44006. * Returns the timestamp for the given uid.
  44007. *
  44008. * @param {string} uid - The unique identifier.
  44009. * @return {number} The timestamp.
  44010. */
  44011. getTimestamp( uid ) {
  44012. const queryPool = this._getQueryPool( uid );
  44013. return queryPool.getTimestamp( uid );
  44014. }
  44015. /**
  44016. * Returns `true` if a timestamp for the given uid is available.
  44017. *
  44018. * @param {string} uid - The unique identifier.
  44019. * @return {boolean} Whether the timestamp is available or not.
  44020. */
  44021. hasTimestamp( uid ) {
  44022. const queryPool = this._getQueryPool( uid );
  44023. return queryPool.hasTimestamp( uid );
  44024. }
  44025. /**
  44026. * Returns `true` if the given 3D object is fully occluded by other
  44027. * 3D objects in the scene. Backends must implement this method by using
  44028. * a Occlusion Query API.
  44029. *
  44030. * @abstract
  44031. * @param {RenderContext} renderContext - The render context.
  44032. * @param {Object3D} object - The 3D object to test.
  44033. * @return {boolean} Whether the 3D object is fully occluded or not.
  44034. */
  44035. isOccluded( /*renderContext, object*/ ) {}
  44036. /**
  44037. * Resolves the time stamp for the given render context and type.
  44038. *
  44039. * @async
  44040. * @abstract
  44041. * @param {string} [type='render'] - The type of the time stamp.
  44042. * @return {Promise<number>} A Promise that resolves with the time stamp.
  44043. */
  44044. async resolveTimestampsAsync( type = 'render' ) {
  44045. if ( ! this.trackTimestamp ) {
  44046. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  44047. return;
  44048. }
  44049. const queryPool = this.timestampQueryPool[ type ];
  44050. if ( ! queryPool ) {
  44051. return;
  44052. }
  44053. const duration = await queryPool.resolveQueriesAsync();
  44054. this.renderer.info[ type ].timestamp = duration;
  44055. return duration;
  44056. }
  44057. /**
  44058. * This method performs a readback operation by moving buffer data from
  44059. * a storage buffer attribute from the GPU to the CPU.
  44060. *
  44061. * @async
  44062. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44063. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44064. */
  44065. async getArrayBufferAsync( /* attribute */ ) {}
  44066. /**
  44067. * Checks if the given feature is supported by the backend.
  44068. *
  44069. * @async
  44070. * @abstract
  44071. * @param {string} name - The feature's name.
  44072. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44073. */
  44074. async hasFeatureAsync( /*name*/ ) { }
  44075. /**
  44076. * Checks if the given feature is supported by the backend.
  44077. *
  44078. * @abstract
  44079. * @param {string} name - The feature's name.
  44080. * @return {boolean} Whether the feature is supported or not.
  44081. */
  44082. hasFeature( /*name*/ ) {}
  44083. /**
  44084. * Returns the maximum anisotropy texture filtering value.
  44085. *
  44086. * @abstract
  44087. * @return {number} The maximum anisotropy texture filtering value.
  44088. */
  44089. getMaxAnisotropy() {}
  44090. /**
  44091. * Returns the drawing buffer size.
  44092. *
  44093. * @return {Vector2} The drawing buffer size.
  44094. */
  44095. getDrawingBufferSize() {
  44096. _vector2 = _vector2 || new Vector2();
  44097. return this.renderer.getDrawingBufferSize( _vector2 );
  44098. }
  44099. /**
  44100. * Defines the scissor test.
  44101. *
  44102. * @abstract
  44103. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44104. */
  44105. setScissorTest( /*boolean*/ ) { }
  44106. /**
  44107. * Returns the clear color and alpha into a single
  44108. * color object.
  44109. *
  44110. * @return {Color4} The clear color.
  44111. */
  44112. getClearColor() {
  44113. const renderer = this.renderer;
  44114. _color4 = _color4 || new Color4();
  44115. renderer.getClearColor( _color4 );
  44116. _color4.getRGB( _color4 );
  44117. return _color4;
  44118. }
  44119. /**
  44120. * Returns the DOM element. If no DOM element exists, the backend
  44121. * creates a new one.
  44122. *
  44123. * @return {HTMLCanvasElement} The DOM element.
  44124. */
  44125. getDomElement() {
  44126. let domElement = this.domElement;
  44127. if ( domElement === null ) {
  44128. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  44129. // OffscreenCanvas does not have setAttribute, see #22811
  44130. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  44131. this.domElement = domElement;
  44132. }
  44133. return domElement;
  44134. }
  44135. /**
  44136. * Sets a dictionary for the given object into the
  44137. * internal data structure.
  44138. *
  44139. * @param {Object} object - The object.
  44140. * @param {Object} value - The dictionary to set.
  44141. */
  44142. set( object, value ) {
  44143. this.data.set( object, value );
  44144. }
  44145. /**
  44146. * Returns the dictionary for the given object.
  44147. *
  44148. * @param {Object} object - The object.
  44149. * @return {Object} The object's dictionary.
  44150. */
  44151. get( object ) {
  44152. let map = this.data.get( object );
  44153. if ( map === undefined ) {
  44154. map = {};
  44155. this.data.set( object, map );
  44156. }
  44157. return map;
  44158. }
  44159. /**
  44160. * Checks if the given object has a dictionary
  44161. * with data defined.
  44162. *
  44163. * @param {Object} object - The object.
  44164. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  44165. */
  44166. has( object ) {
  44167. return this.data.has( object );
  44168. }
  44169. /**
  44170. * Deletes an object from the internal data structure.
  44171. *
  44172. * @param {Object} object - The object to delete.
  44173. */
  44174. delete( object ) {
  44175. this.data.delete( object );
  44176. }
  44177. /**
  44178. * Frees internal resources.
  44179. *
  44180. * @abstract
  44181. */
  44182. dispose() { }
  44183. }
  44184. let _id$1 = 0;
  44185. /**
  44186. * This module is internally used in context of compute shaders.
  44187. * This type of shader is not natively supported in WebGL 2 and
  44188. * thus implemented via Transform Feedback. `DualAttributeData`
  44189. * manages the related data.
  44190. *
  44191. * @private
  44192. */
  44193. class DualAttributeData {
  44194. constructor( attributeData, dualBuffer ) {
  44195. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  44196. this.type = attributeData.type;
  44197. this.bufferType = attributeData.bufferType;
  44198. this.pbo = attributeData.pbo;
  44199. this.byteLength = attributeData.byteLength;
  44200. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  44201. this.version = attributeData.version;
  44202. this.isInteger = attributeData.isInteger;
  44203. this.activeBufferIndex = 0;
  44204. this.baseId = attributeData.id;
  44205. }
  44206. get id() {
  44207. return `${ this.baseId }|${ this.activeBufferIndex }`;
  44208. }
  44209. get bufferGPU() {
  44210. return this.buffers[ this.activeBufferIndex ];
  44211. }
  44212. get transformBuffer() {
  44213. return this.buffers[ this.activeBufferIndex ^ 1 ];
  44214. }
  44215. switchBuffers() {
  44216. this.activeBufferIndex ^= 1;
  44217. }
  44218. }
  44219. /**
  44220. * A WebGL 2 backend utility module for managing shader attributes.
  44221. *
  44222. * @private
  44223. */
  44224. class WebGLAttributeUtils {
  44225. /**
  44226. * Constructs a new utility object.
  44227. *
  44228. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44229. */
  44230. constructor( backend ) {
  44231. /**
  44232. * A reference to the WebGL 2 backend.
  44233. *
  44234. * @type {WebGLBackend}
  44235. */
  44236. this.backend = backend;
  44237. }
  44238. /**
  44239. * Creates the GPU buffer for the given buffer attribute.
  44240. *
  44241. * @param {BufferAttribute} attribute - The buffer attribute.
  44242. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44243. */
  44244. createAttribute( attribute, bufferType ) {
  44245. const backend = this.backend;
  44246. const { gl } = backend;
  44247. const array = attribute.array;
  44248. const usage = attribute.usage || gl.STATIC_DRAW;
  44249. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44250. const bufferData = backend.get( bufferAttribute );
  44251. let bufferGPU = bufferData.bufferGPU;
  44252. if ( bufferGPU === undefined ) {
  44253. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  44254. bufferData.bufferGPU = bufferGPU;
  44255. bufferData.bufferType = bufferType;
  44256. bufferData.version = bufferAttribute.version;
  44257. }
  44258. //attribute.onUploadCallback();
  44259. let type;
  44260. if ( array instanceof Float32Array ) {
  44261. type = gl.FLOAT;
  44262. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  44263. type = gl.HALF_FLOAT;
  44264. } else if ( array instanceof Uint16Array ) {
  44265. if ( attribute.isFloat16BufferAttribute ) {
  44266. type = gl.HALF_FLOAT;
  44267. } else {
  44268. type = gl.UNSIGNED_SHORT;
  44269. }
  44270. } else if ( array instanceof Int16Array ) {
  44271. type = gl.SHORT;
  44272. } else if ( array instanceof Uint32Array ) {
  44273. type = gl.UNSIGNED_INT;
  44274. } else if ( array instanceof Int32Array ) {
  44275. type = gl.INT;
  44276. } else if ( array instanceof Int8Array ) {
  44277. type = gl.BYTE;
  44278. } else if ( array instanceof Uint8Array ) {
  44279. type = gl.UNSIGNED_BYTE;
  44280. } else if ( array instanceof Uint8ClampedArray ) {
  44281. type = gl.UNSIGNED_BYTE;
  44282. } else {
  44283. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  44284. }
  44285. let attributeData = {
  44286. bufferGPU,
  44287. bufferType,
  44288. type,
  44289. byteLength: array.byteLength,
  44290. bytesPerElement: array.BYTES_PER_ELEMENT,
  44291. version: attribute.version,
  44292. pbo: attribute.pbo,
  44293. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  44294. id: _id$1 ++
  44295. };
  44296. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  44297. // create buffer for transform feedback use
  44298. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  44299. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  44300. }
  44301. backend.set( attribute, attributeData );
  44302. }
  44303. /**
  44304. * Updates the GPU buffer of the given buffer attribute.
  44305. *
  44306. * @param {BufferAttribute} attribute - The buffer attribute.
  44307. */
  44308. updateAttribute( attribute ) {
  44309. const backend = this.backend;
  44310. const { gl } = backend;
  44311. const array = attribute.array;
  44312. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44313. const bufferData = backend.get( bufferAttribute );
  44314. const bufferType = bufferData.bufferType;
  44315. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  44316. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  44317. if ( updateRanges.length === 0 ) {
  44318. // Not using update ranges
  44319. gl.bufferSubData( bufferType, 0, array );
  44320. } else {
  44321. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44322. const range = updateRanges[ i ];
  44323. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  44324. array, range.start, range.count );
  44325. }
  44326. bufferAttribute.clearUpdateRanges();
  44327. }
  44328. gl.bindBuffer( bufferType, null );
  44329. bufferData.version = bufferAttribute.version;
  44330. }
  44331. /**
  44332. * Destroys the GPU buffer of the given buffer attribute.
  44333. *
  44334. * @param {BufferAttribute} attribute - The buffer attribute.
  44335. */
  44336. destroyAttribute( attribute ) {
  44337. const backend = this.backend;
  44338. const { gl } = backend;
  44339. if ( attribute.isInterleavedBufferAttribute ) {
  44340. backend.delete( attribute.data );
  44341. }
  44342. const attributeData = backend.get( attribute );
  44343. gl.deleteBuffer( attributeData.bufferGPU );
  44344. backend.delete( attribute );
  44345. }
  44346. /**
  44347. * This method performs a readback operation by moving buffer data from
  44348. * a storage buffer attribute from the GPU to the CPU.
  44349. *
  44350. * @async
  44351. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44352. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44353. */
  44354. async getArrayBufferAsync( attribute ) {
  44355. const backend = this.backend;
  44356. const { gl } = backend;
  44357. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44358. const { bufferGPU } = backend.get( bufferAttribute );
  44359. const array = attribute.array;
  44360. const byteLength = array.byteLength;
  44361. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  44362. const writeBuffer = gl.createBuffer();
  44363. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44364. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  44365. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  44366. await backend.utils._clientWaitAsync();
  44367. const dstBuffer = new attribute.array.constructor( array.length );
  44368. // Ensure the buffer is bound before reading
  44369. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44370. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  44371. gl.deleteBuffer( writeBuffer );
  44372. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  44373. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  44374. return dstBuffer.buffer;
  44375. }
  44376. /**
  44377. * Creates a WebGL buffer with the given data.
  44378. *
  44379. * @private
  44380. * @param {WebGL2RenderingContext} gl - The rendering context.
  44381. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44382. * @param {TypedArray} array - The array of the buffer attribute.
  44383. * @param {GLenum} usage - The usage.
  44384. * @return {WebGLBuffer} The WebGL buffer.
  44385. */
  44386. _createBuffer( gl, bufferType, array, usage ) {
  44387. const bufferGPU = gl.createBuffer();
  44388. gl.bindBuffer( bufferType, bufferGPU );
  44389. gl.bufferData( bufferType, array, usage );
  44390. gl.bindBuffer( bufferType, null );
  44391. return bufferGPU;
  44392. }
  44393. }
  44394. let equationToGL, factorToGL;
  44395. /**
  44396. * A WebGL 2 backend utility module for managing the WebGL state.
  44397. *
  44398. * The major goal of this module is to reduce the number of state changes
  44399. * by caching the WEbGL state with a series of variables. In this way, the
  44400. * renderer only executes state change commands when necessary which
  44401. * improves the overall performance.
  44402. *
  44403. * @private
  44404. */
  44405. class WebGLState {
  44406. /**
  44407. * Constructs a new utility object.
  44408. *
  44409. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44410. */
  44411. constructor( backend ) {
  44412. /**
  44413. * A reference to the WebGL 2 backend.
  44414. *
  44415. * @type {WebGLBackend}
  44416. */
  44417. this.backend = backend;
  44418. /**
  44419. * A reference to the rendering context.
  44420. *
  44421. * @type {WebGL2RenderingContext}
  44422. */
  44423. this.gl = this.backend.gl;
  44424. // Below properties are intended to cache
  44425. // the WebGL state and are not explicitly
  44426. // documented for convenience reasons.
  44427. this.enabled = {};
  44428. this.currentFlipSided = null;
  44429. this.currentCullFace = null;
  44430. this.currentProgram = null;
  44431. this.currentBlendingEnabled = false;
  44432. this.currentBlending = null;
  44433. this.currentBlendSrc = null;
  44434. this.currentBlendDst = null;
  44435. this.currentBlendSrcAlpha = null;
  44436. this.currentBlendDstAlpha = null;
  44437. this.currentPremultipledAlpha = null;
  44438. this.currentPolygonOffsetFactor = null;
  44439. this.currentPolygonOffsetUnits = null;
  44440. this.currentColorMask = null;
  44441. this.currentDepthFunc = null;
  44442. this.currentDepthMask = null;
  44443. this.currentStencilFunc = null;
  44444. this.currentStencilRef = null;
  44445. this.currentStencilFuncMask = null;
  44446. this.currentStencilFail = null;
  44447. this.currentStencilZFail = null;
  44448. this.currentStencilZPass = null;
  44449. this.currentStencilMask = null;
  44450. this.currentLineWidth = null;
  44451. this.currentClippingPlanes = 0;
  44452. this.currentVAO = null;
  44453. this.currentIndex = null;
  44454. this.currentBoundFramebuffers = {};
  44455. this.currentDrawbuffers = new WeakMap();
  44456. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  44457. this.currentTextureSlot = null;
  44458. this.currentBoundTextures = {};
  44459. this.currentBoundBufferBases = {};
  44460. this._init();
  44461. }
  44462. /**
  44463. * Inits the state of the utility.
  44464. *
  44465. * @private
  44466. */
  44467. _init() {
  44468. const gl = this.gl;
  44469. // Store only WebGL constants here.
  44470. equationToGL = {
  44471. [ AddEquation ]: gl.FUNC_ADD,
  44472. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  44473. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  44474. };
  44475. factorToGL = {
  44476. [ ZeroFactor ]: gl.ZERO,
  44477. [ OneFactor ]: gl.ONE,
  44478. [ SrcColorFactor ]: gl.SRC_COLOR,
  44479. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  44480. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  44481. [ DstColorFactor ]: gl.DST_COLOR,
  44482. [ DstAlphaFactor ]: gl.DST_ALPHA,
  44483. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  44484. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  44485. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  44486. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  44487. };
  44488. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  44489. const viewportParam = gl.getParameter( gl.VIEWPORT );
  44490. this.currentScissor = new Vector4().fromArray( scissorParam );
  44491. this.currentViewport = new Vector4().fromArray( viewportParam );
  44492. this._tempVec4 = new Vector4();
  44493. }
  44494. /**
  44495. * Enables the given WebGL capability.
  44496. *
  44497. * This method caches the capability state so
  44498. * `gl.enable()` is only called when necessary.
  44499. *
  44500. * @param {GLenum} id - The capability to enable.
  44501. */
  44502. enable( id ) {
  44503. const { enabled } = this;
  44504. if ( enabled[ id ] !== true ) {
  44505. this.gl.enable( id );
  44506. enabled[ id ] = true;
  44507. }
  44508. }
  44509. /**
  44510. * Disables the given WebGL capability.
  44511. *
  44512. * This method caches the capability state so
  44513. * `gl.disable()` is only called when necessary.
  44514. *
  44515. * @param {GLenum} id - The capability to enable.
  44516. */
  44517. disable( id ) {
  44518. const { enabled } = this;
  44519. if ( enabled[ id ] !== false ) {
  44520. this.gl.disable( id );
  44521. enabled[ id ] = false;
  44522. }
  44523. }
  44524. /**
  44525. * Specifies whether polygons are front- or back-facing
  44526. * by setting the winding orientation.
  44527. *
  44528. * This method caches the state so `gl.frontFace()` is only
  44529. * called when necessary.
  44530. *
  44531. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  44532. */
  44533. setFlipSided( flipSided ) {
  44534. if ( this.currentFlipSided !== flipSided ) {
  44535. const { gl } = this;
  44536. if ( flipSided ) {
  44537. gl.frontFace( gl.CW );
  44538. } else {
  44539. gl.frontFace( gl.CCW );
  44540. }
  44541. this.currentFlipSided = flipSided;
  44542. }
  44543. }
  44544. /**
  44545. * Specifies whether or not front- and/or back-facing
  44546. * polygons can be culled.
  44547. *
  44548. * This method caches the state so `gl.cullFace()` is only
  44549. * called when necessary.
  44550. *
  44551. * @param {number} cullFace - Defines which polygons are candidates for culling.
  44552. */
  44553. setCullFace( cullFace ) {
  44554. const { gl } = this;
  44555. if ( cullFace !== CullFaceNone ) {
  44556. this.enable( gl.CULL_FACE );
  44557. if ( cullFace !== this.currentCullFace ) {
  44558. if ( cullFace === CullFaceBack ) {
  44559. gl.cullFace( gl.BACK );
  44560. } else if ( cullFace === CullFaceFront ) {
  44561. gl.cullFace( gl.FRONT );
  44562. } else {
  44563. gl.cullFace( gl.FRONT_AND_BACK );
  44564. }
  44565. }
  44566. } else {
  44567. this.disable( gl.CULL_FACE );
  44568. }
  44569. this.currentCullFace = cullFace;
  44570. }
  44571. /**
  44572. * Specifies the width of line primitives.
  44573. *
  44574. * This method caches the state so `gl.lineWidth()` is only
  44575. * called when necessary.
  44576. *
  44577. * @param {number} width - The line width.
  44578. */
  44579. setLineWidth( width ) {
  44580. const { currentLineWidth, gl } = this;
  44581. if ( width !== currentLineWidth ) {
  44582. gl.lineWidth( width );
  44583. this.currentLineWidth = width;
  44584. }
  44585. }
  44586. /**
  44587. * Defines the blending.
  44588. *
  44589. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  44590. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  44591. *
  44592. * @param {number} blending - The blending type.
  44593. * @param {number} blendEquation - The blending equation.
  44594. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  44595. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  44596. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  44597. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  44598. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  44599. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  44600. */
  44601. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  44602. const { gl } = this;
  44603. if ( blending === NoBlending ) {
  44604. if ( this.currentBlendingEnabled === true ) {
  44605. this.disable( gl.BLEND );
  44606. this.currentBlendingEnabled = false;
  44607. }
  44608. return;
  44609. }
  44610. if ( this.currentBlendingEnabled === false ) {
  44611. this.enable( gl.BLEND );
  44612. this.currentBlendingEnabled = true;
  44613. }
  44614. if ( blending !== CustomBlending ) {
  44615. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  44616. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  44617. gl.blendEquation( gl.FUNC_ADD );
  44618. this.currentBlendEquation = AddEquation;
  44619. this.currentBlendEquationAlpha = AddEquation;
  44620. }
  44621. if ( premultipliedAlpha ) {
  44622. switch ( blending ) {
  44623. case NormalBlending:
  44624. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44625. break;
  44626. case AdditiveBlending:
  44627. gl.blendFunc( gl.ONE, gl.ONE );
  44628. break;
  44629. case SubtractiveBlending:
  44630. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  44631. break;
  44632. case MultiplyBlending:
  44633. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  44634. break;
  44635. default:
  44636. error( 'WebGLState: Invalid blending: ', blending );
  44637. break;
  44638. }
  44639. } else {
  44640. switch ( blending ) {
  44641. case NormalBlending:
  44642. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44643. break;
  44644. case AdditiveBlending:
  44645. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  44646. break;
  44647. case SubtractiveBlending:
  44648. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  44649. break;
  44650. case MultiplyBlending:
  44651. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  44652. break;
  44653. default:
  44654. error( 'WebGLState: Invalid blending: ', blending );
  44655. break;
  44656. }
  44657. }
  44658. this.currentBlendSrc = null;
  44659. this.currentBlendDst = null;
  44660. this.currentBlendSrcAlpha = null;
  44661. this.currentBlendDstAlpha = null;
  44662. this.currentBlending = blending;
  44663. this.currentPremultipledAlpha = premultipliedAlpha;
  44664. }
  44665. return;
  44666. }
  44667. // custom blending
  44668. blendEquationAlpha = blendEquationAlpha || blendEquation;
  44669. blendSrcAlpha = blendSrcAlpha || blendSrc;
  44670. blendDstAlpha = blendDstAlpha || blendDst;
  44671. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  44672. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  44673. this.currentBlendEquation = blendEquation;
  44674. this.currentBlendEquationAlpha = blendEquationAlpha;
  44675. }
  44676. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  44677. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  44678. this.currentBlendSrc = blendSrc;
  44679. this.currentBlendDst = blendDst;
  44680. this.currentBlendSrcAlpha = blendSrcAlpha;
  44681. this.currentBlendDstAlpha = blendDstAlpha;
  44682. }
  44683. this.currentBlending = blending;
  44684. this.currentPremultipledAlpha = false;
  44685. }
  44686. /**
  44687. * Specifies whether colors can be written when rendering
  44688. * into a framebuffer or not.
  44689. *
  44690. * This method caches the state so `gl.colorMask()` is only
  44691. * called when necessary.
  44692. *
  44693. * @param {boolean} colorMask - The color mask.
  44694. */
  44695. setColorMask( colorMask ) {
  44696. if ( this.currentColorMask !== colorMask ) {
  44697. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  44698. this.currentColorMask = colorMask;
  44699. }
  44700. }
  44701. /**
  44702. * Specifies whether the depth test is enabled or not.
  44703. *
  44704. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  44705. */
  44706. setDepthTest( depthTest ) {
  44707. const { gl } = this;
  44708. if ( depthTest ) {
  44709. this.enable( gl.DEPTH_TEST );
  44710. } else {
  44711. this.disable( gl.DEPTH_TEST );
  44712. }
  44713. }
  44714. /**
  44715. * Specifies whether depth values can be written when rendering
  44716. * into a framebuffer or not.
  44717. *
  44718. * This method caches the state so `gl.depthMask()` is only
  44719. * called when necessary.
  44720. *
  44721. * @param {boolean} depthMask - The depth mask.
  44722. */
  44723. setDepthMask( depthMask ) {
  44724. if ( this.currentDepthMask !== depthMask ) {
  44725. this.gl.depthMask( depthMask );
  44726. this.currentDepthMask = depthMask;
  44727. }
  44728. }
  44729. /**
  44730. * Specifies the depth compare function.
  44731. *
  44732. * This method caches the state so `gl.depthFunc()` is only
  44733. * called when necessary.
  44734. *
  44735. * @param {number} depthFunc - The depth compare function.
  44736. */
  44737. setDepthFunc( depthFunc ) {
  44738. if ( this.currentDepthFunc !== depthFunc ) {
  44739. const { gl } = this;
  44740. switch ( depthFunc ) {
  44741. case NeverDepth:
  44742. gl.depthFunc( gl.NEVER );
  44743. break;
  44744. case AlwaysDepth:
  44745. gl.depthFunc( gl.ALWAYS );
  44746. break;
  44747. case LessDepth:
  44748. gl.depthFunc( gl.LESS );
  44749. break;
  44750. case LessEqualDepth:
  44751. gl.depthFunc( gl.LEQUAL );
  44752. break;
  44753. case EqualDepth:
  44754. gl.depthFunc( gl.EQUAL );
  44755. break;
  44756. case GreaterEqualDepth:
  44757. gl.depthFunc( gl.GEQUAL );
  44758. break;
  44759. case GreaterDepth:
  44760. gl.depthFunc( gl.GREATER );
  44761. break;
  44762. case NotEqualDepth:
  44763. gl.depthFunc( gl.NOTEQUAL );
  44764. break;
  44765. default:
  44766. gl.depthFunc( gl.LEQUAL );
  44767. }
  44768. this.currentDepthFunc = depthFunc;
  44769. }
  44770. }
  44771. /**
  44772. * Specifies the scissor box.
  44773. *
  44774. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44775. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44776. * @param {number} width - The width of the viewport.
  44777. * @param {number} height - The height of the viewport.
  44778. *
  44779. */
  44780. scissor( x, y, width, height ) {
  44781. const scissor = this._tempVec4.set( x, y, width, height );
  44782. if ( this.currentScissor.equals( scissor ) === false ) {
  44783. const { gl } = this;
  44784. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  44785. this.currentScissor.copy( scissor );
  44786. }
  44787. }
  44788. /**
  44789. * Specifies the viewport.
  44790. *
  44791. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44792. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44793. * @param {number} width - The width of the viewport.
  44794. * @param {number} height - The height of the viewport.
  44795. *
  44796. */
  44797. viewport( x, y, width, height ) {
  44798. const viewport = this._tempVec4.set( x, y, width, height );
  44799. if ( this.currentViewport.equals( viewport ) === false ) {
  44800. const { gl } = this;
  44801. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  44802. this.currentViewport.copy( viewport );
  44803. }
  44804. }
  44805. /**
  44806. * Defines the scissor test.
  44807. *
  44808. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44809. */
  44810. setScissorTest( boolean ) {
  44811. const gl = this.gl;
  44812. if ( boolean ) {
  44813. gl.enable( gl.SCISSOR_TEST );
  44814. } else {
  44815. gl.disable( gl.SCISSOR_TEST );
  44816. }
  44817. }
  44818. /**
  44819. * Specifies whether the stencil test is enabled or not.
  44820. *
  44821. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  44822. */
  44823. setStencilTest( stencilTest ) {
  44824. const { gl } = this;
  44825. if ( stencilTest ) {
  44826. this.enable( gl.STENCIL_TEST );
  44827. } else {
  44828. this.disable( gl.STENCIL_TEST );
  44829. }
  44830. }
  44831. /**
  44832. * Specifies whether stencil values can be written when rendering
  44833. * into a framebuffer or not.
  44834. *
  44835. * This method caches the state so `gl.stencilMask()` is only
  44836. * called when necessary.
  44837. *
  44838. * @param {boolean} stencilMask - The stencil mask.
  44839. */
  44840. setStencilMask( stencilMask ) {
  44841. if ( this.currentStencilMask !== stencilMask ) {
  44842. this.gl.stencilMask( stencilMask );
  44843. this.currentStencilMask = stencilMask;
  44844. }
  44845. }
  44846. /**
  44847. * Specifies whether the stencil test functions.
  44848. *
  44849. * This method caches the state so `gl.stencilFunc()` is only
  44850. * called when necessary.
  44851. *
  44852. * @param {number} stencilFunc - The stencil compare function.
  44853. * @param {number} stencilRef - The reference value for the stencil test.
  44854. * @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.
  44855. */
  44856. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  44857. if ( this.currentStencilFunc !== stencilFunc ||
  44858. this.currentStencilRef !== stencilRef ||
  44859. this.currentStencilFuncMask !== stencilMask ) {
  44860. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  44861. this.currentStencilFunc = stencilFunc;
  44862. this.currentStencilRef = stencilRef;
  44863. this.currentStencilFuncMask = stencilMask;
  44864. }
  44865. }
  44866. /**
  44867. * Specifies whether the stencil test operation.
  44868. *
  44869. * This method caches the state so `gl.stencilOp()` is only
  44870. * called when necessary.
  44871. *
  44872. * @param {number} stencilFail - The function to use when the stencil test fails.
  44873. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  44874. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  44875. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  44876. */
  44877. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  44878. if ( this.currentStencilFail !== stencilFail ||
  44879. this.currentStencilZFail !== stencilZFail ||
  44880. this.currentStencilZPass !== stencilZPass ) {
  44881. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  44882. this.currentStencilFail = stencilFail;
  44883. this.currentStencilZFail = stencilZFail;
  44884. this.currentStencilZPass = stencilZPass;
  44885. }
  44886. }
  44887. /**
  44888. * Configures the WebGL state for the given material.
  44889. *
  44890. * @param {Material} material - The material to configure the state for.
  44891. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  44892. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  44893. */
  44894. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  44895. const { gl } = this;
  44896. material.side === DoubleSide
  44897. ? this.disable( gl.CULL_FACE )
  44898. : this.enable( gl.CULL_FACE );
  44899. let flipSided = ( material.side === BackSide );
  44900. if ( frontFaceCW ) flipSided = ! flipSided;
  44901. this.setFlipSided( flipSided );
  44902. ( material.blending === NormalBlending && material.transparent === false )
  44903. ? this.setBlending( NoBlending )
  44904. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  44905. this.setDepthFunc( material.depthFunc );
  44906. this.setDepthTest( material.depthTest );
  44907. this.setDepthMask( material.depthWrite );
  44908. this.setColorMask( material.colorWrite );
  44909. const stencilWrite = material.stencilWrite;
  44910. this.setStencilTest( stencilWrite );
  44911. if ( stencilWrite ) {
  44912. this.setStencilMask( material.stencilWriteMask );
  44913. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  44914. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  44915. }
  44916. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  44917. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  44918. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  44919. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  44920. if ( hardwareClippingPlanes > 0 ) {
  44921. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  44922. const CLIP_DISTANCE0_WEBGL = 0x3000;
  44923. for ( let i = 0; i < 8; i ++ ) {
  44924. if ( i < hardwareClippingPlanes ) {
  44925. this.enable( CLIP_DISTANCE0_WEBGL + i );
  44926. } else {
  44927. this.disable( CLIP_DISTANCE0_WEBGL + i );
  44928. }
  44929. }
  44930. }
  44931. }
  44932. }
  44933. /**
  44934. * Specifies the polygon offset.
  44935. *
  44936. * This method caches the state so `gl.polygonOffset()` is only
  44937. * called when necessary.
  44938. *
  44939. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  44940. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  44941. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  44942. */
  44943. setPolygonOffset( polygonOffset, factor, units ) {
  44944. const { gl } = this;
  44945. if ( polygonOffset ) {
  44946. this.enable( gl.POLYGON_OFFSET_FILL );
  44947. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  44948. gl.polygonOffset( factor, units );
  44949. this.currentPolygonOffsetFactor = factor;
  44950. this.currentPolygonOffsetUnits = units;
  44951. }
  44952. } else {
  44953. this.disable( gl.POLYGON_OFFSET_FILL );
  44954. }
  44955. }
  44956. /**
  44957. * Defines the usage of the given WebGL program.
  44958. *
  44959. * This method caches the state so `gl.useProgram()` is only
  44960. * called when necessary.
  44961. *
  44962. * @param {WebGLProgram} program - The WebGL program to use.
  44963. * @return {boolean} Whether a program change has been executed or not.
  44964. */
  44965. useProgram( program ) {
  44966. if ( this.currentProgram !== program ) {
  44967. this.gl.useProgram( program );
  44968. this.currentProgram = program;
  44969. return true;
  44970. }
  44971. return false;
  44972. }
  44973. /**
  44974. * Sets the vertex state by binding the given VAO and element buffer.
  44975. *
  44976. * @param {WebGLVertexArrayObject} vao - The VAO.
  44977. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  44978. * @return {boolean} Whether a vertex state has been changed or not.
  44979. */
  44980. setVertexState( vao, indexBuffer = null ) {
  44981. const gl = this.gl;
  44982. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  44983. gl.bindVertexArray( vao );
  44984. if ( indexBuffer !== null ) {
  44985. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  44986. }
  44987. this.currentVAO = vao;
  44988. this.currentIndex = indexBuffer;
  44989. return true;
  44990. }
  44991. return false;
  44992. }
  44993. /**
  44994. * Resets the vertex array state by resetting the VAO and element buffer.
  44995. */
  44996. resetVertexState() {
  44997. const gl = this.gl;
  44998. gl.bindVertexArray( null );
  44999. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  45000. this.currentVAO = null;
  45001. this.currentIndex = null;
  45002. }
  45003. // framebuffer
  45004. /**
  45005. * Binds the given framebuffer.
  45006. *
  45007. * This method caches the state so `gl.bindFramebuffer()` is only
  45008. * called when necessary.
  45009. *
  45010. * @param {number} target - The binding point (target).
  45011. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  45012. * @return {boolean} Whether a bind has been executed or not.
  45013. */
  45014. bindFramebuffer( target, framebuffer ) {
  45015. const { gl, currentBoundFramebuffers } = this;
  45016. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  45017. gl.bindFramebuffer( target, framebuffer );
  45018. currentBoundFramebuffers[ target ] = framebuffer;
  45019. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  45020. if ( target === gl.DRAW_FRAMEBUFFER ) {
  45021. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  45022. }
  45023. if ( target === gl.FRAMEBUFFER ) {
  45024. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  45025. }
  45026. return true;
  45027. }
  45028. return false;
  45029. }
  45030. /**
  45031. * Defines draw buffers to which fragment colors are written into.
  45032. * Configures the MRT setup of custom framebuffers.
  45033. *
  45034. * This method caches the state so `gl.drawBuffers()` is only
  45035. * called when necessary.
  45036. *
  45037. * @param {RenderContext} renderContext - The render context.
  45038. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  45039. */
  45040. drawBuffers( renderContext, framebuffer ) {
  45041. const { gl } = this;
  45042. let drawBuffers = [];
  45043. let needsUpdate = false;
  45044. if ( renderContext.textures !== null ) {
  45045. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  45046. if ( drawBuffers === undefined ) {
  45047. drawBuffers = [];
  45048. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  45049. }
  45050. const textures = renderContext.textures;
  45051. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  45052. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  45053. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  45054. }
  45055. drawBuffers.length = textures.length;
  45056. needsUpdate = true;
  45057. }
  45058. } else {
  45059. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  45060. drawBuffers[ 0 ] = gl.BACK;
  45061. needsUpdate = true;
  45062. }
  45063. }
  45064. if ( needsUpdate ) {
  45065. gl.drawBuffers( drawBuffers );
  45066. }
  45067. }
  45068. // texture
  45069. /**
  45070. * Makes the given texture unit active.
  45071. *
  45072. * This method caches the state so `gl.activeTexture()` is only
  45073. * called when necessary.
  45074. *
  45075. * @param {number} webglSlot - The texture unit to make active.
  45076. */
  45077. activeTexture( webglSlot ) {
  45078. const { gl, currentTextureSlot, maxTextures } = this;
  45079. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45080. if ( currentTextureSlot !== webglSlot ) {
  45081. gl.activeTexture( webglSlot );
  45082. this.currentTextureSlot = webglSlot;
  45083. }
  45084. }
  45085. /**
  45086. * Binds the given WebGL texture to a target.
  45087. *
  45088. * This method caches the state so `gl.bindTexture()` is only
  45089. * called when necessary.
  45090. *
  45091. * @param {number} webglType - The binding point (target).
  45092. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  45093. * @param {number} webglSlot - The texture.
  45094. */
  45095. bindTexture( webglType, webglTexture, webglSlot ) {
  45096. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  45097. if ( webglSlot === undefined ) {
  45098. if ( currentTextureSlot === null ) {
  45099. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45100. } else {
  45101. webglSlot = currentTextureSlot;
  45102. }
  45103. }
  45104. let boundTexture = currentBoundTextures[ webglSlot ];
  45105. if ( boundTexture === undefined ) {
  45106. boundTexture = { type: undefined, texture: undefined };
  45107. currentBoundTextures[ webglSlot ] = boundTexture;
  45108. }
  45109. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  45110. if ( currentTextureSlot !== webglSlot ) {
  45111. gl.activeTexture( webglSlot );
  45112. this.currentTextureSlot = webglSlot;
  45113. }
  45114. gl.bindTexture( webglType, webglTexture );
  45115. boundTexture.type = webglType;
  45116. boundTexture.texture = webglTexture;
  45117. }
  45118. }
  45119. /**
  45120. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  45121. *
  45122. * This method caches the state so `gl.bindBufferBase()` is only
  45123. * called when necessary.
  45124. *
  45125. * @param {number} target - The target for the bind operation.
  45126. * @param {number} index - The index of the target.
  45127. * @param {WebGLBuffer} buffer - The WebGL buffer.
  45128. * @return {boolean} Whether a bind has been executed or not.
  45129. */
  45130. bindBufferBase( target, index, buffer ) {
  45131. const { gl } = this;
  45132. const key = `${target}-${index}`;
  45133. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  45134. gl.bindBufferBase( target, index, buffer );
  45135. this.currentBoundBufferBases[ key ] = buffer;
  45136. return true;
  45137. }
  45138. return false;
  45139. }
  45140. /**
  45141. * Unbinds the current bound texture.
  45142. *
  45143. * This method caches the state so `gl.bindTexture()` is only
  45144. * called when necessary.
  45145. */
  45146. unbindTexture() {
  45147. const { gl, currentTextureSlot, currentBoundTextures } = this;
  45148. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  45149. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  45150. gl.bindTexture( boundTexture.type, null );
  45151. boundTexture.type = undefined;
  45152. boundTexture.texture = undefined;
  45153. }
  45154. }
  45155. }
  45156. /**
  45157. * A WebGL 2 backend utility module with common helpers.
  45158. *
  45159. * @private
  45160. */
  45161. class WebGLUtils {
  45162. /**
  45163. * Constructs a new utility object.
  45164. *
  45165. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45166. */
  45167. constructor( backend ) {
  45168. /**
  45169. * A reference to the WebGL 2 backend.
  45170. *
  45171. * @type {WebGLBackend}
  45172. */
  45173. this.backend = backend;
  45174. /**
  45175. * A reference to the rendering context.
  45176. *
  45177. * @type {WebGL2RenderingContext}
  45178. */
  45179. this.gl = this.backend.gl;
  45180. /**
  45181. * A reference to a backend module holding extension-related
  45182. * utility functions.
  45183. *
  45184. * @type {WebGLExtensions}
  45185. */
  45186. this.extensions = backend.extensions;
  45187. }
  45188. /**
  45189. * Converts the given three.js constant into a WebGL constant.
  45190. * The method currently supports the conversion of texture formats
  45191. * and types.
  45192. *
  45193. * @param {number} p - The three.js constant.
  45194. * @param {string} [colorSpace=NoColorSpace] - The color space.
  45195. * @return {?number} The corresponding WebGL constant.
  45196. */
  45197. convert( p, colorSpace = NoColorSpace ) {
  45198. const { gl, extensions } = this;
  45199. let extension;
  45200. const transfer = ColorManagement.getTransfer( colorSpace );
  45201. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  45202. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  45203. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  45204. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  45205. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  45206. if ( p === ByteType ) return gl.BYTE;
  45207. if ( p === ShortType ) return gl.SHORT;
  45208. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  45209. if ( p === IntType ) return gl.INT;
  45210. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  45211. if ( p === FloatType ) return gl.FLOAT;
  45212. if ( p === HalfFloatType ) {
  45213. return gl.HALF_FLOAT;
  45214. }
  45215. if ( p === AlphaFormat ) return gl.ALPHA;
  45216. if ( p === RGBFormat ) return gl.RGB;
  45217. if ( p === RGBAFormat ) return gl.RGBA;
  45218. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  45219. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  45220. // WebGL2 formats.
  45221. if ( p === RedFormat ) return gl.RED;
  45222. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  45223. if ( p === RGFormat ) return gl.RG;
  45224. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  45225. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  45226. // S3TC
  45227. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  45228. if ( transfer === SRGBTransfer ) {
  45229. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  45230. if ( extension !== null ) {
  45231. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  45232. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  45233. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  45234. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  45235. } else {
  45236. return null;
  45237. }
  45238. } else {
  45239. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  45240. if ( extension !== null ) {
  45241. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45242. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45243. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45244. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45245. } else {
  45246. return null;
  45247. }
  45248. }
  45249. }
  45250. // PVRTC
  45251. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  45252. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  45253. if ( extension !== null ) {
  45254. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45255. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45256. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45257. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45258. } else {
  45259. return null;
  45260. }
  45261. }
  45262. // ETC
  45263. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  45264. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  45265. if ( extension !== null ) {
  45266. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  45267. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  45268. } else {
  45269. return null;
  45270. }
  45271. }
  45272. // ASTC
  45273. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  45274. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  45275. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  45276. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  45277. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  45278. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  45279. if ( extension !== null ) {
  45280. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  45281. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  45282. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  45283. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  45284. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  45285. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  45286. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  45287. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  45288. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  45289. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  45290. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  45291. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  45292. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  45293. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  45294. } else {
  45295. return null;
  45296. }
  45297. }
  45298. // BPTC
  45299. if ( p === RGBA_BPTC_Format ) {
  45300. extension = extensions.get( 'EXT_texture_compression_bptc' );
  45301. if ( extension !== null ) {
  45302. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  45303. } else {
  45304. return null;
  45305. }
  45306. }
  45307. // RGTC
  45308. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  45309. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  45310. if ( extension !== null ) {
  45311. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  45312. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  45313. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  45314. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  45315. } else {
  45316. return null;
  45317. }
  45318. }
  45319. //
  45320. if ( p === UnsignedInt248Type ) {
  45321. return gl.UNSIGNED_INT_24_8;
  45322. }
  45323. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  45324. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  45325. }
  45326. /**
  45327. * This method can be used to synchronize the CPU with the GPU by waiting until
  45328. * ongoing GPU commands have been completed.
  45329. *
  45330. * @private
  45331. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  45332. */
  45333. _clientWaitAsync() {
  45334. const { gl } = this;
  45335. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  45336. gl.flush();
  45337. return new Promise( ( resolve, reject ) => {
  45338. function test() {
  45339. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  45340. if ( res === gl.WAIT_FAILED ) {
  45341. gl.deleteSync( sync );
  45342. reject();
  45343. return;
  45344. }
  45345. if ( res === gl.TIMEOUT_EXPIRED ) {
  45346. requestAnimationFrame( test );
  45347. return;
  45348. }
  45349. gl.deleteSync( sync );
  45350. resolve();
  45351. }
  45352. test();
  45353. } );
  45354. }
  45355. }
  45356. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  45357. /**
  45358. * A WebGL 2 backend utility module for managing textures.
  45359. *
  45360. * @private
  45361. */
  45362. class WebGLTextureUtils {
  45363. /**
  45364. * Constructs a new utility object.
  45365. *
  45366. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45367. */
  45368. constructor( backend ) {
  45369. /**
  45370. * A reference to the WebGL 2 backend.
  45371. *
  45372. * @type {WebGLBackend}
  45373. */
  45374. this.backend = backend;
  45375. /**
  45376. * A reference to the rendering context.
  45377. *
  45378. * @type {WebGL2RenderingContext}
  45379. */
  45380. this.gl = backend.gl;
  45381. /**
  45382. * A reference to a backend module holding extension-related
  45383. * utility functions.
  45384. *
  45385. * @type {WebGLExtensions}
  45386. */
  45387. this.extensions = backend.extensions;
  45388. /**
  45389. * A dictionary for managing default textures. The key
  45390. * is the binding point (target), the value the WEbGL texture object.
  45391. *
  45392. * @type {Object<GLenum,WebGLTexture>}
  45393. */
  45394. this.defaultTextures = {};
  45395. /**
  45396. * A scratch framebuffer used for attaching the source texture in
  45397. * {@link copyTextureToTexture}.
  45398. *
  45399. * @private
  45400. * @type {?WebGLFramebuffer}
  45401. */
  45402. this._srcFramebuffer = null;
  45403. /**
  45404. * A scratch framebuffer used for attaching the destination texture in
  45405. * {@link copyTextureToTexture}.
  45406. *
  45407. * @private
  45408. * @type {?WebGLFramebuffer}
  45409. */
  45410. this._dstFramebuffer = null;
  45411. if ( initialized === false ) {
  45412. this._init();
  45413. initialized = true;
  45414. }
  45415. }
  45416. /**
  45417. * Inits the state of the utility.
  45418. *
  45419. * @private
  45420. */
  45421. _init() {
  45422. const gl = this.gl;
  45423. // Store only WebGL constants here.
  45424. wrappingToGL = {
  45425. [ RepeatWrapping ]: gl.REPEAT,
  45426. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  45427. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  45428. };
  45429. filterToGL = {
  45430. [ NearestFilter ]: gl.NEAREST,
  45431. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  45432. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  45433. [ LinearFilter ]: gl.LINEAR,
  45434. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  45435. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  45436. };
  45437. compareToGL = {
  45438. [ NeverCompare ]: gl.NEVER,
  45439. [ AlwaysCompare ]: gl.ALWAYS,
  45440. [ LessCompare ]: gl.LESS,
  45441. [ LessEqualCompare ]: gl.LEQUAL,
  45442. [ EqualCompare ]: gl.EQUAL,
  45443. [ GreaterEqualCompare ]: gl.GEQUAL,
  45444. [ GreaterCompare ]: gl.GREATER,
  45445. [ NotEqualCompare ]: gl.NOTEQUAL
  45446. };
  45447. }
  45448. /**
  45449. * Returns the native texture type for the given texture.
  45450. *
  45451. * @param {Texture} texture - The texture.
  45452. * @return {GLenum} The native texture type.
  45453. */
  45454. getGLTextureType( texture ) {
  45455. const { gl } = this;
  45456. let glTextureType;
  45457. if ( texture.isCubeTexture === true ) {
  45458. glTextureType = gl.TEXTURE_CUBE_MAP;
  45459. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45460. glTextureType = gl.TEXTURE_2D_ARRAY;
  45461. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  45462. glTextureType = gl.TEXTURE_3D;
  45463. } else {
  45464. glTextureType = gl.TEXTURE_2D;
  45465. }
  45466. return glTextureType;
  45467. }
  45468. /**
  45469. * Returns the native texture type for the given texture.
  45470. *
  45471. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  45472. * @param {GLenum} glFormat - The WebGL format.
  45473. * @param {GLenum} glType - The WebGL type.
  45474. * @param {string} colorSpace - The texture's color space.
  45475. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  45476. * @return {GLenum} The internal format.
  45477. */
  45478. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  45479. const { gl, extensions } = this;
  45480. if ( internalFormatName !== null ) {
  45481. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  45482. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  45483. }
  45484. let internalFormat = glFormat;
  45485. if ( glFormat === gl.RED ) {
  45486. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  45487. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  45488. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  45489. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  45490. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45491. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45492. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45493. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45494. }
  45495. if ( glFormat === gl.RED_INTEGER ) {
  45496. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  45497. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  45498. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45499. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45500. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45501. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45502. }
  45503. if ( glFormat === gl.RG ) {
  45504. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  45505. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  45506. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  45507. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  45508. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45509. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45510. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45511. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45512. }
  45513. if ( glFormat === gl.RG_INTEGER ) {
  45514. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  45515. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  45516. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45517. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45518. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45519. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45520. }
  45521. if ( glFormat === gl.RGB ) {
  45522. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45523. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  45524. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  45525. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  45526. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  45527. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45528. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45529. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45530. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45531. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  45532. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  45533. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45534. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  45535. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  45536. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  45537. }
  45538. if ( glFormat === gl.RGB_INTEGER ) {
  45539. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  45540. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  45541. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45542. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45543. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45544. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45545. }
  45546. if ( glFormat === gl.RGBA ) {
  45547. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45548. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  45549. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  45550. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  45551. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  45552. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45553. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45554. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45555. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45556. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  45557. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  45558. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45559. }
  45560. if ( glFormat === gl.RGBA_INTEGER ) {
  45561. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  45562. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  45563. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45564. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45565. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45566. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45567. }
  45568. if ( glFormat === gl.DEPTH_COMPONENT ) {
  45569. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  45570. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  45571. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  45572. }
  45573. if ( glFormat === gl.DEPTH_STENCIL ) {
  45574. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  45575. }
  45576. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  45577. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  45578. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  45579. extensions.get( 'EXT_color_buffer_float' );
  45580. }
  45581. return internalFormat;
  45582. }
  45583. /**
  45584. * Sets the texture parameters for the given texture.
  45585. *
  45586. * @param {GLenum} textureType - The texture type.
  45587. * @param {Texture} texture - The texture.
  45588. */
  45589. setTextureParameters( textureType, texture ) {
  45590. const { gl, extensions, backend } = this;
  45591. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  45592. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  45593. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  45594. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  45595. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  45596. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  45597. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  45598. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  45599. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  45600. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  45601. // WebGL 2 does not support wrapping for depth 2D array textures
  45602. if ( ! texture.isArrayTexture ) {
  45603. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  45604. }
  45605. }
  45606. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  45607. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  45608. // follow WebGPU backend mapping for texture filtering
  45609. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  45610. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  45611. if ( texture.compareFunction ) {
  45612. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  45613. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  45614. }
  45615. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45616. if ( texture.magFilter === NearestFilter ) return;
  45617. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  45618. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  45619. if ( texture.anisotropy > 1 ) {
  45620. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45621. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  45622. }
  45623. }
  45624. }
  45625. /**
  45626. * Creates a default texture for the given texture that can be used
  45627. * as a placeholder until the actual texture is ready for usage.
  45628. *
  45629. * @param {Texture} texture - The texture to create a default texture for.
  45630. */
  45631. createDefaultTexture( texture ) {
  45632. const { gl, backend, defaultTextures } = this;
  45633. const glTextureType = this.getGLTextureType( texture );
  45634. let textureGPU = defaultTextures[ glTextureType ];
  45635. if ( textureGPU === undefined ) {
  45636. textureGPU = gl.createTexture();
  45637. backend.state.bindTexture( glTextureType, textureGPU );
  45638. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  45639. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  45640. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  45641. defaultTextures[ glTextureType ] = textureGPU;
  45642. }
  45643. backend.set( texture, {
  45644. textureGPU,
  45645. glTextureType
  45646. } );
  45647. }
  45648. /**
  45649. * Defines a texture on the GPU for the given texture object.
  45650. *
  45651. * @param {Texture} texture - The texture.
  45652. * @param {Object} [options={}] - Optional configuration parameter.
  45653. * @return {undefined}
  45654. */
  45655. createTexture( texture, options ) {
  45656. const { gl, backend } = this;
  45657. const { levels, width, height, depth } = options;
  45658. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  45659. const glType = backend.utils.convert( texture.type );
  45660. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  45661. const textureGPU = gl.createTexture();
  45662. const glTextureType = this.getGLTextureType( texture );
  45663. backend.state.bindTexture( glTextureType, textureGPU );
  45664. this.setTextureParameters( glTextureType, texture );
  45665. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  45666. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  45667. } else if ( texture.isData3DTexture ) {
  45668. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  45669. } else if ( ! texture.isVideoTexture ) {
  45670. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  45671. }
  45672. backend.set( texture, {
  45673. textureGPU,
  45674. glTextureType,
  45675. glFormat,
  45676. glType,
  45677. glInternalFormat
  45678. } );
  45679. }
  45680. /**
  45681. * Uploads texture buffer data to the GPU memory.
  45682. *
  45683. * @param {WebGLBuffer} buffer - The buffer data.
  45684. * @param {Texture} texture - The texture,
  45685. */
  45686. copyBufferToTexture( buffer, texture ) {
  45687. const { gl, backend } = this;
  45688. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  45689. const { width, height } = texture.source.data;
  45690. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  45691. backend.state.bindTexture( glTextureType, textureGPU );
  45692. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  45693. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  45694. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  45695. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  45696. backend.state.unbindTexture();
  45697. // debug
  45698. // const framebuffer = gl.createFramebuffer();
  45699. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  45700. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  45701. // const readout = new Float32Array( width * height * 4 );
  45702. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  45703. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  45704. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  45705. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  45706. // log( readout );
  45707. }
  45708. /**
  45709. * Uploads the updated texture data to the GPU.
  45710. *
  45711. * @param {Texture} texture - The texture.
  45712. * @param {Object} [options={}] - Optional configuration parameter.
  45713. */
  45714. updateTexture( texture, options ) {
  45715. const { gl } = this;
  45716. const { width, height } = options;
  45717. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  45718. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  45719. return;
  45720. this.backend.state.bindTexture( glTextureType, textureGPU );
  45721. this.setTextureParameters( glTextureType, texture );
  45722. if ( texture.isCompressedTexture ) {
  45723. const mipmaps = texture.mipmaps;
  45724. const image = options.image;
  45725. for ( let i = 0; i < mipmaps.length; i ++ ) {
  45726. const mipmap = mipmaps[ i ];
  45727. if ( texture.isCompressedArrayTexture ) {
  45728. if ( texture.format !== gl.RGBA ) {
  45729. if ( glFormat !== null ) {
  45730. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  45731. } else {
  45732. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  45733. }
  45734. } else {
  45735. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  45736. }
  45737. } else {
  45738. if ( glFormat !== null ) {
  45739. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  45740. } else {
  45741. warn( 'WebGLBackend: Unsupported compressed texture format' );
  45742. }
  45743. }
  45744. }
  45745. } else if ( texture.isCubeTexture ) {
  45746. const images = options.images;
  45747. const mipmaps = texture.mipmaps;
  45748. for ( let i = 0; i < 6; i ++ ) {
  45749. const image = getImage( images[ i ] );
  45750. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  45751. for ( let j = 0; j < mipmaps.length; j ++ ) {
  45752. const mipmap = mipmaps[ j ];
  45753. const image = getImage( mipmap.images[ i ] );
  45754. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  45755. }
  45756. }
  45757. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  45758. const image = options.image;
  45759. if ( texture.layerUpdates.size > 0 ) {
  45760. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  45761. for ( const layerIndex of texture.layerUpdates ) {
  45762. const layerData = image.data.subarray(
  45763. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  45764. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  45765. );
  45766. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  45767. }
  45768. texture.clearLayerUpdates();
  45769. } else {
  45770. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45771. }
  45772. } else if ( texture.isData3DTexture ) {
  45773. const image = options.image;
  45774. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45775. } else if ( texture.isVideoTexture ) {
  45776. texture.update();
  45777. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  45778. } else {
  45779. const mipmaps = texture.mipmaps;
  45780. if ( mipmaps.length > 0 ) {
  45781. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  45782. const mipmap = mipmaps[ i ];
  45783. const image = getImage( mipmap );
  45784. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  45785. }
  45786. } else {
  45787. const image = getImage( options.image );
  45788. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  45789. }
  45790. }
  45791. }
  45792. /**
  45793. * Generates mipmaps for the given texture.
  45794. *
  45795. * @param {Texture} texture - The texture.
  45796. */
  45797. generateMipmaps( texture ) {
  45798. const { gl, backend } = this;
  45799. const { textureGPU, glTextureType } = backend.get( texture );
  45800. backend.state.bindTexture( glTextureType, textureGPU );
  45801. gl.generateMipmap( glTextureType );
  45802. }
  45803. /**
  45804. * Deallocates the render buffers of the given render target.
  45805. *
  45806. * @param {RenderTarget} renderTarget - The render target.
  45807. */
  45808. deallocateRenderBuffers( renderTarget ) {
  45809. const { gl, backend } = this;
  45810. // remove framebuffer reference
  45811. if ( renderTarget ) {
  45812. const renderContextData = backend.get( renderTarget );
  45813. renderContextData.renderBufferStorageSetup = undefined;
  45814. if ( renderContextData.framebuffers ) {
  45815. for ( const cacheKey in renderContextData.framebuffers ) {
  45816. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  45817. }
  45818. delete renderContextData.framebuffers;
  45819. }
  45820. if ( renderContextData.depthRenderbuffer ) {
  45821. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  45822. delete renderContextData.depthRenderbuffer;
  45823. }
  45824. if ( renderContextData.stencilRenderbuffer ) {
  45825. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  45826. delete renderContextData.stencilRenderbuffer;
  45827. }
  45828. if ( renderContextData.msaaFrameBuffer ) {
  45829. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  45830. delete renderContextData.msaaFrameBuffer;
  45831. }
  45832. if ( renderContextData.msaaRenderbuffers ) {
  45833. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  45834. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  45835. }
  45836. delete renderContextData.msaaRenderbuffers;
  45837. }
  45838. }
  45839. }
  45840. /**
  45841. * Destroys the GPU data for the given texture object.
  45842. *
  45843. * @param {Texture} texture - The texture.
  45844. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45845. */
  45846. destroyTexture( texture, isDefaultTexture = false ) {
  45847. const { gl, backend } = this;
  45848. const { textureGPU, renderTarget } = backend.get( texture );
  45849. this.deallocateRenderBuffers( renderTarget );
  45850. if ( isDefaultTexture === false ) {
  45851. gl.deleteTexture( textureGPU );
  45852. }
  45853. backend.delete( texture );
  45854. }
  45855. /**
  45856. * Copies data of the given source texture to the given destination texture.
  45857. *
  45858. * @param {Texture} srcTexture - The source texture.
  45859. * @param {Texture} dstTexture - The destination texture.
  45860. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45861. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45862. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45863. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45864. */
  45865. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45866. const { gl, backend } = this;
  45867. const { state } = this.backend;
  45868. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  45869. state.bindTexture( glTextureType, dstTextureGPU );
  45870. // gather the necessary dimensions to copy
  45871. let width, height, depth, minX, minY, minZ;
  45872. let dstX, dstY, dstZ;
  45873. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  45874. if ( srcRegion !== null ) {
  45875. width = srcRegion.max.x - srcRegion.min.x;
  45876. height = srcRegion.max.y - srcRegion.min.y;
  45877. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  45878. minX = srcRegion.min.x;
  45879. minY = srcRegion.min.y;
  45880. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  45881. } else {
  45882. const levelScale = Math.pow( 2, - srcLevel );
  45883. width = Math.floor( image.width * levelScale );
  45884. height = Math.floor( image.height * levelScale );
  45885. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  45886. depth = image.depth;
  45887. } else if ( srcTexture.isData3DTexture ) {
  45888. depth = Math.floor( image.depth * levelScale );
  45889. } else {
  45890. depth = 1;
  45891. }
  45892. minX = 0;
  45893. minY = 0;
  45894. minZ = 0;
  45895. }
  45896. if ( dstPosition !== null ) {
  45897. dstX = dstPosition.x;
  45898. dstY = dstPosition.y;
  45899. dstZ = dstPosition.z;
  45900. } else {
  45901. dstX = 0;
  45902. dstY = 0;
  45903. dstZ = 0;
  45904. }
  45905. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  45906. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  45907. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  45908. // used for copying data from cpu
  45909. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  45910. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  45911. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  45912. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  45913. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  45914. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  45915. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  45916. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  45917. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  45918. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  45919. // set up the src texture
  45920. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  45921. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  45922. if ( srcTexture.isDepthTexture ) {
  45923. const srcTextureData = backend.get( srcTexture );
  45924. const dstTextureData = backend.get( dstTexture );
  45925. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  45926. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  45927. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  45928. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  45929. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  45930. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  45931. for ( let i = 0; i < depth; i ++ ) {
  45932. // if the source or destination are a 3d target then a layer needs to be bound
  45933. if ( isSrc3D ) {
  45934. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45935. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45936. }
  45937. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  45938. }
  45939. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45940. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45941. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  45942. // get the appropriate frame buffers
  45943. const srcTextureData = backend.get( srcTexture );
  45944. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  45945. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  45946. // bind the frame buffer targets
  45947. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  45948. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  45949. for ( let i = 0; i < depth; i ++ ) {
  45950. // assign the correct layers and mip maps to the frame buffers
  45951. if ( isSrc3D ) {
  45952. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45953. } else {
  45954. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  45955. }
  45956. if ( isDst3D ) {
  45957. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45958. } else {
  45959. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  45960. }
  45961. // copy the data using the fastest function that can achieve the copy
  45962. if ( srcLevel !== 0 ) {
  45963. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  45964. } else if ( isDst3D ) {
  45965. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  45966. } else {
  45967. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  45968. }
  45969. }
  45970. // unbind read, draw buffers
  45971. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45972. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45973. } else {
  45974. if ( isDst3D ) {
  45975. // copy data into the 3d texture
  45976. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  45977. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  45978. } else if ( dstTexture.isCompressedArrayTexture ) {
  45979. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  45980. } else {
  45981. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  45982. }
  45983. } else {
  45984. // copy data into the 2d texture
  45985. if ( srcTexture.isDataTexture ) {
  45986. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  45987. } else if ( srcTexture.isCompressedTexture ) {
  45988. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  45989. } else {
  45990. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  45991. }
  45992. }
  45993. }
  45994. // reset values
  45995. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  45996. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  45997. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  45998. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  45999. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  46000. // Generate mipmaps only when copying level 0
  46001. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  46002. gl.generateMipmap( glTextureType );
  46003. }
  46004. state.unbindTexture();
  46005. }
  46006. /**
  46007. * Copies the current bound framebuffer to the given texture.
  46008. *
  46009. * @param {Texture} texture - The destination texture.
  46010. * @param {RenderContext} renderContext - The render context.
  46011. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46012. */
  46013. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46014. const { gl } = this;
  46015. const { state } = this.backend;
  46016. const { textureGPU } = this.backend.get( texture );
  46017. const { x, y, z: width, w: height } = rectangle;
  46018. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  46019. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  46020. if ( requireDrawFrameBuffer ) {
  46021. const partial = ( x !== 0 || y !== 0 );
  46022. let mask;
  46023. let attachment;
  46024. if ( texture.isDepthTexture === true ) {
  46025. mask = gl.DEPTH_BUFFER_BIT;
  46026. attachment = gl.DEPTH_ATTACHMENT;
  46027. if ( renderContext.stencil ) {
  46028. mask |= gl.STENCIL_BUFFER_BIT;
  46029. }
  46030. } else {
  46031. mask = gl.COLOR_BUFFER_BIT;
  46032. attachment = gl.COLOR_ATTACHMENT0;
  46033. }
  46034. if ( partial ) {
  46035. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  46036. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  46037. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46038. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46039. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  46040. const flippedY = srcHeight - y - height;
  46041. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  46042. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46043. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46044. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  46045. state.unbindTexture();
  46046. } else {
  46047. const fb = gl.createFramebuffer();
  46048. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46049. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  46050. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  46051. gl.deleteFramebuffer( fb );
  46052. }
  46053. } else {
  46054. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46055. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  46056. state.unbindTexture();
  46057. }
  46058. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  46059. this.backend._setFramebuffer( renderContext );
  46060. }
  46061. /**
  46062. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  46063. *
  46064. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  46065. * @param {RenderContext} renderContext - The render context.
  46066. * @param {number} samples - The MSAA sample count.
  46067. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  46068. */
  46069. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  46070. const { gl } = this;
  46071. const renderTarget = renderContext.renderTarget;
  46072. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  46073. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46074. if ( depthBuffer && ! stencilBuffer ) {
  46075. let glInternalFormat = gl.DEPTH_COMPONENT24;
  46076. if ( useMultisampledRTT === true ) {
  46077. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46078. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  46079. } else if ( samples > 0 ) {
  46080. if ( depthTexture && depthTexture.isDepthTexture ) {
  46081. if ( depthTexture.type === gl.FLOAT ) {
  46082. glInternalFormat = gl.DEPTH_COMPONENT32F;
  46083. }
  46084. }
  46085. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  46086. } else {
  46087. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  46088. }
  46089. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46090. } else if ( depthBuffer && stencilBuffer ) {
  46091. if ( samples > 0 ) {
  46092. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  46093. } else {
  46094. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  46095. }
  46096. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46097. }
  46098. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46099. }
  46100. /**
  46101. * Returns texture data as a typed array.
  46102. *
  46103. * @async
  46104. * @param {Texture} texture - The texture to copy.
  46105. * @param {number} x - The x coordinate of the copy origin.
  46106. * @param {number} y - The y coordinate of the copy origin.
  46107. * @param {number} width - The width of the copy.
  46108. * @param {number} height - The height of the copy.
  46109. * @param {number} faceIndex - The face index.
  46110. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46111. */
  46112. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46113. const { backend, gl } = this;
  46114. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  46115. const fb = gl.createFramebuffer();
  46116. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46117. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  46118. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  46119. const typedArrayType = this._getTypedArrayType( glType );
  46120. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  46121. const elementCount = width * height;
  46122. const byteLength = elementCount * bytesPerTexel;
  46123. const buffer = gl.createBuffer();
  46124. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46125. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  46126. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  46127. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46128. await backend.utils._clientWaitAsync();
  46129. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  46130. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46131. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  46132. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46133. gl.deleteFramebuffer( fb );
  46134. return dstBuffer;
  46135. }
  46136. /**
  46137. * Returns the corresponding typed array type for the given WebGL data type.
  46138. *
  46139. * @private
  46140. * @param {GLenum} glType - The WebGL data type.
  46141. * @return {TypedArray.constructor} The typed array type.
  46142. */
  46143. _getTypedArrayType( glType ) {
  46144. const { gl } = this;
  46145. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  46146. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  46147. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  46148. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  46149. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  46150. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  46151. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  46152. if ( glType === gl.FLOAT ) return Float32Array;
  46153. throw new Error( `Unsupported WebGL type: ${glType}` );
  46154. }
  46155. /**
  46156. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  46157. *
  46158. * @private
  46159. * @param {GLenum} glType - The WebGL data type.
  46160. * @param {GLenum} glFormat - The WebGL texture format.
  46161. * @return {number} The bytes-per-texel.
  46162. */
  46163. _getBytesPerTexel( glType, glFormat ) {
  46164. const { gl } = this;
  46165. let bytesPerComponent = 0;
  46166. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  46167. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  46168. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  46169. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  46170. glType === gl.UNSIGNED_SHORT ||
  46171. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  46172. if ( glType === gl.UNSIGNED_INT ||
  46173. glType === gl.FLOAT ) bytesPerComponent = 4;
  46174. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  46175. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  46176. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  46177. }
  46178. /**
  46179. * Frees the internal resources.
  46180. */
  46181. dispose() {
  46182. const { gl } = this;
  46183. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  46184. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  46185. }
  46186. }
  46187. function getImage( source ) {
  46188. if ( source.isDataTexture ) {
  46189. return source.image.data;
  46190. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  46191. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  46192. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  46193. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  46194. return source;
  46195. }
  46196. return source.data;
  46197. }
  46198. /**
  46199. * A WebGL 2 backend utility module for managing extensions.
  46200. *
  46201. * @private
  46202. */
  46203. class WebGLExtensions {
  46204. /**
  46205. * Constructs a new utility object.
  46206. *
  46207. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46208. */
  46209. constructor( backend ) {
  46210. /**
  46211. * A reference to the WebGL 2 backend.
  46212. *
  46213. * @type {WebGLBackend}
  46214. */
  46215. this.backend = backend;
  46216. /**
  46217. * A reference to the rendering context.
  46218. *
  46219. * @type {WebGL2RenderingContext}
  46220. */
  46221. this.gl = this.backend.gl;
  46222. /**
  46223. * A list with all the supported WebGL extensions.
  46224. *
  46225. * @type {Array<string>}
  46226. */
  46227. this.availableExtensions = this.gl.getSupportedExtensions();
  46228. /**
  46229. * A dictionary with requested WebGL extensions.
  46230. * The key is the name of the extension, the value
  46231. * the requested extension object.
  46232. *
  46233. * @type {Object<string,Object>}
  46234. */
  46235. this.extensions = {};
  46236. }
  46237. /**
  46238. * Returns the extension object for the given extension name.
  46239. *
  46240. * @param {string} name - The extension name.
  46241. * @return {Object} The extension object.
  46242. */
  46243. get( name ) {
  46244. let extension = this.extensions[ name ];
  46245. if ( extension === undefined ) {
  46246. extension = this.gl.getExtension( name );
  46247. this.extensions[ name ] = extension;
  46248. }
  46249. return extension;
  46250. }
  46251. /**
  46252. * Returns `true` if the requested extension is available.
  46253. *
  46254. * @param {string} name - The extension name.
  46255. * @return {boolean} Whether the given extension is available or not.
  46256. */
  46257. has( name ) {
  46258. return this.availableExtensions.includes( name );
  46259. }
  46260. }
  46261. /**
  46262. * A WebGL 2 backend utility module for managing the device's capabilities.
  46263. *
  46264. * @private
  46265. */
  46266. class WebGLCapabilities {
  46267. /**
  46268. * Constructs a new utility object.
  46269. *
  46270. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46271. */
  46272. constructor( backend ) {
  46273. /**
  46274. * A reference to the WebGL 2 backend.
  46275. *
  46276. * @type {WebGLBackend}
  46277. */
  46278. this.backend = backend;
  46279. /**
  46280. * This value holds the cached max anisotropy value.
  46281. *
  46282. * @type {?number}
  46283. * @default null
  46284. */
  46285. this.maxAnisotropy = null;
  46286. }
  46287. /**
  46288. * Returns the maximum anisotropy texture filtering value. This value
  46289. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  46290. * WebGL extension.
  46291. *
  46292. * @return {number} The maximum anisotropy texture filtering value.
  46293. */
  46294. getMaxAnisotropy() {
  46295. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  46296. const gl = this.backend.gl;
  46297. const extensions = this.backend.extensions;
  46298. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46299. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46300. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  46301. } else {
  46302. this.maxAnisotropy = 0;
  46303. }
  46304. return this.maxAnisotropy;
  46305. }
  46306. }
  46307. const GLFeatureName = {
  46308. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  46309. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  46310. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  46311. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  46312. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46313. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46314. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  46315. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  46316. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  46317. 'OVR_multiview2': 'OVR_multiview2'
  46318. };
  46319. class WebGLBufferRenderer {
  46320. constructor( backend ) {
  46321. this.gl = backend.gl;
  46322. this.extensions = backend.extensions;
  46323. this.info = backend.renderer.info;
  46324. this.mode = null;
  46325. this.index = 0;
  46326. this.type = null;
  46327. this.object = null;
  46328. }
  46329. render( start, count ) {
  46330. const { gl, mode, object, type, info, index } = this;
  46331. if ( index !== 0 ) {
  46332. gl.drawElements( mode, count, type, start );
  46333. } else {
  46334. gl.drawArrays( mode, start, count );
  46335. }
  46336. info.update( object, count, 1 );
  46337. }
  46338. renderInstances( start, count, primcount ) {
  46339. const { gl, mode, type, index, object, info } = this;
  46340. if ( primcount === 0 ) return;
  46341. if ( index !== 0 ) {
  46342. gl.drawElementsInstanced( mode, count, type, start, primcount );
  46343. } else {
  46344. gl.drawArraysInstanced( mode, start, count, primcount );
  46345. }
  46346. info.update( object, count, primcount );
  46347. }
  46348. renderMultiDraw( starts, counts, drawCount ) {
  46349. const { extensions, mode, object, info } = this;
  46350. if ( drawCount === 0 ) return;
  46351. const extension = extensions.get( 'WEBGL_multi_draw' );
  46352. if ( extension === null ) {
  46353. for ( let i = 0; i < drawCount; i ++ ) {
  46354. this.render( starts[ i ], counts[ i ] );
  46355. }
  46356. } else {
  46357. if ( this.index !== 0 ) {
  46358. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  46359. } else {
  46360. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  46361. }
  46362. let elementCount = 0;
  46363. for ( let i = 0; i < drawCount; i ++ ) {
  46364. elementCount += counts[ i ];
  46365. }
  46366. info.update( object, elementCount, 1 );
  46367. }
  46368. }
  46369. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  46370. const { extensions, mode, object, info } = this;
  46371. if ( drawCount === 0 ) return;
  46372. const extension = extensions.get( 'WEBGL_multi_draw' );
  46373. if ( extension === null ) {
  46374. for ( let i = 0; i < drawCount; i ++ ) {
  46375. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  46376. }
  46377. } else {
  46378. if ( this.index !== 0 ) {
  46379. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  46380. } else {
  46381. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  46382. }
  46383. let elementCount = 0;
  46384. for ( let i = 0; i < drawCount; i ++ ) {
  46385. elementCount += counts[ i ] * primcount[ i ];
  46386. }
  46387. info.update( object, elementCount, 1 );
  46388. }
  46389. }
  46390. //
  46391. }
  46392. /**
  46393. * Abstract base class of a timestamp query pool.
  46394. *
  46395. * @abstract
  46396. */
  46397. class TimestampQueryPool {
  46398. /**
  46399. * Creates a new timestamp query pool.
  46400. *
  46401. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  46402. */
  46403. constructor( maxQueries = 256 ) {
  46404. /**
  46405. * Whether to track timestamps or not.
  46406. *
  46407. * @type {boolean}
  46408. * @default true
  46409. */
  46410. this.trackTimestamp = true;
  46411. /**
  46412. * Maximum number of queries this pool can hold.
  46413. *
  46414. * @type {number}
  46415. * @default 256
  46416. */
  46417. this.maxQueries = maxQueries;
  46418. /**
  46419. * How many queries allocated so far.
  46420. *
  46421. * @type {number}
  46422. * @default 0
  46423. */
  46424. this.currentQueryIndex = 0;
  46425. /**
  46426. * Tracks offsets for different contexts.
  46427. *
  46428. * @type {Map<string, number>}
  46429. */
  46430. this.queryOffsets = new Map();
  46431. /**
  46432. * Whether the pool has been disposed or not.
  46433. *
  46434. * @type {boolean}
  46435. * @default false
  46436. */
  46437. this.isDisposed = false;
  46438. /**
  46439. * TODO
  46440. *
  46441. * @type {number}
  46442. * @default 0
  46443. */
  46444. this.lastValue = 0;
  46445. /**
  46446. * Stores all timestamp frames.
  46447. *
  46448. * @type {Array<number>}
  46449. */
  46450. this.frames = [];
  46451. /**
  46452. * TODO
  46453. *
  46454. * @type {boolean}
  46455. * @default false
  46456. */
  46457. this.pendingResolve = false;
  46458. /**
  46459. * Stores the latest timestamp for each render context.
  46460. *
  46461. * @type {Map<string, number>}
  46462. */
  46463. this.timestamps = new Map();
  46464. }
  46465. /**
  46466. * Returns all timestamp frames.
  46467. *
  46468. * @return {Array<number>} The timestamp frames.
  46469. */
  46470. getTimestampFrames() {
  46471. return this.frames;
  46472. }
  46473. /**
  46474. * Returns the timestamp for a given render context.
  46475. *
  46476. * @param {string} uid - A unique identifier for the render context.
  46477. * @return {?number} The timestamp, or undefined if not available.
  46478. */
  46479. getTimestamp( uid ) {
  46480. let timestamp = this.timestamps.get( uid );
  46481. if ( timestamp === undefined ) {
  46482. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  46483. timestamp = 0;
  46484. }
  46485. return timestamp;
  46486. }
  46487. /**
  46488. * Returns whether a timestamp is available for a given render context.
  46489. *
  46490. * @param {string} uid - A unique identifier for the render context.
  46491. * @return {boolean} True if a timestamp is available, false otherwise.
  46492. */
  46493. hasTimestamp( uid ) {
  46494. return this.timestamps.has( uid );
  46495. }
  46496. /**
  46497. * Allocate queries for a specific uid.
  46498. *
  46499. * @abstract
  46500. * @param {string} uid - A unique identifier for the render context.
  46501. * @param {number} frameId - The current frame identifier.
  46502. * @returns {?number}
  46503. */
  46504. allocateQueriesForContext( /* uid, frameId */ ) {}
  46505. /**
  46506. * Resolve all timestamps and return data (or process them).
  46507. *
  46508. * @abstract
  46509. * @async
  46510. * @returns {Promise<number>|number} The resolved timestamp value.
  46511. */
  46512. async resolveQueriesAsync() {}
  46513. /**
  46514. * Dispose of the query pool.
  46515. *
  46516. * @abstract
  46517. */
  46518. dispose() {}
  46519. }
  46520. /**
  46521. * Manages a pool of WebGL timestamp queries for performance measurement.
  46522. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  46523. *
  46524. * @augments TimestampQueryPool
  46525. */
  46526. class WebGLTimestampQueryPool extends TimestampQueryPool {
  46527. /**
  46528. * Creates a new WebGL timestamp query pool.
  46529. *
  46530. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  46531. * @param {string} type - The type identifier for this query pool.
  46532. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46533. */
  46534. constructor( gl, type, maxQueries = 2048 ) {
  46535. super( maxQueries );
  46536. this.gl = gl;
  46537. this.type = type;
  46538. // Check for timer query extensions
  46539. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  46540. gl.getExtension( 'EXT_disjoint_timer_query' );
  46541. if ( ! this.ext ) {
  46542. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  46543. this.trackTimestamp = false;
  46544. return;
  46545. }
  46546. // Create query objects
  46547. this.queries = [];
  46548. for ( let i = 0; i < this.maxQueries; i ++ ) {
  46549. this.queries.push( gl.createQuery() );
  46550. }
  46551. this.activeQuery = null;
  46552. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  46553. }
  46554. /**
  46555. * Allocates a pair of queries for a given render context.
  46556. *
  46557. * @param {string} uid - A unique identifier for the render context.
  46558. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46559. */
  46560. allocateQueriesForContext( uid ) {
  46561. if ( ! this.trackTimestamp ) return null;
  46562. // Check if we have enough space for a new query pair
  46563. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46564. 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() } ).` );
  46565. return null;
  46566. }
  46567. const baseOffset = this.currentQueryIndex;
  46568. this.currentQueryIndex += 2;
  46569. // Initialize query states
  46570. this.queryStates.set( baseOffset, 'inactive' );
  46571. this.queryOffsets.set( uid, baseOffset );
  46572. return baseOffset;
  46573. }
  46574. /**
  46575. * Begins a timestamp query for the specified render context.
  46576. *
  46577. * @param {string} uid - A unique identifier for the render context.
  46578. */
  46579. beginQuery( uid ) {
  46580. if ( ! this.trackTimestamp || this.isDisposed ) {
  46581. return;
  46582. }
  46583. const baseOffset = this.queryOffsets.get( uid );
  46584. if ( baseOffset == null ) {
  46585. return;
  46586. }
  46587. // Don't start a new query if there's an active one
  46588. if ( this.activeQuery !== null ) {
  46589. return;
  46590. }
  46591. const query = this.queries[ baseOffset ];
  46592. if ( ! query ) {
  46593. return;
  46594. }
  46595. try {
  46596. // Only begin if query is inactive
  46597. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  46598. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  46599. this.activeQuery = baseOffset;
  46600. this.queryStates.set( baseOffset, 'started' );
  46601. }
  46602. } catch ( error ) {
  46603. error( 'Error in beginQuery:', error );
  46604. this.activeQuery = null;
  46605. this.queryStates.set( baseOffset, 'inactive' );
  46606. }
  46607. }
  46608. /**
  46609. * Ends the active timestamp query for the specified render context.
  46610. *
  46611. * @param {string} uid - A unique identifier for the render context.
  46612. */
  46613. endQuery( uid ) {
  46614. if ( ! this.trackTimestamp || this.isDisposed ) {
  46615. return;
  46616. }
  46617. const baseOffset = this.queryOffsets.get( uid );
  46618. if ( baseOffset == null ) {
  46619. return;
  46620. }
  46621. // Only end if this is the active query
  46622. if ( this.activeQuery !== baseOffset ) {
  46623. return;
  46624. }
  46625. try {
  46626. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  46627. this.queryStates.set( baseOffset, 'ended' );
  46628. this.activeQuery = null;
  46629. } catch ( error ) {
  46630. error( 'Error in endQuery:', error );
  46631. // Reset state on error
  46632. this.queryStates.set( baseOffset, 'inactive' );
  46633. this.activeQuery = null;
  46634. }
  46635. }
  46636. /**
  46637. * Asynchronously resolves all completed queries and returns the total duration.
  46638. *
  46639. * @async
  46640. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46641. */
  46642. async resolveQueriesAsync() {
  46643. if ( ! this.trackTimestamp || this.pendingResolve ) {
  46644. return this.lastValue;
  46645. }
  46646. this.pendingResolve = true;
  46647. try {
  46648. // Wait for all ended queries to complete
  46649. const resolvePromises = new Map();
  46650. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  46651. const state = this.queryStates.get( baseOffset );
  46652. if ( state === 'ended' ) {
  46653. const query = this.queries[ baseOffset ];
  46654. resolvePromises.set( uid, this.resolveQuery( query ) );
  46655. }
  46656. }
  46657. if ( resolvePromises.size === 0 ) {
  46658. return this.lastValue;
  46659. }
  46660. //
  46661. const framesDuration = {};
  46662. const frames = [];
  46663. for ( const [ uid, promise ] of resolvePromises ) {
  46664. const match = uid.match( /^(.*):f(\d+)$/ );
  46665. const frame = parseInt( match[ 2 ] );
  46666. if ( frames.includes( frame ) === false ) {
  46667. frames.push( frame );
  46668. }
  46669. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  46670. const duration = await promise;
  46671. this.timestamps.set( uid, duration );
  46672. framesDuration[ frame ] += duration;
  46673. }
  46674. // Return the total duration of the last frame
  46675. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  46676. // Store the last valid result
  46677. this.lastValue = totalDuration;
  46678. this.frames = frames;
  46679. // Reset states
  46680. this.currentQueryIndex = 0;
  46681. this.queryOffsets.clear();
  46682. this.queryStates.clear();
  46683. this.activeQuery = null;
  46684. return totalDuration;
  46685. } catch ( error ) {
  46686. error( 'Error resolving queries:', error );
  46687. return this.lastValue;
  46688. } finally {
  46689. this.pendingResolve = false;
  46690. }
  46691. }
  46692. /**
  46693. * Resolves a single query, checking for completion and disjoint operation.
  46694. *
  46695. * @async
  46696. * @param {WebGLQuery} query - The query object to resolve.
  46697. * @returns {Promise<number>} The elapsed time in milliseconds.
  46698. */
  46699. async resolveQuery( query ) {
  46700. return new Promise( ( resolve ) => {
  46701. if ( this.isDisposed ) {
  46702. resolve( this.lastValue );
  46703. return;
  46704. }
  46705. let timeoutId;
  46706. let isResolved = false;
  46707. const cleanup = () => {
  46708. if ( timeoutId ) {
  46709. clearTimeout( timeoutId );
  46710. timeoutId = null;
  46711. }
  46712. };
  46713. const finalizeResolution = ( value ) => {
  46714. if ( ! isResolved ) {
  46715. isResolved = true;
  46716. cleanup();
  46717. resolve( value );
  46718. }
  46719. };
  46720. const checkQuery = () => {
  46721. if ( this.isDisposed ) {
  46722. finalizeResolution( this.lastValue );
  46723. return;
  46724. }
  46725. try {
  46726. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  46727. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  46728. if ( disjoint ) {
  46729. finalizeResolution( this.lastValue );
  46730. return;
  46731. }
  46732. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  46733. if ( ! available ) {
  46734. timeoutId = setTimeout( checkQuery, 1 );
  46735. return;
  46736. }
  46737. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  46738. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  46739. } catch ( error ) {
  46740. error( 'Error checking query:', error );
  46741. resolve( this.lastValue );
  46742. }
  46743. };
  46744. checkQuery();
  46745. } );
  46746. }
  46747. /**
  46748. * Releases all resources held by this query pool.
  46749. * This includes deleting all query objects and clearing internal state.
  46750. */
  46751. dispose() {
  46752. if ( this.isDisposed ) {
  46753. return;
  46754. }
  46755. this.isDisposed = true;
  46756. if ( ! this.trackTimestamp ) return;
  46757. for ( const query of this.queries ) {
  46758. this.gl.deleteQuery( query );
  46759. }
  46760. this.queries = [];
  46761. this.queryStates.clear();
  46762. this.queryOffsets.clear();
  46763. this.lastValue = 0;
  46764. this.activeQuery = null;
  46765. }
  46766. }
  46767. /**
  46768. * A backend implementation targeting WebGL 2.
  46769. *
  46770. * @private
  46771. * @augments Backend
  46772. */
  46773. class WebGLBackend extends Backend {
  46774. /**
  46775. * WebGLBackend options.
  46776. *
  46777. * @typedef {Object} WebGLBackend~Options
  46778. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46779. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46780. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46781. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46782. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46783. * @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.
  46784. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46785. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  46786. */
  46787. /**
  46788. * Constructs a new WebGPU backend.
  46789. *
  46790. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  46791. */
  46792. constructor( parameters = {} ) {
  46793. super( parameters );
  46794. /**
  46795. * This flag can be used for type testing.
  46796. *
  46797. * @type {boolean}
  46798. * @readonly
  46799. * @default true
  46800. */
  46801. this.isWebGLBackend = true;
  46802. /**
  46803. * A reference to a backend module holding shader attribute-related
  46804. * utility functions.
  46805. *
  46806. * @type {?WebGLAttributeUtils}
  46807. * @default null
  46808. */
  46809. this.attributeUtils = null;
  46810. /**
  46811. * A reference to a backend module holding extension-related
  46812. * utility functions.
  46813. *
  46814. * @type {?WebGLExtensions}
  46815. * @default null
  46816. */
  46817. this.extensions = null;
  46818. /**
  46819. * A reference to a backend module holding capability-related
  46820. * utility functions.
  46821. *
  46822. * @type {?WebGLCapabilities}
  46823. * @default null
  46824. */
  46825. this.capabilities = null;
  46826. /**
  46827. * A reference to a backend module holding texture-related
  46828. * utility functions.
  46829. *
  46830. * @type {?WebGLTextureUtils}
  46831. * @default null
  46832. */
  46833. this.textureUtils = null;
  46834. /**
  46835. * A reference to a backend module holding renderer-related
  46836. * utility functions.
  46837. *
  46838. * @type {?WebGLBufferRenderer}
  46839. * @default null
  46840. */
  46841. this.bufferRenderer = null;
  46842. /**
  46843. * A reference to the rendering context.
  46844. *
  46845. * @type {?WebGL2RenderingContext}
  46846. * @default null
  46847. */
  46848. this.gl = null;
  46849. /**
  46850. * A reference to a backend module holding state-related
  46851. * utility functions.
  46852. *
  46853. * @type {?WebGLState}
  46854. * @default null
  46855. */
  46856. this.state = null;
  46857. /**
  46858. * A reference to a backend module holding common
  46859. * utility functions.
  46860. *
  46861. * @type {?WebGLUtils}
  46862. * @default null
  46863. */
  46864. this.utils = null;
  46865. /**
  46866. * Dictionary for caching VAOs.
  46867. *
  46868. * @type {Object<string,WebGLVertexArrayObject>}
  46869. */
  46870. this.vaoCache = {};
  46871. /**
  46872. * Dictionary for caching transform feedback objects.
  46873. *
  46874. * @type {Object<string,WebGLTransformFeedback>}
  46875. */
  46876. this.transformFeedbackCache = {};
  46877. /**
  46878. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  46879. * Only relevant when using compute shaders.
  46880. *
  46881. * @type {boolean}
  46882. * @default false
  46883. */
  46884. this.discard = false;
  46885. /**
  46886. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  46887. * device does not support the extension.
  46888. *
  46889. * @type {?EXTDisjointTimerQueryWebGL2}
  46890. * @default null
  46891. */
  46892. this.disjoint = null;
  46893. /**
  46894. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  46895. * device does not support the extension.
  46896. *
  46897. * @type {?KHRParallelShaderCompile}
  46898. * @default null
  46899. */
  46900. this.parallel = null;
  46901. /**
  46902. * A reference to the current render context.
  46903. *
  46904. * @private
  46905. * @type {RenderContext}
  46906. * @default null
  46907. */
  46908. this._currentContext = null;
  46909. /**
  46910. * A unique collection of bindings.
  46911. *
  46912. * @private
  46913. * @type {WeakSet<Array<BindGroup>>}
  46914. */
  46915. this._knownBindings = new WeakSet();
  46916. /**
  46917. * Whether the device supports framebuffers invalidation or not.
  46918. *
  46919. * @private
  46920. * @type {boolean}
  46921. */
  46922. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  46923. /**
  46924. * The target framebuffer when rendering with
  46925. * the WebXR device API.
  46926. *
  46927. * @private
  46928. * @type {?WebGLFramebuffer}
  46929. * @default null
  46930. */
  46931. this._xrFramebuffer = null;
  46932. }
  46933. /**
  46934. * Initializes the backend so it is ready for usage.
  46935. *
  46936. * @param {Renderer} renderer - The renderer.
  46937. */
  46938. init( renderer ) {
  46939. super.init( renderer );
  46940. //
  46941. const parameters = this.parameters;
  46942. const contextAttributes = {
  46943. antialias: renderer.currentSamples > 0,
  46944. alpha: true, // always true for performance reasons
  46945. depth: renderer.depth,
  46946. stencil: renderer.stencil
  46947. };
  46948. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  46949. function onContextLost( event ) {
  46950. event.preventDefault();
  46951. const contextLossInfo = {
  46952. api: 'WebGL',
  46953. message: event.statusMessage || 'Unknown reason',
  46954. reason: null,
  46955. originalEvent: event
  46956. };
  46957. renderer.onDeviceLost( contextLossInfo );
  46958. }
  46959. this._onContextLost = onContextLost;
  46960. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  46961. this.gl = glContext;
  46962. this.extensions = new WebGLExtensions( this );
  46963. this.capabilities = new WebGLCapabilities( this );
  46964. this.attributeUtils = new WebGLAttributeUtils( this );
  46965. this.textureUtils = new WebGLTextureUtils( this );
  46966. this.bufferRenderer = new WebGLBufferRenderer( this );
  46967. this.state = new WebGLState( this );
  46968. this.utils = new WebGLUtils( this );
  46969. this.extensions.get( 'EXT_color_buffer_float' );
  46970. this.extensions.get( 'WEBGL_clip_cull_distance' );
  46971. this.extensions.get( 'OES_texture_float_linear' );
  46972. this.extensions.get( 'EXT_color_buffer_half_float' );
  46973. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46974. this.extensions.get( 'WEBGL_render_shared_exponent' );
  46975. this.extensions.get( 'WEBGL_multi_draw' );
  46976. this.extensions.get( 'OVR_multiview2' );
  46977. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  46978. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  46979. }
  46980. /**
  46981. * The coordinate system of the backend.
  46982. *
  46983. * @type {number}
  46984. * @readonly
  46985. */
  46986. get coordinateSystem() {
  46987. return WebGLCoordinateSystem;
  46988. }
  46989. /**
  46990. * This method performs a readback operation by moving buffer data from
  46991. * a storage buffer attribute from the GPU to the CPU.
  46992. *
  46993. * @async
  46994. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46995. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46996. */
  46997. async getArrayBufferAsync( attribute ) {
  46998. return await this.attributeUtils.getArrayBufferAsync( attribute );
  46999. }
  47000. /**
  47001. * Ensures the backend is XR compatible.
  47002. *
  47003. * @async
  47004. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  47005. */
  47006. async makeXRCompatible() {
  47007. const attributes = this.gl.getContextAttributes();
  47008. if ( attributes.xrCompatible !== true ) {
  47009. await this.gl.makeXRCompatible();
  47010. }
  47011. }
  47012. /**
  47013. * Sets the XR rendering destination.
  47014. *
  47015. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  47016. */
  47017. setXRTarget( xrFramebuffer ) {
  47018. this._xrFramebuffer = xrFramebuffer;
  47019. }
  47020. /**
  47021. * Configures the given XR render target with external textures.
  47022. *
  47023. * This method is only relevant when using the WebXR Layers API.
  47024. *
  47025. * @param {XRRenderTarget} renderTarget - The XR render target.
  47026. * @param {WebGLTexture} colorTexture - A native color texture.
  47027. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  47028. */
  47029. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  47030. const gl = this.gl;
  47031. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  47032. if ( depthTexture !== null ) {
  47033. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  47034. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  47035. // The multisample_render_to_texture extension doesn't work properly if there
  47036. // are midframe flushes and an external depth texture.
  47037. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  47038. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  47039. }
  47040. renderTarget._autoAllocateDepthBuffer = false;
  47041. }
  47042. }
  47043. /**
  47044. * Inits a time stamp query for the given render context.
  47045. *
  47046. * @param {string} type - The type of the timestamp query.
  47047. * @param {string} uid - A unique identifier for the timestamp query.
  47048. */
  47049. initTimestampQuery( type, uid ) {
  47050. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47051. if ( ! this.timestampQueryPool[ type ] ) {
  47052. // TODO: Variable maxQueries?
  47053. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  47054. }
  47055. const timestampQueryPool = this.timestampQueryPool[ type ];
  47056. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  47057. if ( baseOffset !== null ) {
  47058. timestampQueryPool.beginQuery( uid );
  47059. }
  47060. }
  47061. // timestamp utils
  47062. /**
  47063. * Prepares the timestamp buffer.
  47064. *
  47065. * @param {string} type - The type of the timestamp query.
  47066. * @param {string} uid - A unique identifier for the timestamp query.
  47067. */
  47068. prepareTimestampBuffer( type, uid ) {
  47069. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47070. const timestampQueryPool = this.timestampQueryPool[ type ];
  47071. timestampQueryPool.endQuery( uid );
  47072. }
  47073. /**
  47074. * Returns the backend's rendering context.
  47075. *
  47076. * @return {WebGL2RenderingContext} The rendering context.
  47077. */
  47078. getContext() {
  47079. return this.gl;
  47080. }
  47081. /**
  47082. * This method is executed at the beginning of a render call and prepares
  47083. * the WebGL state for upcoming render calls
  47084. *
  47085. * @param {RenderContext} renderContext - The render context.
  47086. */
  47087. beginRender( renderContext ) {
  47088. const { state } = this;
  47089. const renderContextData = this.get( renderContext );
  47090. //
  47091. if ( renderContext.viewport ) {
  47092. this.updateViewport( renderContext );
  47093. } else {
  47094. const { width, height } = this.getDrawingBufferSize();
  47095. state.viewport( 0, 0, width, height );
  47096. }
  47097. if ( renderContext.scissor ) {
  47098. const { x, y, width, height } = renderContext.scissorValue;
  47099. state.scissor( x, renderContext.height - height - y, width, height );
  47100. }
  47101. //
  47102. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47103. renderContextData.previousContext = this._currentContext;
  47104. this._currentContext = renderContext;
  47105. this._setFramebuffer( renderContext );
  47106. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  47107. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47108. if ( occlusionQueryCount > 0 ) {
  47109. // Get a reference to the array of objects with queries. The renderContextData property
  47110. // can be changed by another render pass before the async reading of all previous queries complete
  47111. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  47112. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47113. renderContextData.lastOcclusionObject = null;
  47114. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  47115. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47116. renderContextData.occlusionQueryIndex = 0;
  47117. }
  47118. }
  47119. /**
  47120. * This method is executed at the end of a render call and finalizes work
  47121. * after draw calls.
  47122. *
  47123. * @param {RenderContext} renderContext - The render context.
  47124. */
  47125. finishRender( renderContext ) {
  47126. const { gl, state } = this;
  47127. const renderContextData = this.get( renderContext );
  47128. const previousContext = renderContextData.previousContext;
  47129. state.resetVertexState();
  47130. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47131. if ( occlusionQueryCount > 0 ) {
  47132. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47133. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47134. }
  47135. this.resolveOccludedAsync( renderContext );
  47136. }
  47137. const textures = renderContext.textures;
  47138. if ( textures !== null ) {
  47139. for ( let i = 0; i < textures.length; i ++ ) {
  47140. const texture = textures[ i ];
  47141. if ( texture.generateMipmaps ) {
  47142. this.generateMipmaps( texture );
  47143. }
  47144. }
  47145. }
  47146. this._currentContext = previousContext;
  47147. this._resolveRenderTarget( renderContext );
  47148. if ( previousContext !== null ) {
  47149. this._setFramebuffer( previousContext );
  47150. if ( previousContext.viewport ) {
  47151. this.updateViewport( previousContext );
  47152. } else {
  47153. const { width, height } = this.getDrawingBufferSize();
  47154. state.viewport( 0, 0, width, height );
  47155. }
  47156. }
  47157. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47158. }
  47159. /**
  47160. * This method processes the result of occlusion queries and writes it
  47161. * into render context data.
  47162. *
  47163. * @async
  47164. * @param {RenderContext} renderContext - The render context.
  47165. */
  47166. resolveOccludedAsync( renderContext ) {
  47167. const renderContextData = this.get( renderContext );
  47168. // handle occlusion query results
  47169. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  47170. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  47171. const occluded = new WeakSet();
  47172. const { gl } = this;
  47173. renderContextData.currentOcclusionQueryObjects = null;
  47174. renderContextData.currentOcclusionQueries = null;
  47175. const check = () => {
  47176. let completed = 0;
  47177. // check all queries and requeue as appropriate
  47178. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  47179. const query = currentOcclusionQueries[ i ];
  47180. if ( query === null ) continue;
  47181. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  47182. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  47183. currentOcclusionQueries[ i ] = null;
  47184. gl.deleteQuery( query );
  47185. completed ++;
  47186. }
  47187. }
  47188. if ( completed < currentOcclusionQueries.length ) {
  47189. requestAnimationFrame( check );
  47190. } else {
  47191. renderContextData.occluded = occluded;
  47192. }
  47193. };
  47194. check();
  47195. }
  47196. }
  47197. /**
  47198. * Returns `true` if the given 3D object is fully occluded by other
  47199. * 3D objects in the scene.
  47200. *
  47201. * @param {RenderContext} renderContext - The render context.
  47202. * @param {Object3D} object - The 3D object to test.
  47203. * @return {boolean} Whether the 3D object is fully occluded or not.
  47204. */
  47205. isOccluded( renderContext, object ) {
  47206. const renderContextData = this.get( renderContext );
  47207. return renderContextData.occluded && renderContextData.occluded.has( object );
  47208. }
  47209. /**
  47210. * Updates the viewport with the values from the given render context.
  47211. *
  47212. * @param {RenderContext} renderContext - The render context.
  47213. */
  47214. updateViewport( renderContext ) {
  47215. const { state } = this;
  47216. const { x, y, width, height } = renderContext.viewportValue;
  47217. state.viewport( x, renderContext.height - height - y, width, height );
  47218. }
  47219. /**
  47220. * Defines the scissor test.
  47221. *
  47222. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47223. */
  47224. setScissorTest( boolean ) {
  47225. const state = this.state;
  47226. state.setScissorTest( boolean );
  47227. }
  47228. /**
  47229. * Returns the clear color and alpha into a single
  47230. * color object.
  47231. *
  47232. * @return {Color4} The clear color.
  47233. */
  47234. getClearColor() {
  47235. const clearColor = super.getClearColor();
  47236. // Since the canvas is always created with alpha: true,
  47237. // WebGL must always premultiply the clear color.
  47238. clearColor.r *= clearColor.a;
  47239. clearColor.g *= clearColor.a;
  47240. clearColor.b *= clearColor.a;
  47241. return clearColor;
  47242. }
  47243. /**
  47244. * Performs a clear operation.
  47245. *
  47246. * @param {boolean} color - Whether the color buffer should be cleared or not.
  47247. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  47248. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  47249. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  47250. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  47251. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  47252. * or not. Only relevant for explicit clears.
  47253. */
  47254. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  47255. const { gl, renderer } = this;
  47256. if ( descriptor === null ) {
  47257. const clearColor = this.getClearColor();
  47258. descriptor = {
  47259. textures: null,
  47260. clearColorValue: clearColor
  47261. };
  47262. }
  47263. //
  47264. let clear = 0;
  47265. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  47266. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  47267. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  47268. if ( clear !== 0 ) {
  47269. let clearColor;
  47270. if ( descriptor.clearColorValue ) {
  47271. clearColor = descriptor.clearColorValue;
  47272. } else {
  47273. clearColor = this.getClearColor();
  47274. }
  47275. const clearDepth = renderer.getClearDepth();
  47276. const clearStencil = renderer.getClearStencil();
  47277. if ( depth ) this.state.setDepthMask( true );
  47278. if ( descriptor.textures === null ) {
  47279. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  47280. gl.clear( clear );
  47281. } else {
  47282. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  47283. if ( color ) {
  47284. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  47285. if ( i === 0 ) {
  47286. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  47287. } else {
  47288. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  47289. }
  47290. }
  47291. }
  47292. if ( depth && stencil ) {
  47293. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  47294. } else if ( depth ) {
  47295. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  47296. } else if ( stencil ) {
  47297. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  47298. }
  47299. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  47300. }
  47301. }
  47302. }
  47303. /**
  47304. * This method is executed at the beginning of a compute call and
  47305. * prepares the state for upcoming compute tasks.
  47306. *
  47307. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47308. */
  47309. beginCompute( computeGroup ) {
  47310. const { state, gl } = this;
  47311. //
  47312. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47313. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47314. }
  47315. /**
  47316. * Executes a compute command for the given compute node.
  47317. *
  47318. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47319. * @param {Node} computeNode - The compute node.
  47320. * @param {Array<BindGroup>} bindings - The bindings.
  47321. * @param {ComputePipeline} pipeline - The compute pipeline.
  47322. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  47323. */
  47324. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  47325. const { state, gl } = this;
  47326. if ( this.discard === false ) {
  47327. // required here to handle async behaviour of render.compute()
  47328. gl.enable( gl.RASTERIZER_DISCARD );
  47329. this.discard = true;
  47330. }
  47331. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  47332. const vaoKey = this._getVaoKey( attributes );
  47333. const vaoGPU = this.vaoCache[ vaoKey ];
  47334. if ( vaoGPU === undefined ) {
  47335. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  47336. } else {
  47337. state.setVertexState( vaoGPU );
  47338. }
  47339. state.useProgram( programGPU );
  47340. this._bindUniforms( bindings );
  47341. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  47342. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47343. gl.beginTransformFeedback( gl.POINTS );
  47344. count = ( count !== null ) ? count : computeNode.count;
  47345. if ( Array.isArray( count ) ) {
  47346. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  47347. count = count[ 0 ];
  47348. }
  47349. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  47350. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  47351. } else {
  47352. gl.drawArrays( gl.POINTS, 0, count );
  47353. }
  47354. gl.endTransformFeedback();
  47355. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47356. // switch active buffers
  47357. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47358. const dualAttributeData = transformBuffers[ i ];
  47359. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  47360. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  47361. }
  47362. dualAttributeData.switchBuffers();
  47363. }
  47364. }
  47365. /**
  47366. * This method is executed at the end of a compute call and
  47367. * finalizes work after compute tasks.
  47368. *
  47369. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47370. */
  47371. finishCompute( computeGroup ) {
  47372. const gl = this.gl;
  47373. this.discard = false;
  47374. gl.disable( gl.RASTERIZER_DISCARD );
  47375. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47376. if ( this._currentContext ) {
  47377. this._setFramebuffer( this._currentContext );
  47378. }
  47379. }
  47380. /**
  47381. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  47382. *
  47383. * @param {RenderContext} renderContext - The render context.
  47384. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  47385. *
  47386. * @private
  47387. */
  47388. _isRenderCameraDepthArray( renderContext ) {
  47389. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  47390. }
  47391. /**
  47392. * Executes a draw command for the given render object.
  47393. *
  47394. * @param {RenderObject} renderObject - The render object to draw.
  47395. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47396. */
  47397. draw( renderObject/*, info*/ ) {
  47398. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  47399. const { programGPU } = this.get( pipeline );
  47400. const { gl, state } = this;
  47401. const contextData = this.get( context );
  47402. const drawParams = renderObject.getDrawParameters();
  47403. if ( drawParams === null ) return;
  47404. //
  47405. this._bindUniforms( renderObject.getBindings() );
  47406. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  47407. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  47408. state.useProgram( programGPU );
  47409. // vertex state
  47410. const attributes = renderObject.getAttributes();
  47411. const attributesData = this.get( attributes );
  47412. let vaoGPU = attributesData.vaoGPU;
  47413. if ( vaoGPU === undefined ) {
  47414. const vaoKey = this._getVaoKey( attributes );
  47415. vaoGPU = this.vaoCache[ vaoKey ];
  47416. if ( vaoGPU === undefined ) {
  47417. vaoGPU = this._createVao( attributes );
  47418. this.vaoCache[ vaoKey ] = vaoGPU;
  47419. attributesData.vaoGPU = vaoGPU;
  47420. }
  47421. }
  47422. const index = renderObject.getIndex();
  47423. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  47424. state.setVertexState( vaoGPU, indexGPU );
  47425. //
  47426. const lastObject = contextData.lastOcclusionObject;
  47427. if ( lastObject !== object && lastObject !== undefined ) {
  47428. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47429. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47430. contextData.occlusionQueryIndex ++;
  47431. }
  47432. if ( object.occlusionTest === true ) {
  47433. const query = gl.createQuery();
  47434. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  47435. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  47436. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  47437. }
  47438. contextData.lastOcclusionObject = object;
  47439. }
  47440. //
  47441. const renderer = this.bufferRenderer;
  47442. if ( object.isPoints ) renderer.mode = gl.POINTS;
  47443. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  47444. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  47445. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  47446. else {
  47447. if ( material.wireframe === true ) {
  47448. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  47449. renderer.mode = gl.LINES;
  47450. } else {
  47451. renderer.mode = gl.TRIANGLES;
  47452. }
  47453. }
  47454. //
  47455. const { vertexCount, instanceCount } = drawParams;
  47456. let { firstVertex } = drawParams;
  47457. renderer.object = object;
  47458. if ( index !== null ) {
  47459. firstVertex *= index.array.BYTES_PER_ELEMENT;
  47460. const indexData = this.get( index );
  47461. renderer.index = index.count;
  47462. renderer.type = indexData.type;
  47463. } else {
  47464. renderer.index = 0;
  47465. }
  47466. const draw = () => {
  47467. if ( object.isBatchedMesh ) {
  47468. if ( object._multiDrawInstances !== null ) {
  47469. // @deprecated, r174
  47470. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  47471. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  47472. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  47473. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  47474. } else {
  47475. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  47476. }
  47477. } else if ( instanceCount > 1 ) {
  47478. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  47479. } else {
  47480. renderer.render( firstVertex, vertexCount );
  47481. }
  47482. };
  47483. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  47484. const cameraData = this.get( renderObject.camera );
  47485. const cameras = renderObject.camera.cameras;
  47486. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  47487. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47488. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47489. const indexesGPU = [];
  47490. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47491. const bufferGPU = gl.createBuffer();
  47492. data[ 0 ] = i;
  47493. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47494. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  47495. indexesGPU.push( bufferGPU );
  47496. }
  47497. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47498. }
  47499. const cameraIndexData = this.get( cameraIndex );
  47500. const pixelRatio = this.renderer.getPixelRatio();
  47501. const renderTarget = this._currentContext.renderTarget;
  47502. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  47503. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  47504. if ( isRenderCameraDepthArray ) {
  47505. // Clear the depth texture
  47506. const textureData = this.get( renderTarget.depthTexture );
  47507. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  47508. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  47509. const { stencilBuffer } = renderTarget;
  47510. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47511. this.renderer._activeCubeFace = i;
  47512. this._currentContext.activeCubeFace = i;
  47513. this._setFramebuffer( this._currentContext );
  47514. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  47515. }
  47516. this.renderer._activeCubeFace = prevActiveCubeFace;
  47517. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47518. }
  47519. }
  47520. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47521. const subCamera = cameras[ i ];
  47522. if ( object.layers.test( subCamera.layers ) ) {
  47523. if ( isRenderCameraDepthArray ) {
  47524. // Update the active layer
  47525. this.renderer._activeCubeFace = i;
  47526. this._currentContext.activeCubeFace = i;
  47527. this._setFramebuffer( this._currentContext );
  47528. }
  47529. const vp = subCamera.viewport;
  47530. if ( vp !== undefined ) {
  47531. const x = vp.x * pixelRatio;
  47532. const y = vp.y * pixelRatio;
  47533. const width = vp.width * pixelRatio;
  47534. const height = vp.height * pixelRatio;
  47535. state.viewport(
  47536. Math.floor( x ),
  47537. Math.floor( renderObject.context.height - height - y ),
  47538. Math.floor( width ),
  47539. Math.floor( height )
  47540. );
  47541. }
  47542. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  47543. draw();
  47544. }
  47545. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47546. this.renderer._activeCubeFace = prevActiveCubeFace;
  47547. }
  47548. } else {
  47549. draw();
  47550. }
  47551. }
  47552. /**
  47553. * Explain why always null is returned.
  47554. *
  47555. * @param {RenderObject} renderObject - The render object.
  47556. * @return {boolean} Whether the render pipeline requires an update or not.
  47557. */
  47558. needsRenderUpdate( /*renderObject*/ ) {
  47559. return false;
  47560. }
  47561. /**
  47562. * Explain why no cache key is computed.
  47563. *
  47564. * @param {RenderObject} renderObject - The render object.
  47565. * @return {string} The cache key.
  47566. */
  47567. getRenderCacheKey( /*renderObject*/ ) {
  47568. return '';
  47569. }
  47570. // textures
  47571. /**
  47572. * Creates a default texture for the given texture that can be used
  47573. * as a placeholder until the actual texture is ready for usage.
  47574. *
  47575. * @param {Texture} texture - The texture to create a default texture for.
  47576. */
  47577. createDefaultTexture( texture ) {
  47578. this.textureUtils.createDefaultTexture( texture );
  47579. }
  47580. /**
  47581. * Defines a texture on the GPU for the given texture object.
  47582. *
  47583. * @param {Texture} texture - The texture.
  47584. * @param {Object} [options={}] - Optional configuration parameter.
  47585. */
  47586. createTexture( texture, options ) {
  47587. this.textureUtils.createTexture( texture, options );
  47588. }
  47589. /**
  47590. * Uploads the updated texture data to the GPU.
  47591. *
  47592. * @param {Texture} texture - The texture.
  47593. * @param {Object} [options={}] - Optional configuration parameter.
  47594. */
  47595. updateTexture( texture, options ) {
  47596. this.textureUtils.updateTexture( texture, options );
  47597. }
  47598. /**
  47599. * Generates mipmaps for the given texture.
  47600. *
  47601. * @param {Texture} texture - The texture.
  47602. */
  47603. generateMipmaps( texture ) {
  47604. this.textureUtils.generateMipmaps( texture );
  47605. }
  47606. /**
  47607. * Destroys the GPU data for the given texture object.
  47608. *
  47609. * @param {Texture} texture - The texture.
  47610. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47611. */
  47612. destroyTexture( texture, isDefaultTexture = false ) {
  47613. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  47614. }
  47615. /**
  47616. * Returns texture data as a typed array.
  47617. *
  47618. * @async
  47619. * @param {Texture} texture - The texture to copy.
  47620. * @param {number} x - The x coordinate of the copy origin.
  47621. * @param {number} y - The y coordinate of the copy origin.
  47622. * @param {number} width - The width of the copy.
  47623. * @param {number} height - The height of the copy.
  47624. * @param {number} faceIndex - The face index.
  47625. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47626. */
  47627. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47628. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47629. }
  47630. /**
  47631. * This method does nothing since WebGL 2 has no concept of samplers.
  47632. *
  47633. * @param {Texture} texture - The texture to update the sampler for.
  47634. * @return {string} The current sampler key.
  47635. */
  47636. updateSampler( /*texture*/ ) {
  47637. return '';
  47638. }
  47639. // node builder
  47640. /**
  47641. * Returns a node builder for the given render object.
  47642. *
  47643. * @param {RenderObject} object - The render object.
  47644. * @param {Renderer} renderer - The renderer.
  47645. * @return {GLSLNodeBuilder} The node builder.
  47646. */
  47647. createNodeBuilder( object, renderer ) {
  47648. return new GLSLNodeBuilder( object, renderer );
  47649. }
  47650. // program
  47651. /**
  47652. * Creates a shader program from the given programmable stage.
  47653. *
  47654. * @param {ProgrammableStage} program - The programmable stage.
  47655. */
  47656. createProgram( program ) {
  47657. const gl = this.gl;
  47658. const { stage, code } = program;
  47659. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  47660. gl.shaderSource( shader, code );
  47661. gl.compileShader( shader );
  47662. this.set( program, {
  47663. shaderGPU: shader
  47664. } );
  47665. }
  47666. /**
  47667. * Destroys the shader program of the given programmable stage.
  47668. *
  47669. * @param {ProgrammableStage} program - The programmable stage.
  47670. */
  47671. destroyProgram( program ) {
  47672. this.delete( program );
  47673. }
  47674. /**
  47675. * Creates a render pipeline for the given render object.
  47676. *
  47677. * @param {RenderObject} renderObject - The render object.
  47678. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47679. */
  47680. createRenderPipeline( renderObject, promises ) {
  47681. const gl = this.gl;
  47682. const pipeline = renderObject.pipeline;
  47683. // Program
  47684. const { fragmentProgram, vertexProgram } = pipeline;
  47685. const programGPU = gl.createProgram();
  47686. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47687. const vertexShader = this.get( vertexProgram ).shaderGPU;
  47688. gl.attachShader( programGPU, fragmentShader );
  47689. gl.attachShader( programGPU, vertexShader );
  47690. gl.linkProgram( programGPU );
  47691. this.set( pipeline, {
  47692. programGPU,
  47693. fragmentShader,
  47694. vertexShader
  47695. } );
  47696. if ( promises !== null && this.parallel ) {
  47697. const p = new Promise( ( resolve /*, reject*/ ) => {
  47698. const parallel = this.parallel;
  47699. const checkStatus = () => {
  47700. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  47701. this._completeCompile( renderObject, pipeline );
  47702. resolve();
  47703. } else {
  47704. requestAnimationFrame( checkStatus );
  47705. }
  47706. };
  47707. checkStatus();
  47708. } );
  47709. promises.push( p );
  47710. return;
  47711. }
  47712. this._completeCompile( renderObject, pipeline );
  47713. }
  47714. /**
  47715. * Formats the source code of error messages.
  47716. *
  47717. * @private
  47718. * @param {string} string - The code.
  47719. * @param {number} errorLine - The error line.
  47720. * @return {string} The formatted code.
  47721. */
  47722. _handleSource( string, errorLine ) {
  47723. const lines = string.split( '\n' );
  47724. const lines2 = [];
  47725. const from = Math.max( errorLine - 6, 0 );
  47726. const to = Math.min( errorLine + 6, lines.length );
  47727. for ( let i = from; i < to; i ++ ) {
  47728. const line = i + 1;
  47729. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  47730. }
  47731. return lines2.join( '\n' );
  47732. }
  47733. /**
  47734. * Gets the shader compilation errors from the info log.
  47735. *
  47736. * @private
  47737. * @param {WebGL2RenderingContext} gl - The rendering context.
  47738. * @param {WebGLShader} shader - The WebGL shader object.
  47739. * @param {string} type - The shader type.
  47740. * @return {string} The shader errors.
  47741. */
  47742. _getShaderErrors( gl, shader, type ) {
  47743. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  47744. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  47745. const errors = shaderInfoLog.trim();
  47746. if ( status && errors === '' ) return '';
  47747. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  47748. if ( errorMatches ) {
  47749. const errorLine = parseInt( errorMatches[ 1 ] );
  47750. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  47751. } else {
  47752. return errors;
  47753. }
  47754. }
  47755. /**
  47756. * Logs shader compilation errors.
  47757. *
  47758. * @private
  47759. * @param {WebGLProgram} programGPU - The WebGL program.
  47760. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  47761. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  47762. */
  47763. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  47764. if ( this.renderer.debug.checkShaderErrors ) {
  47765. const gl = this.gl;
  47766. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  47767. const programLog = programInfoLog.trim();
  47768. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47769. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  47770. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  47771. } else {
  47772. // default error reporting
  47773. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  47774. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  47775. error(
  47776. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47777. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  47778. 'Program Info Log: ' + programLog + '\n' +
  47779. vertexErrors + '\n' +
  47780. fragmentErrors
  47781. );
  47782. }
  47783. } else if ( programLog !== '' ) {
  47784. warn( 'WebGLProgram: Program Info Log:', programLog );
  47785. }
  47786. }
  47787. }
  47788. /**
  47789. * Completes the shader program setup for the given render object.
  47790. *
  47791. * @private
  47792. * @param {RenderObject} renderObject - The render object.
  47793. * @param {RenderPipeline} pipeline - The render pipeline.
  47794. */
  47795. _completeCompile( renderObject, pipeline ) {
  47796. const { state, gl } = this;
  47797. const pipelineData = this.get( pipeline );
  47798. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  47799. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47800. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47801. }
  47802. state.useProgram( programGPU );
  47803. // Bindings
  47804. const bindings = renderObject.getBindings();
  47805. this._setupBindings( bindings, programGPU );
  47806. //
  47807. this.set( pipeline, {
  47808. programGPU
  47809. } );
  47810. }
  47811. /**
  47812. * Creates a compute pipeline for the given compute node.
  47813. *
  47814. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47815. * @param {Array<BindGroup>} bindings - The bindings.
  47816. */
  47817. createComputePipeline( computePipeline, bindings ) {
  47818. const { state, gl } = this;
  47819. // Program
  47820. const fragmentProgram = {
  47821. stage: 'fragment',
  47822. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  47823. };
  47824. this.createProgram( fragmentProgram );
  47825. const { computeProgram } = computePipeline;
  47826. const programGPU = gl.createProgram();
  47827. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47828. const vertexShader = this.get( computeProgram ).shaderGPU;
  47829. const transforms = computeProgram.transforms;
  47830. const transformVaryingNames = [];
  47831. const transformAttributeNodes = [];
  47832. for ( let i = 0; i < transforms.length; i ++ ) {
  47833. const transform = transforms[ i ];
  47834. transformVaryingNames.push( transform.varyingName );
  47835. transformAttributeNodes.push( transform.attributeNode );
  47836. }
  47837. gl.attachShader( programGPU, fragmentShader );
  47838. gl.attachShader( programGPU, vertexShader );
  47839. gl.transformFeedbackVaryings(
  47840. programGPU,
  47841. transformVaryingNames,
  47842. gl.SEPARATE_ATTRIBS
  47843. );
  47844. gl.linkProgram( programGPU );
  47845. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47846. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47847. }
  47848. state.useProgram( programGPU );
  47849. // Bindings
  47850. this._setupBindings( bindings, programGPU );
  47851. const attributeNodes = computeProgram.attributes;
  47852. const attributes = [];
  47853. const transformBuffers = [];
  47854. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  47855. const attribute = attributeNodes[ i ].node.attribute;
  47856. attributes.push( attribute );
  47857. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47858. }
  47859. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  47860. const attribute = transformAttributeNodes[ i ].attribute;
  47861. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47862. const attributeData = this.get( attribute );
  47863. transformBuffers.push( attributeData );
  47864. }
  47865. //
  47866. this.set( computePipeline, {
  47867. programGPU,
  47868. transformBuffers,
  47869. attributes
  47870. } );
  47871. }
  47872. /**
  47873. * Creates bindings from the given bind group definition.
  47874. *
  47875. * @param {BindGroup} bindGroup - The bind group.
  47876. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47877. * @param {number} cacheIndex - The cache index.
  47878. * @param {number} version - The version.
  47879. */
  47880. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  47881. if ( this._knownBindings.has( bindings ) === false ) {
  47882. this._knownBindings.add( bindings );
  47883. let uniformBuffers = 0;
  47884. let textures = 0;
  47885. for ( const bindGroup of bindings ) {
  47886. this.set( bindGroup, {
  47887. textures: textures,
  47888. uniformBuffers: uniformBuffers
  47889. } );
  47890. for ( const binding of bindGroup.bindings ) {
  47891. if ( binding.isUniformBuffer ) uniformBuffers ++;
  47892. if ( binding.isSampledTexture ) textures ++;
  47893. }
  47894. }
  47895. }
  47896. this.updateBindings( bindGroup, bindings );
  47897. }
  47898. /**
  47899. * Updates the given bind group definition.
  47900. *
  47901. * @param {BindGroup} bindGroup - The bind group.
  47902. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47903. * @param {number} cacheIndex - The cache index.
  47904. * @param {number} version - The version.
  47905. */
  47906. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  47907. const { gl } = this;
  47908. const bindGroupData = this.get( bindGroup );
  47909. let i = bindGroupData.uniformBuffers;
  47910. let t = bindGroupData.textures;
  47911. for ( const binding of bindGroup.bindings ) {
  47912. const map = this.get( binding );
  47913. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47914. const data = binding.buffer;
  47915. let { bufferGPU } = this.get( data );
  47916. if ( bufferGPU === undefined ) {
  47917. // create
  47918. bufferGPU = gl.createBuffer();
  47919. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47920. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47921. this.set( data, { bufferGPU } );
  47922. } else {
  47923. // update
  47924. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47925. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  47926. }
  47927. map.index = i ++;
  47928. map.bufferGPU = bufferGPU;
  47929. this.set( binding, map );
  47930. } else if ( binding.isSampledTexture ) {
  47931. const { textureGPU, glTextureType } = this.get( binding.texture );
  47932. map.index = t ++;
  47933. map.textureGPU = textureGPU;
  47934. map.glTextureType = glTextureType;
  47935. this.set( binding, map );
  47936. }
  47937. }
  47938. }
  47939. /**
  47940. * Updates a buffer binding.
  47941. *
  47942. * @param {Buffer} binding - The buffer binding to update.
  47943. */
  47944. updateBinding( binding ) {
  47945. const gl = this.gl;
  47946. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47947. const bindingData = this.get( binding );
  47948. const bufferGPU = bindingData.bufferGPU;
  47949. const data = binding.buffer;
  47950. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47951. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47952. }
  47953. }
  47954. // attributes
  47955. /**
  47956. * Creates the GPU buffer of an indexed shader attribute.
  47957. *
  47958. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47959. */
  47960. createIndexAttribute( attribute ) {
  47961. const gl = this.gl;
  47962. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  47963. }
  47964. /**
  47965. * Creates the GPU buffer of a shader attribute.
  47966. *
  47967. * @param {BufferAttribute} attribute - The buffer attribute.
  47968. */
  47969. createAttribute( attribute ) {
  47970. if ( this.has( attribute ) ) return;
  47971. const gl = this.gl;
  47972. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47973. }
  47974. /**
  47975. * Creates the GPU buffer of a storage attribute.
  47976. *
  47977. * @param {BufferAttribute} attribute - The buffer attribute.
  47978. */
  47979. createStorageAttribute( attribute ) {
  47980. if ( this.has( attribute ) ) return;
  47981. const gl = this.gl;
  47982. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47983. }
  47984. /**
  47985. * Updates the GPU buffer of a shader attribute.
  47986. *
  47987. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47988. */
  47989. updateAttribute( attribute ) {
  47990. this.attributeUtils.updateAttribute( attribute );
  47991. }
  47992. /**
  47993. * Destroys the GPU buffer of a shader attribute.
  47994. *
  47995. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47996. */
  47997. destroyAttribute( attribute ) {
  47998. this.attributeUtils.destroyAttribute( attribute );
  47999. }
  48000. /**
  48001. * Checks if the given feature is supported by the backend.
  48002. *
  48003. * @param {string} name - The feature's name.
  48004. * @return {boolean} Whether the feature is supported or not.
  48005. */
  48006. hasFeature( name ) {
  48007. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  48008. const extensions = this.extensions;
  48009. for ( let i = 0; i < keysMatching.length; i ++ ) {
  48010. if ( extensions.has( keysMatching[ i ] ) ) return true;
  48011. }
  48012. return false;
  48013. }
  48014. /**
  48015. * Returns the maximum anisotropy texture filtering value.
  48016. *
  48017. * @return {number} The maximum anisotropy texture filtering value.
  48018. */
  48019. getMaxAnisotropy() {
  48020. return this.capabilities.getMaxAnisotropy();
  48021. }
  48022. /**
  48023. * Copies data of the given source texture to the given destination texture.
  48024. *
  48025. * @param {Texture} srcTexture - The source texture.
  48026. * @param {Texture} dstTexture - The destination texture.
  48027. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48028. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48029. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48030. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48031. */
  48032. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48033. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  48034. }
  48035. /**
  48036. * Copies the current bound framebuffer to the given texture.
  48037. *
  48038. * @param {Texture} texture - The destination texture.
  48039. * @param {RenderContext} renderContext - The render context.
  48040. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48041. */
  48042. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48043. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  48044. }
  48045. /**
  48046. * Configures the active framebuffer from the given render context.
  48047. *
  48048. * @private
  48049. * @param {RenderContext} descriptor - The render context.
  48050. */
  48051. _setFramebuffer( descriptor ) {
  48052. const { gl, state } = this;
  48053. let currentFrameBuffer = null;
  48054. if ( descriptor.textures !== null ) {
  48055. const renderTarget = descriptor.renderTarget;
  48056. const renderTargetContextData = this.get( renderTarget );
  48057. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  48058. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  48059. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  48060. const isRenderTargetArray = renderTarget.depth > 1;
  48061. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  48062. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  48063. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  48064. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  48065. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48066. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  48067. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  48068. const cacheKey = getCacheKey( descriptor );
  48069. let fb;
  48070. if ( isCube ) {
  48071. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  48072. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  48073. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  48074. fb = this._xrFramebuffer;
  48075. } else {
  48076. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  48077. fb = renderTargetContextData.framebuffers[ cacheKey ];
  48078. }
  48079. if ( fb === undefined ) {
  48080. fb = gl.createFramebuffer();
  48081. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48082. const textures = descriptor.textures;
  48083. const depthInvalidationArray = [];
  48084. if ( isCube ) {
  48085. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  48086. const { textureGPU } = this.get( textures[ 0 ] );
  48087. const cubeFace = this.renderer._activeCubeFace;
  48088. const mipLevel = this.renderer._activeMipmapLevel;
  48089. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  48090. } else {
  48091. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  48092. for ( let i = 0; i < textures.length; i ++ ) {
  48093. const texture = textures[ i ];
  48094. const textureData = this.get( texture );
  48095. textureData.renderTarget = descriptor.renderTarget;
  48096. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48097. const attachment = gl.COLOR_ATTACHMENT0 + i;
  48098. if ( renderTarget.multiview ) {
  48099. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  48100. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  48101. const layer = this.renderer._activeCubeFace;
  48102. const mipLevel = this.renderer._activeMipmapLevel;
  48103. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  48104. } else {
  48105. if ( useMultisampledRTT ) {
  48106. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48107. } else {
  48108. const mipLevel = this.renderer._activeMipmapLevel;
  48109. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  48110. }
  48111. }
  48112. }
  48113. }
  48114. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48115. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48116. const renderbuffer = gl.createRenderbuffer();
  48117. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  48118. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  48119. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48120. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48121. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48122. } else {
  48123. if ( descriptor.depthTexture !== null ) {
  48124. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48125. const textureData = this.get( descriptor.depthTexture );
  48126. textureData.renderTarget = descriptor.renderTarget;
  48127. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48128. if ( renderTarget.multiview ) {
  48129. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48130. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  48131. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48132. } else {
  48133. if ( descriptor.depthTexture.isArrayTexture ) {
  48134. const layer = this.renderer._activeCubeFace;
  48135. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  48136. } else {
  48137. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48138. }
  48139. }
  48140. }
  48141. }
  48142. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  48143. } else {
  48144. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  48145. if ( isRenderCameraDepthArray ) {
  48146. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48147. const layer = this.renderer._activeCubeFace;
  48148. const depthData = this.get( descriptor.depthTexture );
  48149. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48150. gl.framebufferTextureLayer(
  48151. gl.FRAMEBUFFER,
  48152. depthStyle,
  48153. depthData.textureGPU,
  48154. 0,
  48155. layer
  48156. );
  48157. }
  48158. // rebind external XR textures
  48159. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  48160. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48161. // rebind color
  48162. const textureData = this.get( descriptor.textures[ 0 ] );
  48163. if ( renderTarget.multiview ) {
  48164. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  48165. } else if ( useMultisampledRTT ) {
  48166. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48167. } else {
  48168. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48169. }
  48170. // rebind depth
  48171. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48172. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48173. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  48174. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48175. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48176. } else {
  48177. const textureData = this.get( descriptor.depthTexture );
  48178. if ( renderTarget.multiview ) {
  48179. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48180. } else if ( useMultisampledRTT ) {
  48181. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48182. } else {
  48183. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48184. }
  48185. }
  48186. }
  48187. }
  48188. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  48189. if ( msaaFb === undefined ) {
  48190. const invalidationArray = [];
  48191. msaaFb = gl.createFramebuffer();
  48192. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  48193. const msaaRenderbuffers = [];
  48194. const textures = descriptor.textures;
  48195. for ( let i = 0; i < textures.length; i ++ ) {
  48196. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  48197. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48198. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  48199. const texture = descriptor.textures[ i ];
  48200. const textureData = this.get( texture );
  48201. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  48202. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48203. }
  48204. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48205. renderTargetContextData.msaaFrameBuffer = msaaFb;
  48206. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  48207. if ( depthBuffer && depthRenderbuffer === undefined ) {
  48208. depthRenderbuffer = gl.createRenderbuffer();
  48209. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  48210. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  48211. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48212. invalidationArray.push( depthStyle );
  48213. }
  48214. renderTargetContextData.invalidationArray = invalidationArray;
  48215. }
  48216. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48217. } else {
  48218. currentFrameBuffer = fb;
  48219. }
  48220. state.drawBuffers( descriptor, fb );
  48221. }
  48222. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  48223. }
  48224. /**
  48225. * Computes the VAO key for the given index and attributes.
  48226. *
  48227. * @private
  48228. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48229. * @return {string} The VAO key.
  48230. */
  48231. _getVaoKey( attributes ) {
  48232. let key = '';
  48233. for ( let i = 0; i < attributes.length; i ++ ) {
  48234. const attributeData = this.get( attributes[ i ] );
  48235. key += ':' + attributeData.id;
  48236. }
  48237. return key;
  48238. }
  48239. /**
  48240. * Creates a VAO from the index and attributes.
  48241. *
  48242. * @private
  48243. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48244. * @return {Object} The VAO data.
  48245. */
  48246. _createVao( attributes ) {
  48247. const { gl } = this;
  48248. const vaoGPU = gl.createVertexArray();
  48249. gl.bindVertexArray( vaoGPU );
  48250. for ( let i = 0; i < attributes.length; i ++ ) {
  48251. const attribute = attributes[ i ];
  48252. const attributeData = this.get( attribute );
  48253. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  48254. gl.enableVertexAttribArray( i );
  48255. let stride, offset;
  48256. if ( attribute.isInterleavedBufferAttribute === true ) {
  48257. stride = attribute.data.stride * attributeData.bytesPerElement;
  48258. offset = attribute.offset * attributeData.bytesPerElement;
  48259. } else {
  48260. stride = 0;
  48261. offset = 0;
  48262. }
  48263. if ( attributeData.isInteger ) {
  48264. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  48265. } else {
  48266. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  48267. }
  48268. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  48269. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  48270. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  48271. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  48272. }
  48273. }
  48274. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  48275. return vaoGPU;
  48276. }
  48277. /**
  48278. * Creates a transform feedback from the given transform buffers.
  48279. *
  48280. * @private
  48281. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  48282. * @return {WebGLTransformFeedback} The transform feedback.
  48283. */
  48284. _getTransformFeedback( transformBuffers ) {
  48285. let key = '';
  48286. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48287. key += ':' + transformBuffers[ i ].id;
  48288. }
  48289. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  48290. if ( transformFeedbackGPU !== undefined ) {
  48291. return transformFeedbackGPU;
  48292. }
  48293. const { gl } = this;
  48294. transformFeedbackGPU = gl.createTransformFeedback();
  48295. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48296. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48297. const attributeData = transformBuffers[ i ];
  48298. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  48299. }
  48300. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48301. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  48302. return transformFeedbackGPU;
  48303. }
  48304. /**
  48305. * Setups the given bindings.
  48306. *
  48307. * @private
  48308. * @param {Array<BindGroup>} bindings - The bindings.
  48309. * @param {WebGLProgram} programGPU - The WebGL program.
  48310. */
  48311. _setupBindings( bindings, programGPU ) {
  48312. const gl = this.gl;
  48313. for ( const bindGroup of bindings ) {
  48314. for ( const binding of bindGroup.bindings ) {
  48315. const bindingData = this.get( binding );
  48316. const index = bindingData.index;
  48317. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48318. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  48319. gl.uniformBlockBinding( programGPU, location, index );
  48320. } else if ( binding.isSampledTexture ) {
  48321. const location = gl.getUniformLocation( programGPU, binding.name );
  48322. gl.uniform1i( location, index );
  48323. }
  48324. }
  48325. }
  48326. }
  48327. /**
  48328. * Binds the given uniforms.
  48329. *
  48330. * @private
  48331. * @param {Array<BindGroup>} bindings - The bindings.
  48332. */
  48333. _bindUniforms( bindings ) {
  48334. const { gl, state } = this;
  48335. for ( const bindGroup of bindings ) {
  48336. for ( const binding of bindGroup.bindings ) {
  48337. const bindingData = this.get( binding );
  48338. const index = bindingData.index;
  48339. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48340. // TODO USE bindBufferRange to group multiple uniform buffers
  48341. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  48342. } else if ( binding.isSampledTexture ) {
  48343. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  48344. }
  48345. }
  48346. }
  48347. }
  48348. /**
  48349. * The method ensures multisampled render targets are resolved.
  48350. *
  48351. * @private
  48352. * @param {RenderContext} renderContext - The render context.
  48353. */
  48354. _resolveRenderTarget( renderContext ) {
  48355. const { gl, state } = this;
  48356. const renderTarget = renderContext.renderTarget;
  48357. if ( renderContext.textures !== null && renderTarget ) {
  48358. const renderTargetContextData = this.get( renderTarget );
  48359. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  48360. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48361. let mask = gl.COLOR_BUFFER_BIT;
  48362. if ( renderTarget.resolveDepthBuffer ) {
  48363. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  48364. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  48365. }
  48366. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48367. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  48368. const textures = renderContext.textures;
  48369. const isMRT = textures.length > 1;
  48370. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48371. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48372. if ( isMRT ) {
  48373. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  48374. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  48375. for ( let i = 0; i < textures.length; i ++ ) {
  48376. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  48377. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  48378. }
  48379. }
  48380. for ( let i = 0; i < textures.length; i ++ ) {
  48381. if ( isMRT ) {
  48382. // configure attachment for resolve
  48383. const { textureGPU } = this.get( textures[ i ] );
  48384. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48385. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  48386. }
  48387. if ( renderContext.scissor ) {
  48388. const { x, y, width, height } = renderContext.scissorValue;
  48389. const viewY = renderContext.height - height - y;
  48390. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  48391. } else {
  48392. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  48393. }
  48394. }
  48395. if ( isMRT ) {
  48396. // restore attachments
  48397. for ( let i = 0; i < textures.length; i ++ ) {
  48398. const { textureGPU } = this.get( textures[ i ] );
  48399. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48400. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  48401. }
  48402. }
  48403. if ( this._supportsInvalidateFramebuffer === true ) {
  48404. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  48405. }
  48406. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  48407. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48408. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48409. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  48410. }
  48411. }
  48412. }
  48413. /**
  48414. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  48415. * should be used when MSAA is enabled.
  48416. *
  48417. * @private
  48418. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  48419. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  48420. */
  48421. _useMultisampledExtension( renderTarget ) {
  48422. if ( renderTarget.multiview === true ) {
  48423. return true;
  48424. }
  48425. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  48426. }
  48427. /**
  48428. * Frees internal resources.
  48429. */
  48430. dispose() {
  48431. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  48432. const extension = this.extensions.get( 'WEBGL_lose_context' );
  48433. if ( extension ) extension.loseContext();
  48434. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  48435. }
  48436. }
  48437. const GPUPrimitiveTopology = {
  48438. PointList: 'point-list',
  48439. LineList: 'line-list',
  48440. LineStrip: 'line-strip',
  48441. TriangleList: 'triangle-list',
  48442. TriangleStrip: 'triangle-strip',
  48443. };
  48444. const GPUCompareFunction = {
  48445. Never: 'never',
  48446. Less: 'less',
  48447. Equal: 'equal',
  48448. LessEqual: 'less-equal',
  48449. Greater: 'greater',
  48450. NotEqual: 'not-equal',
  48451. GreaterEqual: 'greater-equal',
  48452. Always: 'always'
  48453. };
  48454. const GPUStoreOp = {
  48455. Store: 'store'};
  48456. const GPULoadOp = {
  48457. Load: 'load',
  48458. Clear: 'clear'
  48459. };
  48460. const GPUFrontFace = {
  48461. CCW: 'ccw',
  48462. CW: 'cw'
  48463. };
  48464. const GPUCullMode = {
  48465. None: 'none',
  48466. Back: 'back'
  48467. };
  48468. const GPUIndexFormat = {
  48469. Uint16: 'uint16',
  48470. Uint32: 'uint32'
  48471. };
  48472. const GPUTextureFormat = {
  48473. // 8-bit formats
  48474. R8Unorm: 'r8unorm',
  48475. R8Snorm: 'r8snorm',
  48476. R8Uint: 'r8uint',
  48477. R8Sint: 'r8sint',
  48478. // 16-bit formats
  48479. R16Uint: 'r16uint',
  48480. R16Sint: 'r16sint',
  48481. R16Float: 'r16float',
  48482. RG8Unorm: 'rg8unorm',
  48483. RG8Snorm: 'rg8snorm',
  48484. RG8Uint: 'rg8uint',
  48485. RG8Sint: 'rg8sint',
  48486. // 32-bit formats
  48487. R32Uint: 'r32uint',
  48488. R32Sint: 'r32sint',
  48489. R32Float: 'r32float',
  48490. RG16Uint: 'rg16uint',
  48491. RG16Sint: 'rg16sint',
  48492. RG16Float: 'rg16float',
  48493. RGBA8Unorm: 'rgba8unorm',
  48494. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  48495. RGBA8Snorm: 'rgba8snorm',
  48496. RGBA8Uint: 'rgba8uint',
  48497. RGBA8Sint: 'rgba8sint',
  48498. BGRA8Unorm: 'bgra8unorm',
  48499. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  48500. // Packed 32-bit formats
  48501. RGB9E5UFloat: 'rgb9e5ufloat',
  48502. RGB10A2Unorm: 'rgb10a2unorm',
  48503. RG11B10UFloat: 'rg11b10ufloat',
  48504. // 64-bit formats
  48505. RG32Uint: 'rg32uint',
  48506. RG32Sint: 'rg32sint',
  48507. RG32Float: 'rg32float',
  48508. RGBA16Uint: 'rgba16uint',
  48509. RGBA16Sint: 'rgba16sint',
  48510. RGBA16Float: 'rgba16float',
  48511. // 128-bit formats
  48512. RGBA32Uint: 'rgba32uint',
  48513. RGBA32Sint: 'rgba32sint',
  48514. RGBA32Float: 'rgba32float',
  48515. Depth16Unorm: 'depth16unorm',
  48516. Depth24Plus: 'depth24plus',
  48517. Depth24PlusStencil8: 'depth24plus-stencil8',
  48518. Depth32Float: 'depth32float',
  48519. // 'depth32float-stencil8' extension
  48520. Depth32FloatStencil8: 'depth32float-stencil8',
  48521. // BC compressed formats usable if 'texture-compression-bc' is both
  48522. // supported by the device/user agent and enabled in requestDevice.
  48523. BC1RGBAUnorm: 'bc1-rgba-unorm',
  48524. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  48525. BC2RGBAUnorm: 'bc2-rgba-unorm',
  48526. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  48527. BC3RGBAUnorm: 'bc3-rgba-unorm',
  48528. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  48529. BC4RUnorm: 'bc4-r-unorm',
  48530. BC4RSnorm: 'bc4-r-snorm',
  48531. BC5RGUnorm: 'bc5-rg-unorm',
  48532. BC5RGSnorm: 'bc5-rg-snorm',
  48533. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  48534. BC6HRGBFloat: 'bc6h-rgb-float',
  48535. BC7RGBAUnorm: 'bc7-rgba-unorm',
  48536. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  48537. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  48538. // supported by the device/user agent and enabled in requestDevice.
  48539. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  48540. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  48541. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  48542. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  48543. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  48544. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  48545. EACR11Unorm: 'eac-r11unorm',
  48546. EACR11Snorm: 'eac-r11snorm',
  48547. EACRG11Unorm: 'eac-rg11unorm',
  48548. EACRG11Snorm: 'eac-rg11snorm',
  48549. // ASTC compressed formats usable if 'texture-compression-astc' is both
  48550. // supported by the device/user agent and enabled in requestDevice.
  48551. ASTC4x4Unorm: 'astc-4x4-unorm',
  48552. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  48553. ASTC5x4Unorm: 'astc-5x4-unorm',
  48554. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  48555. ASTC5x5Unorm: 'astc-5x5-unorm',
  48556. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  48557. ASTC6x5Unorm: 'astc-6x5-unorm',
  48558. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  48559. ASTC6x6Unorm: 'astc-6x6-unorm',
  48560. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  48561. ASTC8x5Unorm: 'astc-8x5-unorm',
  48562. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  48563. ASTC8x6Unorm: 'astc-8x6-unorm',
  48564. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  48565. ASTC8x8Unorm: 'astc-8x8-unorm',
  48566. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  48567. ASTC10x5Unorm: 'astc-10x5-unorm',
  48568. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  48569. ASTC10x6Unorm: 'astc-10x6-unorm',
  48570. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  48571. ASTC10x8Unorm: 'astc-10x8-unorm',
  48572. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  48573. ASTC10x10Unorm: 'astc-10x10-unorm',
  48574. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  48575. ASTC12x10Unorm: 'astc-12x10-unorm',
  48576. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  48577. ASTC12x12Unorm: 'astc-12x12-unorm',
  48578. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  48579. };
  48580. const GPUAddressMode = {
  48581. ClampToEdge: 'clamp-to-edge',
  48582. Repeat: 'repeat',
  48583. MirrorRepeat: 'mirror-repeat'
  48584. };
  48585. const GPUFilterMode = {
  48586. Linear: 'linear',
  48587. Nearest: 'nearest'
  48588. };
  48589. const GPUBlendFactor = {
  48590. Zero: 'zero',
  48591. One: 'one',
  48592. Src: 'src',
  48593. OneMinusSrc: 'one-minus-src',
  48594. SrcAlpha: 'src-alpha',
  48595. OneMinusSrcAlpha: 'one-minus-src-alpha',
  48596. Dst: 'dst',
  48597. OneMinusDst: 'one-minus-dst',
  48598. DstAlpha: 'dst-alpha',
  48599. OneMinusDstAlpha: 'one-minus-dst-alpha',
  48600. SrcAlphaSaturated: 'src-alpha-saturated',
  48601. Constant: 'constant',
  48602. OneMinusConstant: 'one-minus-constant'
  48603. };
  48604. const GPUBlendOperation = {
  48605. Add: 'add',
  48606. Subtract: 'subtract',
  48607. ReverseSubtract: 'reverse-subtract',
  48608. Min: 'min',
  48609. Max: 'max'
  48610. };
  48611. const GPUColorWriteFlags = {
  48612. None: 0,
  48613. All: 0xF
  48614. };
  48615. const GPUStencilOperation = {
  48616. Keep: 'keep',
  48617. Zero: 'zero',
  48618. Replace: 'replace',
  48619. Invert: 'invert',
  48620. IncrementClamp: 'increment-clamp',
  48621. DecrementClamp: 'decrement-clamp',
  48622. IncrementWrap: 'increment-wrap',
  48623. DecrementWrap: 'decrement-wrap'
  48624. };
  48625. const GPUBufferBindingType = {
  48626. Storage: 'storage',
  48627. ReadOnlyStorage: 'read-only-storage'
  48628. };
  48629. const GPUStorageTextureAccess = {
  48630. WriteOnly: 'write-only',
  48631. ReadOnly: 'read-only',
  48632. ReadWrite: 'read-write',
  48633. };
  48634. const GPUSamplerBindingType = {
  48635. NonFiltering: 'non-filtering',
  48636. Comparison: 'comparison'
  48637. };
  48638. const GPUTextureSampleType = {
  48639. Float: 'float',
  48640. UnfilterableFloat: 'unfilterable-float',
  48641. Depth: 'depth',
  48642. SInt: 'sint',
  48643. UInt: 'uint'
  48644. };
  48645. const GPUTextureDimension = {
  48646. TwoD: '2d',
  48647. ThreeD: '3d'
  48648. };
  48649. const GPUTextureViewDimension = {
  48650. TwoD: '2d',
  48651. TwoDArray: '2d-array',
  48652. Cube: 'cube',
  48653. ThreeD: '3d'
  48654. };
  48655. const GPUTextureAspect = {
  48656. All: 'all'};
  48657. const GPUInputStepMode = {
  48658. Vertex: 'vertex',
  48659. Instance: 'instance'
  48660. };
  48661. const GPUFeatureName = {
  48662. CoreFeaturesAndLimits: 'core-features-and-limits',
  48663. DepthClipControl: 'depth-clip-control',
  48664. Depth32FloatStencil8: 'depth32float-stencil8',
  48665. TextureCompressionBC: 'texture-compression-bc',
  48666. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  48667. TextureCompressionETC2: 'texture-compression-etc2',
  48668. TextureCompressionASTC: 'texture-compression-astc',
  48669. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  48670. TimestampQuery: 'timestamp-query',
  48671. IndirectFirstInstance: 'indirect-first-instance',
  48672. ShaderF16: 'shader-f16',
  48673. RG11B10UFloat: 'rg11b10ufloat-renderable',
  48674. BGRA8UNormStorage: 'bgra8unorm-storage',
  48675. Float32Filterable: 'float32-filterable',
  48676. Float32Blendable: 'float32-blendable',
  48677. ClipDistances: 'clip-distances',
  48678. DualSourceBlending: 'dual-source-blending',
  48679. Subgroups: 'subgroups',
  48680. TextureFormatsTier1: 'texture-formats-tier1',
  48681. TextureFormatsTier2: 'texture-formats-tier2'
  48682. };
  48683. const GPUFeatureMap = {
  48684. 'texture-compression-s3tc': 'texture-compression-bc',
  48685. 'texture-compression-etc1': 'texture-compression-etc2'
  48686. };
  48687. /**
  48688. * A special form of sampler binding type.
  48689. * It's texture value is managed by a node object.
  48690. *
  48691. * @private
  48692. * @augments Sampler
  48693. */
  48694. class NodeSampler extends Sampler {
  48695. /**
  48696. * Constructs a new node-based sampler.
  48697. *
  48698. * @param {string} name - The samplers's name.
  48699. * @param {TextureNode} textureNode - The texture node.
  48700. * @param {UniformGroupNode} groupNode - The uniform group node.
  48701. */
  48702. constructor( name, textureNode, groupNode ) {
  48703. super( name, textureNode ? textureNode.value : null );
  48704. /**
  48705. * The texture node.
  48706. *
  48707. * @type {TextureNode}
  48708. */
  48709. this.textureNode = textureNode;
  48710. /**
  48711. * The uniform group node.
  48712. *
  48713. * @type {UniformGroupNode}
  48714. */
  48715. this.groupNode = groupNode;
  48716. }
  48717. /**
  48718. * Updates the texture value of this sampler.
  48719. *
  48720. * @return {boolean} Whether the sampler needs an update or not.
  48721. */
  48722. update() {
  48723. const { textureNode } = this;
  48724. if ( this.texture !== textureNode.value ) {
  48725. this.texture = textureNode.value;
  48726. return true;
  48727. }
  48728. return super.update();
  48729. }
  48730. }
  48731. /**
  48732. * Represents a storage buffer binding type.
  48733. *
  48734. * @private
  48735. * @augments Buffer
  48736. */
  48737. class StorageBuffer extends Buffer {
  48738. /**
  48739. * Constructs a new uniform buffer.
  48740. *
  48741. * @param {string} name - The buffer's name.
  48742. * @param {BufferAttribute} attribute - The buffer attribute.
  48743. */
  48744. constructor( name, attribute ) {
  48745. super( name, attribute ? attribute.array : null );
  48746. /**
  48747. * This flag can be used for type testing.
  48748. *
  48749. * @type {BufferAttribute}
  48750. */
  48751. this.attribute = attribute;
  48752. /**
  48753. * This flag can be used for type testing.
  48754. *
  48755. * @type {boolean}
  48756. * @readonly
  48757. * @default true
  48758. */
  48759. this.isStorageBuffer = true;
  48760. }
  48761. }
  48762. let _id = 0;
  48763. /**
  48764. * A special form of storage buffer binding type.
  48765. * It's buffer value is managed by a node object.
  48766. *
  48767. * @private
  48768. * @augments StorageBuffer
  48769. */
  48770. class NodeStorageBuffer extends StorageBuffer {
  48771. /**
  48772. * Constructs a new node-based storage buffer.
  48773. *
  48774. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  48775. * @param {UniformGroupNode} groupNode - The uniform group node.
  48776. */
  48777. constructor( nodeUniform, groupNode ) {
  48778. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  48779. /**
  48780. * The node uniform.
  48781. *
  48782. * @type {StorageBufferNode}
  48783. */
  48784. this.nodeUniform = nodeUniform;
  48785. /**
  48786. * The access type.
  48787. *
  48788. * @type {string}
  48789. */
  48790. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  48791. /**
  48792. * The uniform group node.
  48793. *
  48794. * @type {UniformGroupNode}
  48795. */
  48796. this.groupNode = groupNode;
  48797. }
  48798. /**
  48799. * The storage buffer.
  48800. *
  48801. * @type {BufferAttribute}
  48802. */
  48803. get buffer() {
  48804. return this.nodeUniform.value;
  48805. }
  48806. }
  48807. /**
  48808. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  48809. *
  48810. * @private
  48811. */
  48812. class WebGPUTexturePassUtils extends DataMap {
  48813. /**
  48814. * Constructs a new utility object.
  48815. *
  48816. * @param {GPUDevice} device - The WebGPU device.
  48817. */
  48818. constructor( device ) {
  48819. super();
  48820. /**
  48821. * The WebGPU device.
  48822. *
  48823. * @type {GPUDevice}
  48824. */
  48825. this.device = device;
  48826. const mipmapVertexSource = `
  48827. struct VarysStruct {
  48828. @builtin( position ) Position: vec4<f32>,
  48829. @location( 0 ) vTex : vec2<f32>
  48830. };
  48831. @vertex
  48832. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  48833. var Varys : VarysStruct;
  48834. var pos = array< vec2<f32>, 4 >(
  48835. vec2<f32>( -1.0, 1.0 ),
  48836. vec2<f32>( 1.0, 1.0 ),
  48837. vec2<f32>( -1.0, -1.0 ),
  48838. vec2<f32>( 1.0, -1.0 )
  48839. );
  48840. var tex = array< vec2<f32>, 4 >(
  48841. vec2<f32>( 0.0, 0.0 ),
  48842. vec2<f32>( 1.0, 0.0 ),
  48843. vec2<f32>( 0.0, 1.0 ),
  48844. vec2<f32>( 1.0, 1.0 )
  48845. );
  48846. Varys.vTex = tex[ vertexIndex ];
  48847. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  48848. return Varys;
  48849. }
  48850. `;
  48851. const mipmapFragmentSource = `
  48852. @group( 0 ) @binding( 0 )
  48853. var imgSampler : sampler;
  48854. @group( 0 ) @binding( 1 )
  48855. var img : texture_2d<f32>;
  48856. @fragment
  48857. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48858. return textureSample( img, imgSampler, vTex );
  48859. }
  48860. `;
  48861. const flipYFragmentSource = `
  48862. @group( 0 ) @binding( 0 )
  48863. var imgSampler : sampler;
  48864. @group( 0 ) @binding( 1 )
  48865. var img : texture_2d<f32>;
  48866. @fragment
  48867. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48868. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  48869. }
  48870. `;
  48871. /**
  48872. * The mipmap GPU sampler.
  48873. *
  48874. * @type {GPUSampler}
  48875. */
  48876. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  48877. /**
  48878. * The flipY GPU sampler.
  48879. *
  48880. * @type {GPUSampler}
  48881. */
  48882. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  48883. /**
  48884. * A cache for GPU render pipelines used for copy/transfer passes.
  48885. * Every texture format requires a unique pipeline.
  48886. *
  48887. * @type {Object<string,GPURenderPipeline>}
  48888. */
  48889. this.transferPipelines = {};
  48890. /**
  48891. * A cache for GPU render pipelines used for flipY passes.
  48892. * Every texture format requires a unique pipeline.
  48893. *
  48894. * @type {Object<string,GPURenderPipeline>}
  48895. */
  48896. this.flipYPipelines = {};
  48897. /**
  48898. * The mipmap vertex shader module.
  48899. *
  48900. * @type {GPUShaderModule}
  48901. */
  48902. this.mipmapVertexShaderModule = device.createShaderModule( {
  48903. label: 'mipmapVertex',
  48904. code: mipmapVertexSource
  48905. } );
  48906. /**
  48907. * The mipmap fragment shader module.
  48908. *
  48909. * @type {GPUShaderModule}
  48910. */
  48911. this.mipmapFragmentShaderModule = device.createShaderModule( {
  48912. label: 'mipmapFragment',
  48913. code: mipmapFragmentSource
  48914. } );
  48915. /**
  48916. * The flipY fragment shader module.
  48917. *
  48918. * @type {GPUShaderModule}
  48919. */
  48920. this.flipYFragmentShaderModule = device.createShaderModule( {
  48921. label: 'flipYFragment',
  48922. code: flipYFragmentSource
  48923. } );
  48924. }
  48925. /**
  48926. * Returns a render pipeline for the internal copy render pass. The pass
  48927. * requires a unique render pipeline for each texture format.
  48928. *
  48929. * @param {string} format - The GPU texture format
  48930. * @return {GPURenderPipeline} The GPU render pipeline.
  48931. */
  48932. getTransferPipeline( format ) {
  48933. let pipeline = this.transferPipelines[ format ];
  48934. if ( pipeline === undefined ) {
  48935. pipeline = this.device.createRenderPipeline( {
  48936. label: `mipmap-${ format }`,
  48937. vertex: {
  48938. module: this.mipmapVertexShaderModule,
  48939. entryPoint: 'main'
  48940. },
  48941. fragment: {
  48942. module: this.mipmapFragmentShaderModule,
  48943. entryPoint: 'main',
  48944. targets: [ { format } ]
  48945. },
  48946. primitive: {
  48947. topology: GPUPrimitiveTopology.TriangleStrip,
  48948. stripIndexFormat: GPUIndexFormat.Uint32
  48949. },
  48950. layout: 'auto'
  48951. } );
  48952. this.transferPipelines[ format ] = pipeline;
  48953. }
  48954. return pipeline;
  48955. }
  48956. /**
  48957. * Returns a render pipeline for the flipY render pass. The pass
  48958. * requires a unique render pipeline for each texture format.
  48959. *
  48960. * @param {string} format - The GPU texture format
  48961. * @return {GPURenderPipeline} The GPU render pipeline.
  48962. */
  48963. getFlipYPipeline( format ) {
  48964. let pipeline = this.flipYPipelines[ format ];
  48965. if ( pipeline === undefined ) {
  48966. pipeline = this.device.createRenderPipeline( {
  48967. label: `flipY-${ format }`,
  48968. vertex: {
  48969. module: this.mipmapVertexShaderModule,
  48970. entryPoint: 'main'
  48971. },
  48972. fragment: {
  48973. module: this.flipYFragmentShaderModule,
  48974. entryPoint: 'main',
  48975. targets: [ { format } ]
  48976. },
  48977. primitive: {
  48978. topology: GPUPrimitiveTopology.TriangleStrip,
  48979. stripIndexFormat: GPUIndexFormat.Uint32
  48980. },
  48981. layout: 'auto'
  48982. } );
  48983. this.flipYPipelines[ format ] = pipeline;
  48984. }
  48985. return pipeline;
  48986. }
  48987. /**
  48988. * Flip the contents of the given GPU texture along its vertical axis.
  48989. *
  48990. * @param {GPUTexture} textureGPU - The GPU texture object.
  48991. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48992. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48993. */
  48994. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  48995. const format = textureGPUDescriptor.format;
  48996. const { width, height } = textureGPUDescriptor.size;
  48997. const transferPipeline = this.getTransferPipeline( format );
  48998. const flipYPipeline = this.getFlipYPipeline( format );
  48999. const tempTexture = this.device.createTexture( {
  49000. size: { width, height, depthOrArrayLayers: 1 },
  49001. format,
  49002. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  49003. } );
  49004. const srcView = textureGPU.createView( {
  49005. baseMipLevel: 0,
  49006. mipLevelCount: 1,
  49007. dimension: GPUTextureViewDimension.TwoD,
  49008. baseArrayLayer
  49009. } );
  49010. const dstView = tempTexture.createView( {
  49011. baseMipLevel: 0,
  49012. mipLevelCount: 1,
  49013. dimension: GPUTextureViewDimension.TwoD,
  49014. baseArrayLayer: 0
  49015. } );
  49016. const commandEncoder = this.device.createCommandEncoder( {} );
  49017. const pass = ( pipeline, sourceView, destinationView ) => {
  49018. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49019. const bindGroup = this.device.createBindGroup( {
  49020. layout: bindGroupLayout,
  49021. entries: [ {
  49022. binding: 0,
  49023. resource: this.flipYSampler
  49024. }, {
  49025. binding: 1,
  49026. resource: sourceView
  49027. } ]
  49028. } );
  49029. const passEncoder = commandEncoder.beginRenderPass( {
  49030. colorAttachments: [ {
  49031. view: destinationView,
  49032. loadOp: GPULoadOp.Clear,
  49033. storeOp: GPUStoreOp.Store,
  49034. clearValue: [ 0, 0, 0, 0 ]
  49035. } ]
  49036. } );
  49037. passEncoder.setPipeline( pipeline );
  49038. passEncoder.setBindGroup( 0, bindGroup );
  49039. passEncoder.draw( 4, 1, 0, 0 );
  49040. passEncoder.end();
  49041. };
  49042. pass( transferPipeline, srcView, dstView );
  49043. pass( flipYPipeline, dstView, srcView );
  49044. this.device.queue.submit( [ commandEncoder.finish() ] );
  49045. tempTexture.destroy();
  49046. }
  49047. /**
  49048. * Generates mipmaps for the given GPU texture.
  49049. *
  49050. * @param {GPUTexture} textureGPU - The GPU texture object.
  49051. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49052. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49053. */
  49054. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  49055. const textureData = this.get( textureGPU );
  49056. if ( textureData.useCount === undefined ) {
  49057. textureData.useCount = 0;
  49058. textureData.layers = [];
  49059. }
  49060. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  49061. const commandEncoder = this.device.createCommandEncoder( {} );
  49062. this._mipmapRunBundles( commandEncoder, passes );
  49063. this.device.queue.submit( [ commandEncoder.finish() ] );
  49064. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  49065. textureData.useCount ++;
  49066. }
  49067. /**
  49068. * Since multiple copy render passes are required to generate mipmaps, the passes
  49069. * are managed as render bundles to improve performance.
  49070. *
  49071. * @param {GPUTexture} textureGPU - The GPU texture object.
  49072. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49073. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  49074. * @return {Array<Object>} An array of render bundles.
  49075. */
  49076. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  49077. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  49078. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49079. let srcView = textureGPU.createView( {
  49080. baseMipLevel: 0,
  49081. mipLevelCount: 1,
  49082. dimension: GPUTextureViewDimension.TwoD,
  49083. baseArrayLayer
  49084. } );
  49085. const passes = [];
  49086. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  49087. const bindGroup = this.device.createBindGroup( {
  49088. layout: bindGroupLayout,
  49089. entries: [ {
  49090. binding: 0,
  49091. resource: this.mipmapSampler
  49092. }, {
  49093. binding: 1,
  49094. resource: srcView
  49095. } ]
  49096. } );
  49097. const dstView = textureGPU.createView( {
  49098. baseMipLevel: i,
  49099. mipLevelCount: 1,
  49100. dimension: GPUTextureViewDimension.TwoD,
  49101. baseArrayLayer
  49102. } );
  49103. const passDescriptor = {
  49104. colorAttachments: [ {
  49105. view: dstView,
  49106. loadOp: GPULoadOp.Clear,
  49107. storeOp: GPUStoreOp.Store,
  49108. clearValue: [ 0, 0, 0, 0 ]
  49109. } ]
  49110. };
  49111. const passEncoder = this.device.createRenderBundleEncoder( {
  49112. colorFormats: [ textureGPUDescriptor.format ]
  49113. } );
  49114. passEncoder.setPipeline( pipeline );
  49115. passEncoder.setBindGroup( 0, bindGroup );
  49116. passEncoder.draw( 4, 1, 0, 0 );
  49117. passes.push( {
  49118. renderBundles: [ passEncoder.finish() ],
  49119. passDescriptor
  49120. } );
  49121. srcView = dstView;
  49122. }
  49123. return passes;
  49124. }
  49125. /**
  49126. * Executes the render bundles.
  49127. *
  49128. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  49129. * @param {Array<Object>} passes - An array of render bundles.
  49130. */
  49131. _mipmapRunBundles( commandEncoder, passes ) {
  49132. const levels = passes.length;
  49133. for ( let i = 0; i < levels; i ++ ) {
  49134. const pass = passes[ i ];
  49135. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  49136. passEncoder.executeBundles( pass.renderBundles );
  49137. passEncoder.end();
  49138. }
  49139. }
  49140. }
  49141. const _compareToWebGPU = {
  49142. [ NeverCompare ]: 'never',
  49143. [ LessCompare ]: 'less',
  49144. [ EqualCompare ]: 'equal',
  49145. [ LessEqualCompare ]: 'less-equal',
  49146. [ GreaterCompare ]: 'greater',
  49147. [ GreaterEqualCompare ]: 'greater-equal',
  49148. [ AlwaysCompare ]: 'always',
  49149. [ NotEqualCompare ]: 'not-equal'
  49150. };
  49151. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  49152. /**
  49153. * A WebGPU backend utility module for managing textures.
  49154. *
  49155. * @private
  49156. */
  49157. class WebGPUTextureUtils {
  49158. /**
  49159. * Constructs a new utility object.
  49160. *
  49161. * @param {WebGPUBackend} backend - The WebGPU backend.
  49162. */
  49163. constructor( backend ) {
  49164. /**
  49165. * A reference to the WebGPU backend.
  49166. *
  49167. * @type {WebGPUBackend}
  49168. */
  49169. this.backend = backend;
  49170. /**
  49171. * A reference to the pass utils.
  49172. *
  49173. * @type {?WebGPUTexturePassUtils}
  49174. * @default null
  49175. */
  49176. this._passUtils = null;
  49177. /**
  49178. * A dictionary for managing default textures. The key
  49179. * is the texture format, the value the texture object.
  49180. *
  49181. * @type {Object<string,Texture>}
  49182. */
  49183. this.defaultTexture = {};
  49184. /**
  49185. * A dictionary for managing default cube textures. The key
  49186. * is the texture format, the value the texture object.
  49187. *
  49188. * @type {Object<string,CubeTexture>}
  49189. */
  49190. this.defaultCubeTexture = {};
  49191. /**
  49192. * A default video frame.
  49193. *
  49194. * @type {?VideoFrame}
  49195. * @default null
  49196. */
  49197. this.defaultVideoFrame = null;
  49198. /**
  49199. * A cache of shared texture samplers.
  49200. *
  49201. * @type {Map<string, Object>}
  49202. */
  49203. this._samplerCache = new Map();
  49204. }
  49205. /**
  49206. * Creates a GPU sampler for the given texture.
  49207. *
  49208. * @param {Texture} texture - The texture to create the sampler for.
  49209. * @return {string} The current sampler key.
  49210. */
  49211. updateSampler( texture ) {
  49212. const backend = this.backend;
  49213. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  49214. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  49215. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  49216. let samplerData = this._samplerCache.get( samplerKey );
  49217. if ( samplerData === undefined ) {
  49218. const samplerDescriptorGPU = {
  49219. addressModeU: this._convertAddressMode( texture.wrapS ),
  49220. addressModeV: this._convertAddressMode( texture.wrapT ),
  49221. addressModeW: this._convertAddressMode( texture.wrapR ),
  49222. magFilter: this._convertFilterMode( texture.magFilter ),
  49223. minFilter: this._convertFilterMode( texture.minFilter ),
  49224. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  49225. maxAnisotropy: 1
  49226. };
  49227. // anisotropy can only be used when all filter modes are set to linear.
  49228. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  49229. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  49230. }
  49231. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  49232. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  49233. }
  49234. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  49235. samplerData = { sampler, usedTimes: 0 };
  49236. this._samplerCache.set( samplerKey, samplerData );
  49237. }
  49238. const textureData = backend.get( texture );
  49239. if ( textureData.sampler !== samplerData.sampler ) {
  49240. // check if previous sampler is unused so it can be deleted
  49241. if ( textureData.sampler !== undefined ) {
  49242. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  49243. oldSamplerData.usedTimes --;
  49244. if ( oldSamplerData.usedTimes === 0 ) {
  49245. this._samplerCache.delete( textureData.samplerKey );
  49246. }
  49247. }
  49248. // update to new sampler data
  49249. textureData.samplerKey = samplerKey;
  49250. textureData.sampler = samplerData.sampler;
  49251. samplerData.usedTimes ++;
  49252. }
  49253. return samplerKey;
  49254. }
  49255. /**
  49256. * Creates a default texture for the given texture that can be used
  49257. * as a placeholder until the actual texture is ready for usage.
  49258. *
  49259. * @param {Texture} texture - The texture to create a default texture for.
  49260. */
  49261. createDefaultTexture( texture ) {
  49262. let textureGPU;
  49263. const format = getFormat( texture );
  49264. if ( texture.isCubeTexture ) {
  49265. textureGPU = this._getDefaultCubeTextureGPU( format );
  49266. } else {
  49267. textureGPU = this._getDefaultTextureGPU( format );
  49268. }
  49269. this.backend.get( texture ).texture = textureGPU;
  49270. }
  49271. /**
  49272. * Defines a texture on the GPU for the given texture object.
  49273. *
  49274. * @param {Texture} texture - The texture.
  49275. * @param {Object} [options={}] - Optional configuration parameter.
  49276. */
  49277. createTexture( texture, options = {} ) {
  49278. const backend = this.backend;
  49279. const textureData = backend.get( texture );
  49280. if ( textureData.initialized ) {
  49281. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  49282. }
  49283. if ( texture.isExternalTexture ) {
  49284. textureData.texture = texture.sourceTexture;
  49285. textureData.initialized = true;
  49286. return;
  49287. }
  49288. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  49289. if ( options.levels === undefined ) options.levels = 1;
  49290. if ( options.depth === undefined ) options.depth = 1;
  49291. const { width, height, depth, levels } = options;
  49292. if ( texture.isFramebufferTexture ) {
  49293. if ( options.renderTarget ) {
  49294. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  49295. } else {
  49296. options.format = this.backend.utils.getPreferredCanvasFormat();
  49297. }
  49298. }
  49299. const dimension = this._getDimension( texture );
  49300. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  49301. textureData.format = format;
  49302. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  49303. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  49304. if ( texture.isStorageTexture === true ) {
  49305. usage |= GPUTextureUsage.STORAGE_BINDING;
  49306. }
  49307. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  49308. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  49309. }
  49310. const textureDescriptorGPU = {
  49311. label: texture.name,
  49312. size: {
  49313. width: width,
  49314. height: height,
  49315. depthOrArrayLayers: depth,
  49316. },
  49317. mipLevelCount: levels,
  49318. sampleCount: primarySamples,
  49319. dimension: dimension,
  49320. format: format,
  49321. usage: usage
  49322. };
  49323. // texture creation
  49324. if ( format === undefined ) {
  49325. warn( 'WebGPURenderer: Texture format not supported.' );
  49326. this.createDefaultTexture( texture );
  49327. return;
  49328. }
  49329. if ( texture.isCubeTexture ) {
  49330. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  49331. }
  49332. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  49333. if ( isMSAA ) {
  49334. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  49335. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  49336. msaaTextureDescriptorGPU.sampleCount = samples;
  49337. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  49338. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  49339. }
  49340. textureData.initialized = true;
  49341. textureData.textureDescriptorGPU = textureDescriptorGPU;
  49342. }
  49343. /**
  49344. * Destroys the GPU data for the given texture object.
  49345. *
  49346. * @param {Texture} texture - The texture.
  49347. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49348. */
  49349. destroyTexture( texture, isDefaultTexture = false ) {
  49350. const backend = this.backend;
  49351. const textureData = backend.get( texture );
  49352. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  49353. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  49354. backend.delete( texture );
  49355. }
  49356. /**
  49357. * Generates mipmaps for the given texture.
  49358. *
  49359. * @param {Texture} texture - The texture.
  49360. */
  49361. generateMipmaps( texture ) {
  49362. const textureData = this.backend.get( texture );
  49363. if ( texture.isCubeTexture ) {
  49364. for ( let i = 0; i < 6; i ++ ) {
  49365. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  49366. }
  49367. } else {
  49368. const depth = texture.image.depth || 1;
  49369. for ( let i = 0; i < depth; i ++ ) {
  49370. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  49371. }
  49372. }
  49373. }
  49374. /**
  49375. * Returns the color buffer representing the color
  49376. * attachment of the default framebuffer.
  49377. *
  49378. * @return {GPUTexture} The color buffer.
  49379. */
  49380. getColorBuffer() {
  49381. const backend = this.backend;
  49382. const canvasTarget = backend.renderer.getCanvasTarget();
  49383. const { width, height } = backend.getDrawingBufferSize();
  49384. const samples = backend.renderer.currentSamples;
  49385. const colorTexture = canvasTarget.colorTexture;
  49386. const colorTextureData = backend.get( colorTexture );
  49387. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  49388. return colorTextureData.texture;
  49389. }
  49390. // recreate
  49391. let colorBuffer = colorTextureData.texture;
  49392. if ( colorBuffer ) colorBuffer.destroy();
  49393. colorBuffer = backend.device.createTexture( {
  49394. label: 'colorBuffer',
  49395. size: {
  49396. width: width,
  49397. height: height,
  49398. depthOrArrayLayers: 1
  49399. },
  49400. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  49401. format: backend.utils.getPreferredCanvasFormat(),
  49402. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  49403. } );
  49404. //
  49405. colorTexture.source.width = width;
  49406. colorTexture.source.height = height;
  49407. colorTexture.samples = samples;
  49408. colorTextureData.texture = colorBuffer;
  49409. return colorBuffer;
  49410. }
  49411. /**
  49412. * Returns the depth buffer representing the depth
  49413. * attachment of the default framebuffer.
  49414. *
  49415. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  49416. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  49417. * @return {GPUTexture} The depth buffer.
  49418. */
  49419. getDepthBuffer( depth = true, stencil = false ) {
  49420. const backend = this.backend;
  49421. const canvasTarget = backend.renderer.getCanvasTarget();
  49422. const { width, height } = backend.getDrawingBufferSize();
  49423. const samples = backend.renderer.currentSamples;
  49424. const depthTexture = canvasTarget.depthTexture;
  49425. if ( depthTexture.width === width &&
  49426. depthTexture.height === height &&
  49427. depthTexture.samples === samples &&
  49428. depthTexture.depth === depth &&
  49429. depthTexture.stencil === stencil ) {
  49430. return backend.get( depthTexture ).texture;
  49431. }
  49432. //
  49433. const depthTextureGPU = backend.get( depthTexture ).texture;
  49434. let format, type;
  49435. if ( stencil ) {
  49436. format = DepthStencilFormat;
  49437. type = UnsignedInt248Type;
  49438. } else if ( depth ) {
  49439. format = DepthFormat;
  49440. type = UnsignedIntType;
  49441. }
  49442. if ( depthTextureGPU !== undefined ) {
  49443. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  49444. return depthTextureGPU;
  49445. }
  49446. this.destroyTexture( depthTexture );
  49447. }
  49448. // recreate
  49449. depthTexture.name = 'depthBuffer';
  49450. depthTexture.format = format;
  49451. depthTexture.type = type;
  49452. depthTexture.image.width = width;
  49453. depthTexture.image.height = height;
  49454. depthTexture.samples = samples;
  49455. this.createTexture( depthTexture, { width, height } );
  49456. return backend.get( depthTexture ).texture;
  49457. }
  49458. /**
  49459. * Uploads the updated texture data to the GPU.
  49460. *
  49461. * @param {Texture} texture - The texture.
  49462. * @param {Object} [options={}] - Optional configuration parameter.
  49463. */
  49464. updateTexture( texture, options ) {
  49465. const textureData = this.backend.get( texture );
  49466. const mipmaps = texture.mipmaps;
  49467. const { textureDescriptorGPU } = textureData;
  49468. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  49469. return;
  49470. // transfer texture data
  49471. if ( texture.isDataTexture ) {
  49472. if ( mipmaps.length > 0 ) {
  49473. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49474. const mipmap = mipmaps[ i ];
  49475. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  49476. }
  49477. } else {
  49478. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  49479. }
  49480. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49481. for ( let i = 0; i < options.image.depth; i ++ ) {
  49482. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  49483. }
  49484. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  49485. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  49486. } else if ( texture.isCubeTexture ) {
  49487. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  49488. } else {
  49489. if ( mipmaps.length > 0 ) {
  49490. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49491. const mipmap = mipmaps[ i ];
  49492. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  49493. }
  49494. } else {
  49495. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  49496. }
  49497. }
  49498. //
  49499. textureData.version = texture.version;
  49500. }
  49501. /**
  49502. * Returns texture data as a typed array.
  49503. *
  49504. * @async
  49505. * @param {Texture} texture - The texture to copy.
  49506. * @param {number} x - The x coordinate of the copy origin.
  49507. * @param {number} y - The y coordinate of the copy origin.
  49508. * @param {number} width - The width of the copy.
  49509. * @param {number} height - The height of the copy.
  49510. * @param {number} faceIndex - The face index.
  49511. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49512. */
  49513. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49514. const device = this.backend.device;
  49515. const textureData = this.backend.get( texture );
  49516. const textureGPU = textureData.texture;
  49517. const format = textureData.textureDescriptorGPU.format;
  49518. const bytesPerTexel = this._getBytesPerTexel( format );
  49519. let bytesPerRow = width * bytesPerTexel;
  49520. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  49521. const readBuffer = device.createBuffer(
  49522. {
  49523. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  49524. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49525. }
  49526. );
  49527. const encoder = device.createCommandEncoder();
  49528. encoder.copyTextureToBuffer(
  49529. {
  49530. texture: textureGPU,
  49531. origin: { x, y, z: faceIndex },
  49532. },
  49533. {
  49534. buffer: readBuffer,
  49535. bytesPerRow: bytesPerRow
  49536. },
  49537. {
  49538. width: width,
  49539. height: height
  49540. }
  49541. );
  49542. const typedArrayType = this._getTypedArrayType( format );
  49543. device.queue.submit( [ encoder.finish() ] );
  49544. await readBuffer.mapAsync( GPUMapMode.READ );
  49545. const buffer = readBuffer.getMappedRange();
  49546. return new typedArrayType( buffer );
  49547. }
  49548. /**
  49549. * Frees all internal resources.
  49550. */
  49551. dispose() {
  49552. this._samplerCache.clear();
  49553. }
  49554. /**
  49555. * Returns the default GPU texture for the given format.
  49556. *
  49557. * @private
  49558. * @param {string} format - The GPU format.
  49559. * @return {GPUTexture} The GPU texture.
  49560. */
  49561. _getDefaultTextureGPU( format ) {
  49562. let defaultTexture = this.defaultTexture[ format ];
  49563. if ( defaultTexture === undefined ) {
  49564. const texture = new Texture();
  49565. texture.minFilter = NearestFilter;
  49566. texture.magFilter = NearestFilter;
  49567. this.createTexture( texture, { width: 1, height: 1, format } );
  49568. this.defaultTexture[ format ] = defaultTexture = texture;
  49569. }
  49570. return this.backend.get( defaultTexture ).texture;
  49571. }
  49572. /**
  49573. * Returns the default GPU cube texture for the given format.
  49574. *
  49575. * @private
  49576. * @param {string} format - The GPU format.
  49577. * @return {GPUTexture} The GPU texture.
  49578. */
  49579. _getDefaultCubeTextureGPU( format ) {
  49580. let defaultCubeTexture = this.defaultTexture[ format ];
  49581. if ( defaultCubeTexture === undefined ) {
  49582. const texture = new CubeTexture();
  49583. texture.minFilter = NearestFilter;
  49584. texture.magFilter = NearestFilter;
  49585. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  49586. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  49587. }
  49588. return this.backend.get( defaultCubeTexture ).texture;
  49589. }
  49590. /**
  49591. * Uploads cube texture image data to the GPU memory.
  49592. *
  49593. * @private
  49594. * @param {CubeTexture} texture - The cube texture.
  49595. * @param {GPUTexture} textureGPU - The GPU texture.
  49596. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49597. */
  49598. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  49599. const images = texture.images;
  49600. const mipmaps = texture.mipmaps;
  49601. for ( let i = 0; i < 6; i ++ ) {
  49602. const image = images[ i ];
  49603. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  49604. if ( image.isDataTexture ) {
  49605. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  49606. } else {
  49607. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  49608. }
  49609. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49610. const mipmap = mipmaps[ j ];
  49611. const image = mipmap.images[ i ];
  49612. if ( image.isDataTexture ) {
  49613. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  49614. } else {
  49615. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  49616. }
  49617. }
  49618. }
  49619. }
  49620. /**
  49621. * Uploads texture image data to the GPU memory.
  49622. *
  49623. * @private
  49624. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  49625. * @param {GPUTexture} textureGPU - The GPU texture.
  49626. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49627. * @param {number} originDepth - The origin depth.
  49628. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49629. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  49630. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49631. */
  49632. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  49633. const device = this.backend.device;
  49634. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  49635. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  49636. device.queue.copyExternalImageToTexture(
  49637. {
  49638. source: image,
  49639. flipY: flipY
  49640. }, {
  49641. texture: textureGPU,
  49642. mipLevel: mipLevel,
  49643. origin: { x: 0, y: 0, z: originDepth },
  49644. premultipliedAlpha: premultiplyAlpha
  49645. }, {
  49646. width: width,
  49647. height: height,
  49648. depthOrArrayLayers: 1
  49649. }
  49650. );
  49651. }
  49652. /**
  49653. * Returns the pass utils singleton.
  49654. *
  49655. * @private
  49656. * @return {WebGPUTexturePassUtils} The utils instance.
  49657. */
  49658. _getPassUtils() {
  49659. let passUtils = this._passUtils;
  49660. if ( passUtils === null ) {
  49661. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  49662. }
  49663. return passUtils;
  49664. }
  49665. /**
  49666. * Generates mipmaps for the given GPU texture.
  49667. *
  49668. * @private
  49669. * @param {GPUTexture} textureGPU - The GPU texture object.
  49670. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49671. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49672. */
  49673. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  49674. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  49675. }
  49676. /**
  49677. * Flip the contents of the given GPU texture along its vertical axis.
  49678. *
  49679. * @private
  49680. * @param {GPUTexture} textureGPU - The GPU texture object.
  49681. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49682. * @param {number} [originDepth=0] - The origin depth.
  49683. */
  49684. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  49685. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  49686. }
  49687. /**
  49688. * Uploads texture buffer data to the GPU memory.
  49689. *
  49690. * @private
  49691. * @param {Object} image - An object defining the image buffer data.
  49692. * @param {GPUTexture} textureGPU - The GPU texture.
  49693. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49694. * @param {number} originDepth - The origin depth.
  49695. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49696. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  49697. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49698. */
  49699. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  49700. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49701. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  49702. const device = this.backend.device;
  49703. const data = image.data;
  49704. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  49705. const bytesPerRow = image.width * bytesPerTexel;
  49706. device.queue.writeTexture(
  49707. {
  49708. texture: textureGPU,
  49709. mipLevel: mipLevel,
  49710. origin: { x: 0, y: 0, z: originDepth }
  49711. },
  49712. data,
  49713. {
  49714. offset: image.width * image.height * bytesPerTexel * depth,
  49715. bytesPerRow
  49716. },
  49717. {
  49718. width: image.width,
  49719. height: image.height,
  49720. depthOrArrayLayers: 1
  49721. } );
  49722. if ( flipY === true ) {
  49723. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  49724. }
  49725. }
  49726. /**
  49727. * Uploads compressed texture data to the GPU memory.
  49728. *
  49729. * @private
  49730. * @param {Array<Object>} mipmaps - An array with mipmap data.
  49731. * @param {GPUTexture} textureGPU - The GPU texture.
  49732. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49733. */
  49734. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  49735. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49736. const device = this.backend.device;
  49737. const blockData = this._getBlockData( textureDescriptorGPU.format );
  49738. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  49739. for ( let i = 0; i < mipmaps.length; i ++ ) {
  49740. const mipmap = mipmaps[ i ];
  49741. const width = mipmap.width;
  49742. const height = mipmap.height;
  49743. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  49744. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  49745. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  49746. for ( let j = 0; j < depth; j ++ ) {
  49747. device.queue.writeTexture(
  49748. {
  49749. texture: textureGPU,
  49750. mipLevel: i,
  49751. origin: { x: 0, y: 0, z: j }
  49752. },
  49753. mipmap.data,
  49754. {
  49755. offset: j * bytesPerImage,
  49756. bytesPerRow,
  49757. rowsPerImage: Math.ceil( height / blockData.height )
  49758. },
  49759. {
  49760. width: Math.ceil( width / blockData.width ) * blockData.width,
  49761. height: Math.ceil( height / blockData.height ) * blockData.height,
  49762. depthOrArrayLayers: 1
  49763. }
  49764. );
  49765. }
  49766. }
  49767. }
  49768. /**
  49769. * This method is only relevant for compressed texture formats. It returns a block
  49770. * data descriptor for the given GPU compressed texture format.
  49771. *
  49772. * @private
  49773. * @param {string} format - The GPU compressed texture format.
  49774. * @return {Object} The block data descriptor.
  49775. */
  49776. _getBlockData( format ) {
  49777. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  49778. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  49779. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  49780. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  49781. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  49782. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  49783. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  49784. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49785. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49786. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49787. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  49788. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  49789. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  49790. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  49791. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49792. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  49793. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  49794. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  49795. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  49796. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  49797. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  49798. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  49799. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  49800. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  49801. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  49802. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  49803. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  49804. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  49805. }
  49806. /**
  49807. * Converts the three.js uv wrapping constants to GPU address mode constants.
  49808. *
  49809. * @private
  49810. * @param {number} value - The three.js constant defining a uv wrapping mode.
  49811. * @return {string} The GPU address mode.
  49812. */
  49813. _convertAddressMode( value ) {
  49814. let addressMode = GPUAddressMode.ClampToEdge;
  49815. if ( value === RepeatWrapping ) {
  49816. addressMode = GPUAddressMode.Repeat;
  49817. } else if ( value === MirroredRepeatWrapping ) {
  49818. addressMode = GPUAddressMode.MirrorRepeat;
  49819. }
  49820. return addressMode;
  49821. }
  49822. /**
  49823. * Converts the three.js filter constants to GPU filter constants.
  49824. *
  49825. * @private
  49826. * @param {number} value - The three.js constant defining a filter mode.
  49827. * @return {string} The GPU filter mode.
  49828. */
  49829. _convertFilterMode( value ) {
  49830. let filterMode = GPUFilterMode.Linear;
  49831. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  49832. filterMode = GPUFilterMode.Nearest;
  49833. }
  49834. return filterMode;
  49835. }
  49836. /**
  49837. * Returns the bytes-per-texel value for the given GPU texture format.
  49838. *
  49839. * @private
  49840. * @param {string} format - The GPU texture format.
  49841. * @return {number} The bytes-per-texel.
  49842. */
  49843. _getBytesPerTexel( format ) {
  49844. // 8-bit formats
  49845. if ( format === GPUTextureFormat.R8Unorm ||
  49846. format === GPUTextureFormat.R8Snorm ||
  49847. format === GPUTextureFormat.R8Uint ||
  49848. format === GPUTextureFormat.R8Sint ) return 1;
  49849. // 16-bit formats
  49850. if ( format === GPUTextureFormat.R16Uint ||
  49851. format === GPUTextureFormat.R16Sint ||
  49852. format === GPUTextureFormat.R16Float ||
  49853. format === GPUTextureFormat.RG8Unorm ||
  49854. format === GPUTextureFormat.RG8Snorm ||
  49855. format === GPUTextureFormat.RG8Uint ||
  49856. format === GPUTextureFormat.RG8Sint ) return 2;
  49857. // 32-bit formats
  49858. if ( format === GPUTextureFormat.R32Uint ||
  49859. format === GPUTextureFormat.R32Sint ||
  49860. format === GPUTextureFormat.R32Float ||
  49861. format === GPUTextureFormat.RG16Uint ||
  49862. format === GPUTextureFormat.RG16Sint ||
  49863. format === GPUTextureFormat.RG16Float ||
  49864. format === GPUTextureFormat.RGBA8Unorm ||
  49865. format === GPUTextureFormat.RGBA8UnormSRGB ||
  49866. format === GPUTextureFormat.RGBA8Snorm ||
  49867. format === GPUTextureFormat.RGBA8Uint ||
  49868. format === GPUTextureFormat.RGBA8Sint ||
  49869. format === GPUTextureFormat.BGRA8Unorm ||
  49870. format === GPUTextureFormat.BGRA8UnormSRGB ||
  49871. // Packed 32-bit formats
  49872. format === GPUTextureFormat.RGB9E5UFloat ||
  49873. format === GPUTextureFormat.RGB10A2Unorm ||
  49874. format === GPUTextureFormat.RG11B10UFloat ||
  49875. format === GPUTextureFormat.Depth32Float ||
  49876. format === GPUTextureFormat.Depth24Plus ||
  49877. format === GPUTextureFormat.Depth24PlusStencil8 ||
  49878. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  49879. // 64-bit formats
  49880. if ( format === GPUTextureFormat.RG32Uint ||
  49881. format === GPUTextureFormat.RG32Sint ||
  49882. format === GPUTextureFormat.RG32Float ||
  49883. format === GPUTextureFormat.RGBA16Uint ||
  49884. format === GPUTextureFormat.RGBA16Sint ||
  49885. format === GPUTextureFormat.RGBA16Float ) return 8;
  49886. // 128-bit formats
  49887. if ( format === GPUTextureFormat.RGBA32Uint ||
  49888. format === GPUTextureFormat.RGBA32Sint ||
  49889. format === GPUTextureFormat.RGBA32Float ) return 16;
  49890. }
  49891. /**
  49892. * Returns the corresponding typed array type for the given GPU texture format.
  49893. *
  49894. * @private
  49895. * @param {string} format - The GPU texture format.
  49896. * @return {TypedArray.constructor} The typed array type.
  49897. */
  49898. _getTypedArrayType( format ) {
  49899. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  49900. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  49901. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  49902. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  49903. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  49904. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  49905. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  49906. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  49907. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  49908. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  49909. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  49910. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  49911. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  49912. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  49913. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  49914. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  49915. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  49916. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  49917. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  49918. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  49919. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  49920. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  49921. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  49922. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  49923. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  49924. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  49925. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  49926. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  49927. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  49928. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  49929. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  49930. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  49931. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  49932. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  49933. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  49934. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  49935. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  49936. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  49937. }
  49938. /**
  49939. * Returns the GPU dimensions for the given texture.
  49940. *
  49941. * @private
  49942. * @param {Texture} texture - The texture.
  49943. * @return {string} The GPU dimension.
  49944. */
  49945. _getDimension( texture ) {
  49946. let dimension;
  49947. if ( texture.is3DTexture || texture.isData3DTexture ) {
  49948. dimension = GPUTextureDimension.ThreeD;
  49949. } else {
  49950. dimension = GPUTextureDimension.TwoD;
  49951. }
  49952. return dimension;
  49953. }
  49954. }
  49955. /**
  49956. * Returns the GPU format for the given texture.
  49957. *
  49958. * @param {Texture} texture - The texture.
  49959. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  49960. * It is not necessary to apply the device for most formats.
  49961. * @return {string} The GPU format.
  49962. */
  49963. function getFormat( texture, device = null ) {
  49964. const format = texture.format;
  49965. const type = texture.type;
  49966. const colorSpace = texture.colorSpace;
  49967. const transfer = ColorManagement.getTransfer( colorSpace );
  49968. let formatGPU;
  49969. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  49970. switch ( format ) {
  49971. case RGB_S3TC_DXT1_Format:
  49972. case RGBA_S3TC_DXT1_Format:
  49973. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  49974. break;
  49975. case RGBA_S3TC_DXT3_Format:
  49976. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  49977. break;
  49978. case RGBA_S3TC_DXT5_Format:
  49979. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  49980. break;
  49981. case RED_RGTC1_Format:
  49982. formatGPU = GPUTextureFormat.BC4RUnorm;
  49983. break;
  49984. case SIGNED_RED_RGTC1_Format:
  49985. formatGPU = GPUTextureFormat.BC4RSnorm;
  49986. break;
  49987. case RED_GREEN_RGTC2_Format:
  49988. formatGPU = GPUTextureFormat.BC5RGUnorm;
  49989. break;
  49990. case SIGNED_RED_GREEN_RGTC2_Format:
  49991. formatGPU = GPUTextureFormat.BC5RGSnorm;
  49992. break;
  49993. case RGBA_BPTC_Format:
  49994. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  49995. break;
  49996. case RGB_ETC2_Format:
  49997. case RGB_ETC1_Format:
  49998. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  49999. break;
  50000. case RGBA_ETC2_EAC_Format:
  50001. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  50002. break;
  50003. case RGBA_ASTC_4x4_Format:
  50004. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  50005. break;
  50006. case RGBA_ASTC_5x4_Format:
  50007. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  50008. break;
  50009. case RGBA_ASTC_5x5_Format:
  50010. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  50011. break;
  50012. case RGBA_ASTC_6x5_Format:
  50013. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  50014. break;
  50015. case RGBA_ASTC_6x6_Format:
  50016. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  50017. break;
  50018. case RGBA_ASTC_8x5_Format:
  50019. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  50020. break;
  50021. case RGBA_ASTC_8x6_Format:
  50022. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  50023. break;
  50024. case RGBA_ASTC_8x8_Format:
  50025. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  50026. break;
  50027. case RGBA_ASTC_10x5_Format:
  50028. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  50029. break;
  50030. case RGBA_ASTC_10x6_Format:
  50031. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  50032. break;
  50033. case RGBA_ASTC_10x8_Format:
  50034. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  50035. break;
  50036. case RGBA_ASTC_10x10_Format:
  50037. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  50038. break;
  50039. case RGBA_ASTC_12x10_Format:
  50040. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  50041. break;
  50042. case RGBA_ASTC_12x12_Format:
  50043. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  50044. break;
  50045. case RGBAFormat:
  50046. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50047. break;
  50048. default:
  50049. error( 'WebGPURenderer: Unsupported texture format.', format );
  50050. }
  50051. } else {
  50052. switch ( format ) {
  50053. case RGBAFormat:
  50054. switch ( type ) {
  50055. case ByteType:
  50056. formatGPU = GPUTextureFormat.RGBA8Snorm;
  50057. break;
  50058. case ShortType:
  50059. formatGPU = GPUTextureFormat.RGBA16Sint;
  50060. break;
  50061. case UnsignedShortType:
  50062. formatGPU = GPUTextureFormat.RGBA16Uint;
  50063. break;
  50064. case UnsignedIntType:
  50065. formatGPU = GPUTextureFormat.RGBA32Uint;
  50066. break;
  50067. case IntType:
  50068. formatGPU = GPUTextureFormat.RGBA32Sint;
  50069. break;
  50070. case UnsignedByteType:
  50071. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50072. break;
  50073. case HalfFloatType:
  50074. formatGPU = GPUTextureFormat.RGBA16Float;
  50075. break;
  50076. case FloatType:
  50077. formatGPU = GPUTextureFormat.RGBA32Float;
  50078. break;
  50079. default:
  50080. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  50081. }
  50082. break;
  50083. case RGBFormat:
  50084. switch ( type ) {
  50085. case UnsignedInt5999Type:
  50086. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  50087. break;
  50088. case UnsignedInt101111Type:
  50089. formatGPU = GPUTextureFormat.RG11B10UFloat;
  50090. break;
  50091. default:
  50092. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  50093. }
  50094. break;
  50095. case RedFormat:
  50096. switch ( type ) {
  50097. case ByteType:
  50098. formatGPU = GPUTextureFormat.R8Snorm;
  50099. break;
  50100. case ShortType:
  50101. formatGPU = GPUTextureFormat.R16Sint;
  50102. break;
  50103. case UnsignedShortType:
  50104. formatGPU = GPUTextureFormat.R16Uint;
  50105. break;
  50106. case UnsignedIntType:
  50107. formatGPU = GPUTextureFormat.R32Uint;
  50108. break;
  50109. case IntType:
  50110. formatGPU = GPUTextureFormat.R32Sint;
  50111. break;
  50112. case UnsignedByteType:
  50113. formatGPU = GPUTextureFormat.R8Unorm;
  50114. break;
  50115. case HalfFloatType:
  50116. formatGPU = GPUTextureFormat.R16Float;
  50117. break;
  50118. case FloatType:
  50119. formatGPU = GPUTextureFormat.R32Float;
  50120. break;
  50121. default:
  50122. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  50123. }
  50124. break;
  50125. case RGFormat:
  50126. switch ( type ) {
  50127. case ByteType:
  50128. formatGPU = GPUTextureFormat.RG8Snorm;
  50129. break;
  50130. case ShortType:
  50131. formatGPU = GPUTextureFormat.RG16Sint;
  50132. break;
  50133. case UnsignedShortType:
  50134. formatGPU = GPUTextureFormat.RG16Uint;
  50135. break;
  50136. case UnsignedIntType:
  50137. formatGPU = GPUTextureFormat.RG32Uint;
  50138. break;
  50139. case IntType:
  50140. formatGPU = GPUTextureFormat.RG32Sint;
  50141. break;
  50142. case UnsignedByteType:
  50143. formatGPU = GPUTextureFormat.RG8Unorm;
  50144. break;
  50145. case HalfFloatType:
  50146. formatGPU = GPUTextureFormat.RG16Float;
  50147. break;
  50148. case FloatType:
  50149. formatGPU = GPUTextureFormat.RG32Float;
  50150. break;
  50151. default:
  50152. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  50153. }
  50154. break;
  50155. case DepthFormat:
  50156. switch ( type ) {
  50157. case UnsignedShortType:
  50158. formatGPU = GPUTextureFormat.Depth16Unorm;
  50159. break;
  50160. case UnsignedIntType:
  50161. formatGPU = GPUTextureFormat.Depth24Plus;
  50162. break;
  50163. case FloatType:
  50164. formatGPU = GPUTextureFormat.Depth32Float;
  50165. break;
  50166. default:
  50167. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  50168. }
  50169. break;
  50170. case DepthStencilFormat:
  50171. switch ( type ) {
  50172. case UnsignedInt248Type:
  50173. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  50174. break;
  50175. case FloatType:
  50176. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  50177. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  50178. }
  50179. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  50180. break;
  50181. default:
  50182. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  50183. }
  50184. break;
  50185. case RedIntegerFormat:
  50186. switch ( type ) {
  50187. case IntType:
  50188. formatGPU = GPUTextureFormat.R32Sint;
  50189. break;
  50190. case UnsignedIntType:
  50191. formatGPU = GPUTextureFormat.R32Uint;
  50192. break;
  50193. default:
  50194. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  50195. }
  50196. break;
  50197. case RGIntegerFormat:
  50198. switch ( type ) {
  50199. case IntType:
  50200. formatGPU = GPUTextureFormat.RG32Sint;
  50201. break;
  50202. case UnsignedIntType:
  50203. formatGPU = GPUTextureFormat.RG32Uint;
  50204. break;
  50205. default:
  50206. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  50207. }
  50208. break;
  50209. case RGBAIntegerFormat:
  50210. switch ( type ) {
  50211. case IntType:
  50212. formatGPU = GPUTextureFormat.RGBA32Sint;
  50213. break;
  50214. case UnsignedIntType:
  50215. formatGPU = GPUTextureFormat.RGBA32Uint;
  50216. break;
  50217. default:
  50218. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  50219. }
  50220. break;
  50221. default:
  50222. error( 'WebGPURenderer: Unsupported texture format.', format );
  50223. }
  50224. }
  50225. return formatGPU;
  50226. }
  50227. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  50228. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  50229. const wgslTypeLib$1 = {
  50230. 'f32': 'float',
  50231. 'i32': 'int',
  50232. 'u32': 'uint',
  50233. 'bool': 'bool',
  50234. 'vec2<f32>': 'vec2',
  50235. 'vec2<i32>': 'ivec2',
  50236. 'vec2<u32>': 'uvec2',
  50237. 'vec2<bool>': 'bvec2',
  50238. 'vec2f': 'vec2',
  50239. 'vec2i': 'ivec2',
  50240. 'vec2u': 'uvec2',
  50241. 'vec2b': 'bvec2',
  50242. 'vec3<f32>': 'vec3',
  50243. 'vec3<i32>': 'ivec3',
  50244. 'vec3<u32>': 'uvec3',
  50245. 'vec3<bool>': 'bvec3',
  50246. 'vec3f': 'vec3',
  50247. 'vec3i': 'ivec3',
  50248. 'vec3u': 'uvec3',
  50249. 'vec3b': 'bvec3',
  50250. 'vec4<f32>': 'vec4',
  50251. 'vec4<i32>': 'ivec4',
  50252. 'vec4<u32>': 'uvec4',
  50253. 'vec4<bool>': 'bvec4',
  50254. 'vec4f': 'vec4',
  50255. 'vec4i': 'ivec4',
  50256. 'vec4u': 'uvec4',
  50257. 'vec4b': 'bvec4',
  50258. 'mat2x2<f32>': 'mat2',
  50259. 'mat2x2f': 'mat2',
  50260. 'mat3x3<f32>': 'mat3',
  50261. 'mat3x3f': 'mat3',
  50262. 'mat4x4<f32>': 'mat4',
  50263. 'mat4x4f': 'mat4',
  50264. 'sampler': 'sampler',
  50265. 'texture_1d': 'texture',
  50266. 'texture_2d': 'texture',
  50267. 'texture_2d_array': 'texture',
  50268. 'texture_multisampled_2d': 'cubeTexture',
  50269. 'texture_depth_2d': 'depthTexture',
  50270. 'texture_depth_2d_array': 'depthTexture',
  50271. 'texture_depth_multisampled_2d': 'depthTexture',
  50272. 'texture_depth_cube': 'depthTexture',
  50273. 'texture_depth_cube_array': 'depthTexture',
  50274. 'texture_3d': 'texture3D',
  50275. 'texture_cube': 'cubeTexture',
  50276. 'texture_cube_array': 'cubeTexture',
  50277. 'texture_storage_1d': 'storageTexture',
  50278. 'texture_storage_2d': 'storageTexture',
  50279. 'texture_storage_2d_array': 'storageTexture',
  50280. 'texture_storage_3d': 'storageTexture'
  50281. };
  50282. const parse = ( source ) => {
  50283. source = source.trim();
  50284. const declaration = source.match( declarationRegexp );
  50285. if ( declaration !== null && declaration.length === 4 ) {
  50286. const inputsCode = declaration[ 2 ];
  50287. const propsMatches = [];
  50288. let match = null;
  50289. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  50290. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  50291. }
  50292. // Process matches to correctly pair names and types
  50293. const inputs = [];
  50294. for ( let i = 0; i < propsMatches.length; i ++ ) {
  50295. const { name, type } = propsMatches[ i ];
  50296. let resolvedType = type;
  50297. if ( resolvedType.startsWith( 'ptr' ) ) {
  50298. resolvedType = 'pointer';
  50299. } else {
  50300. if ( resolvedType.startsWith( 'texture' ) ) {
  50301. resolvedType = type.split( '<' )[ 0 ];
  50302. }
  50303. resolvedType = wgslTypeLib$1[ resolvedType ];
  50304. }
  50305. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  50306. }
  50307. const blockCode = source.substring( declaration[ 0 ].length );
  50308. const outputType = declaration[ 3 ] || 'void';
  50309. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  50310. const type = wgslTypeLib$1[ outputType ] || outputType;
  50311. return {
  50312. type,
  50313. inputs,
  50314. name,
  50315. inputsCode,
  50316. blockCode,
  50317. outputType
  50318. };
  50319. } else {
  50320. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  50321. }
  50322. };
  50323. /**
  50324. * This class represents a WSL node function.
  50325. *
  50326. * @augments NodeFunction
  50327. */
  50328. class WGSLNodeFunction extends NodeFunction {
  50329. /**
  50330. * Constructs a new WGSL node function.
  50331. *
  50332. * @param {string} source - The WGSL source.
  50333. */
  50334. constructor( source ) {
  50335. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  50336. super( type, inputs, name );
  50337. this.inputsCode = inputsCode;
  50338. this.blockCode = blockCode;
  50339. this.outputType = outputType;
  50340. }
  50341. /**
  50342. * This method returns the WGSL code of the node function.
  50343. *
  50344. * @param {string} [name=this.name] - The function's name.
  50345. * @return {string} The shader code.
  50346. */
  50347. getCode( name = this.name ) {
  50348. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  50349. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  50350. }
  50351. }
  50352. /**
  50353. * A WGSL node parser.
  50354. *
  50355. * @augments NodeParser
  50356. */
  50357. class WGSLNodeParser extends NodeParser {
  50358. /**
  50359. * The method parses the given WGSL code an returns a node function.
  50360. *
  50361. * @param {string} source - The WGSL code.
  50362. * @return {WGSLNodeFunction} A node function.
  50363. */
  50364. parseFunction( source ) {
  50365. return new WGSLNodeFunction( source );
  50366. }
  50367. }
  50368. // GPUShaderStage is not defined in browsers not supporting WebGPU
  50369. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50370. const accessNames = {
  50371. [ NodeAccess.READ_ONLY ]: 'read',
  50372. [ NodeAccess.WRITE_ONLY ]: 'write',
  50373. [ NodeAccess.READ_WRITE ]: 'read_write'
  50374. };
  50375. const wrapNames = {
  50376. [ RepeatWrapping ]: 'repeat',
  50377. [ ClampToEdgeWrapping ]: 'clamp',
  50378. [ MirroredRepeatWrapping ]: 'mirror'
  50379. };
  50380. const gpuShaderStageLib = {
  50381. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  50382. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  50383. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  50384. };
  50385. const supports = {
  50386. instance: true,
  50387. swizzleAssign: false,
  50388. storageBuffer: true
  50389. };
  50390. const wgslFnOpLib = {
  50391. '^^': 'tsl_xor'
  50392. };
  50393. const wgslTypeLib = {
  50394. float: 'f32',
  50395. int: 'i32',
  50396. uint: 'u32',
  50397. bool: 'bool',
  50398. color: 'vec3<f32>',
  50399. vec2: 'vec2<f32>',
  50400. ivec2: 'vec2<i32>',
  50401. uvec2: 'vec2<u32>',
  50402. bvec2: 'vec2<bool>',
  50403. vec3: 'vec3<f32>',
  50404. ivec3: 'vec3<i32>',
  50405. uvec3: 'vec3<u32>',
  50406. bvec3: 'vec3<bool>',
  50407. vec4: 'vec4<f32>',
  50408. ivec4: 'vec4<i32>',
  50409. uvec4: 'vec4<u32>',
  50410. bvec4: 'vec4<bool>',
  50411. mat2: 'mat2x2<f32>',
  50412. mat3: 'mat3x3<f32>',
  50413. mat4: 'mat4x4<f32>'
  50414. };
  50415. const wgslCodeCache = {};
  50416. const wgslPolyfill = {
  50417. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  50418. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  50419. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  50420. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  50421. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  50422. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  50423. 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 ); }' ),
  50424. 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 ); }' ),
  50425. 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 ); }' ),
  50426. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  50427. 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 ); }' ),
  50428. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  50429. biquadraticTexture: new CodeNode( /* wgsl */`
  50430. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  50431. let res = vec2f( iRes );
  50432. let uvScaled = coord * res;
  50433. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  50434. // https://www.shadertoy.com/view/WtyXRy
  50435. let uv = uvWrapping - 0.5;
  50436. let iuv = floor( uv );
  50437. let f = fract( uv );
  50438. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  50439. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  50440. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  50441. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  50442. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  50443. }
  50444. ` )
  50445. };
  50446. const wgslMethods = {
  50447. dFdx: 'dpdx',
  50448. dFdy: '- dpdy',
  50449. mod_float: 'tsl_mod_float',
  50450. mod_vec2: 'tsl_mod_vec2',
  50451. mod_vec3: 'tsl_mod_vec3',
  50452. mod_vec4: 'tsl_mod_vec4',
  50453. equals_bool: 'tsl_equals_bool',
  50454. equals_bvec2: 'tsl_equals_bvec2',
  50455. equals_bvec3: 'tsl_equals_bvec3',
  50456. equals_bvec4: 'tsl_equals_bvec4',
  50457. inversesqrt: 'inverseSqrt',
  50458. bitcast: 'bitcast<f32>'
  50459. };
  50460. //
  50461. let diagnostics = '';
  50462. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  50463. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  50464. }
  50465. /**
  50466. * A node builder targeting WGSL.
  50467. *
  50468. * This module generates WGSL shader code from node materials and also
  50469. * generates the respective bindings and vertex buffer definitions. These
  50470. * data are later used by the renderer to create render and compute pipelines
  50471. * for render objects.
  50472. *
  50473. * @augments NodeBuilder
  50474. */
  50475. class WGSLNodeBuilder extends NodeBuilder {
  50476. /**
  50477. * Constructs a new WGSL node builder renderer.
  50478. *
  50479. * @param {Object3D} object - The 3D object.
  50480. * @param {Renderer} renderer - The renderer.
  50481. */
  50482. constructor( object, renderer ) {
  50483. super( object, renderer, new WGSLNodeParser() );
  50484. /**
  50485. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  50486. * another dictionary which manages UBOs per group ('render','frame','object').
  50487. *
  50488. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  50489. */
  50490. this.uniformGroups = {};
  50491. /**
  50492. * A dictionary that holds for each shader stage a Map of builtins.
  50493. *
  50494. * @type {Object<string,Map<string,Object>>}
  50495. */
  50496. this.builtins = {};
  50497. /**
  50498. * A dictionary that holds for each shader stage a Set of directives.
  50499. *
  50500. * @type {Object<string,Set<string>>}
  50501. */
  50502. this.directives = {};
  50503. /**
  50504. * A map for managing scope arrays. Only relevant for when using
  50505. * {@link WorkgroupInfoNode} in context of compute shaders.
  50506. *
  50507. * @type {Map<string,Object>}
  50508. */
  50509. this.scopedArrays = new Map();
  50510. }
  50511. /**
  50512. * Generates the WGSL snippet for sampled textures.
  50513. *
  50514. * @private
  50515. * @param {Texture} texture - The texture.
  50516. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50517. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50518. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50519. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50520. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50521. * @return {string} The WGSL snippet.
  50522. */
  50523. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50524. if ( shaderStage === 'fragment' ) {
  50525. if ( depthSnippet ) {
  50526. if ( offsetSnippet ) {
  50527. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  50528. }
  50529. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  50530. } else {
  50531. if ( offsetSnippet ) {
  50532. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  50533. }
  50534. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  50535. }
  50536. } else {
  50537. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  50538. }
  50539. }
  50540. /**
  50541. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50542. *
  50543. * @private
  50544. * @param {Texture} texture - The texture.
  50545. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50546. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50547. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50548. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50549. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50550. * @return {string} The WGSL snippet.
  50551. */
  50552. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50553. if ( this.isUnfilterable( texture ) === false ) {
  50554. if ( offsetSnippet ) {
  50555. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50556. }
  50557. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50558. } else if ( this.isFilteredTexture( texture ) ) {
  50559. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50560. } else {
  50561. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50562. }
  50563. }
  50564. /**
  50565. * Generates a wrap function used in context of textures.
  50566. *
  50567. * @param {Texture} texture - The texture to generate the function for.
  50568. * @return {string} The name of the generated function.
  50569. */
  50570. generateWrapFunction( texture ) {
  50571. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  50572. let nodeCode = wgslCodeCache[ functionName ];
  50573. if ( nodeCode === undefined ) {
  50574. const includes = [];
  50575. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  50576. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  50577. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  50578. const addWrapSnippet = ( wrap, axis ) => {
  50579. if ( wrap === RepeatWrapping ) {
  50580. includes.push( wgslPolyfill.repeatWrapping_float );
  50581. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  50582. } else if ( wrap === ClampToEdgeWrapping ) {
  50583. includes.push( wgslPolyfill.clampWrapping_float );
  50584. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  50585. } else if ( wrap === MirroredRepeatWrapping ) {
  50586. includes.push( wgslPolyfill.mirrorWrapping_float );
  50587. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  50588. } else {
  50589. code += `\t\tcoord.${ axis }`;
  50590. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  50591. }
  50592. };
  50593. addWrapSnippet( texture.wrapS, 'x' );
  50594. code += ',\n';
  50595. addWrapSnippet( texture.wrapT, 'y' );
  50596. if ( texture.isData3DTexture ) {
  50597. code += ',\n';
  50598. addWrapSnippet( texture.wrapR, 'z' );
  50599. }
  50600. code += '\n\t);\n\n}\n';
  50601. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  50602. }
  50603. nodeCode.build( this );
  50604. return functionName;
  50605. }
  50606. /**
  50607. * Generates the array declaration string.
  50608. *
  50609. * @param {string} type - The type.
  50610. * @param {?number} [count] - The count.
  50611. * @return {string} The generated value as a shader string.
  50612. */
  50613. generateArrayDeclaration( type, count ) {
  50614. return `array< ${ this.getType( type ) }, ${ count } >`;
  50615. }
  50616. /**
  50617. * Generates a WGSL variable that holds the texture dimension of the given texture.
  50618. * It also returns information about the number of layers (elements) of an arrayed
  50619. * texture as well as the cube face count of cube textures.
  50620. *
  50621. * @param {Texture} texture - The texture to generate the function for.
  50622. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  50623. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50624. * @return {string} The name of the dimension variable.
  50625. */
  50626. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  50627. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  50628. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  50629. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  50630. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  50631. let textureDimensionsParams;
  50632. let dimensionType;
  50633. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50634. const isMultisampled = primarySamples > 1;
  50635. if ( texture.isData3DTexture ) {
  50636. dimensionType = 'vec3<u32>';
  50637. } else {
  50638. // Regular 2D textures, depth textures, etc.
  50639. dimensionType = 'vec2<u32>';
  50640. }
  50641. // Build parameters string based on texture type and multisampling
  50642. if ( isMultisampled || texture.isStorageTexture ) {
  50643. textureDimensionsParams = textureProperty;
  50644. } else {
  50645. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  50646. }
  50647. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  50648. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  50649. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50650. textureData.arrayLayerCount = new VarNode(
  50651. new ExpressionNode(
  50652. `textureNumLayers(${textureProperty})`,
  50653. 'u32'
  50654. )
  50655. );
  50656. }
  50657. // For cube textures, we know it's always 6 faces
  50658. if ( texture.isTextureCube ) {
  50659. textureData.cubeFaceCount = new VarNode(
  50660. new ExpressionNode( '6u', 'u32' )
  50661. );
  50662. }
  50663. }
  50664. return textureDimensionNode.build( this );
  50665. }
  50666. /**
  50667. * Generates the WGSL snippet for a manual filtered texture.
  50668. *
  50669. * @param {Texture} texture - The texture.
  50670. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50671. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50672. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50673. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50674. * @return {string} The WGSL snippet.
  50675. */
  50676. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50677. this._include( 'biquadraticTexture' );
  50678. const wrapFunction = this.generateWrapFunction( texture );
  50679. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50680. if ( offsetSnippet ) {
  50681. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  50682. }
  50683. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  50684. }
  50685. /**
  50686. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  50687. * Since it's a lookup, no sampling or filtering is applied.
  50688. *
  50689. * @param {Texture} texture - The texture.
  50690. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50691. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50692. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50693. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50694. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50695. * @return {string} The WGSL snippet.
  50696. */
  50697. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50698. const wrapFunction = this.generateWrapFunction( texture );
  50699. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50700. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  50701. if ( offsetSnippet ) {
  50702. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  50703. }
  50704. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  50705. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  50706. }
  50707. /**
  50708. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  50709. *
  50710. * @param {Texture} texture - The texture.
  50711. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50712. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50713. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50714. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  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. * @return {string} The WGSL snippet.
  50717. */
  50718. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50719. if ( levelSnippet === null ) levelSnippet = '0u';
  50720. if ( offsetSnippet ) {
  50721. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  50722. }
  50723. let snippet;
  50724. if ( depthSnippet ) {
  50725. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  50726. } else {
  50727. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  50728. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  50729. snippet += '.x';
  50730. }
  50731. }
  50732. return snippet;
  50733. }
  50734. /**
  50735. * Generates the WGSL snippet that writes a single texel to a texture.
  50736. *
  50737. * @param {Texture} texture - The texture.
  50738. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50739. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50740. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50741. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  50742. * @return {string} The WGSL snippet.
  50743. */
  50744. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  50745. let snippet;
  50746. if ( depthSnippet ) {
  50747. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  50748. } else {
  50749. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  50750. }
  50751. return snippet;
  50752. }
  50753. /**
  50754. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  50755. *
  50756. * @param {Texture} texture - The texture.
  50757. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  50758. */
  50759. isSampleCompare( texture ) {
  50760. return texture.isDepthTexture === true && texture.compareFunction !== null;
  50761. }
  50762. /**
  50763. * Returns `true` if the given texture is unfilterable.
  50764. *
  50765. * @param {Texture} texture - The texture.
  50766. * @return {boolean} Whether the given texture is unfilterable or not.
  50767. */
  50768. isUnfilterable( texture ) {
  50769. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  50770. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  50771. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  50772. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  50773. }
  50774. /**
  50775. * Generates the WGSL snippet for sampling/loading the given texture.
  50776. *
  50777. * @param {Texture} texture - The texture.
  50778. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50779. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50780. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50781. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50782. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50783. * @return {string} The WGSL snippet.
  50784. */
  50785. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50786. let snippet = null;
  50787. if ( this.isUnfilterable( texture ) ) {
  50788. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  50789. } else {
  50790. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  50791. }
  50792. return snippet;
  50793. }
  50794. /**
  50795. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  50796. *
  50797. * @param {Texture} texture - The texture.
  50798. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50799. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50800. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  50801. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50802. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50803. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50804. * @return {string} The WGSL snippet.
  50805. */
  50806. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50807. if ( shaderStage === 'fragment' ) {
  50808. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  50809. if ( offsetSnippet ) {
  50810. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  50811. }
  50812. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  50813. } else {
  50814. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  50815. }
  50816. }
  50817. /**
  50818. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  50819. * against a reference value.
  50820. *
  50821. * @param {Texture} texture - The texture.
  50822. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50823. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50824. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  50825. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50826. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50827. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50828. * @return {string} The WGSL snippet.
  50829. */
  50830. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50831. if ( shaderStage === 'fragment' ) {
  50832. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  50833. if ( offsetSnippet ) {
  50834. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50835. }
  50836. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  50837. }
  50838. if ( offsetSnippet ) {
  50839. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50840. }
  50841. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  50842. } else {
  50843. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  50844. }
  50845. }
  50846. /**
  50847. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50848. *
  50849. * @param {Texture} texture - The texture.
  50850. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50851. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50852. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50853. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50854. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50855. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50856. * @return {string} The WGSL snippet.
  50857. */
  50858. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50859. if ( this.isUnfilterable( texture ) === false ) {
  50860. if ( offsetSnippet ) {
  50861. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50862. }
  50863. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50864. } else if ( this.isFilteredTexture( texture ) ) {
  50865. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50866. } else {
  50867. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50868. }
  50869. }
  50870. /**
  50871. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  50872. *
  50873. * @param {Texture} texture - The texture.
  50874. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50875. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50876. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  50877. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50878. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50879. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50880. * @return {string} The WGSL snippet.
  50881. */
  50882. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50883. if ( shaderStage === 'fragment' ) {
  50884. if ( offsetSnippet ) {
  50885. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  50886. }
  50887. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  50888. } else {
  50889. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  50890. }
  50891. }
  50892. /**
  50893. * Returns a WGSL snippet that represents the property name of the given node.
  50894. *
  50895. * @param {Node} node - The node.
  50896. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50897. * @return {string} The property name.
  50898. */
  50899. getPropertyName( node, shaderStage = this.shaderStage ) {
  50900. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  50901. if ( shaderStage === 'vertex' ) {
  50902. return `varyings.${ node.name }`;
  50903. }
  50904. } else if ( node.isNodeUniform === true ) {
  50905. const name = node.name;
  50906. const type = node.type;
  50907. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50908. return name;
  50909. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  50910. if ( this.isCustomStruct( node ) ) {
  50911. return name;
  50912. }
  50913. return name + '.value';
  50914. } else {
  50915. return node.groupNode.name + '.' + name;
  50916. }
  50917. }
  50918. return super.getPropertyName( node );
  50919. }
  50920. /**
  50921. * Returns the output struct name.
  50922. *
  50923. * @return {string} The name of the output struct.
  50924. */
  50925. getOutputStructName() {
  50926. return 'output';
  50927. }
  50928. /**
  50929. * Returns the native shader operator name for a given generic name.
  50930. *
  50931. * @param {string} op - The operator name to resolve.
  50932. * @return {?string} The resolved operator name.
  50933. */
  50934. getFunctionOperator( op ) {
  50935. const fnOp = wgslFnOpLib[ op ];
  50936. if ( fnOp !== undefined ) {
  50937. this._include( fnOp );
  50938. return fnOp;
  50939. }
  50940. return null;
  50941. }
  50942. /**
  50943. * Returns the node access for the given node and shader stage.
  50944. *
  50945. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50946. * @param {string} shaderStage - The shader stage.
  50947. * @return {string} The node access.
  50948. */
  50949. getNodeAccess( node, shaderStage ) {
  50950. if ( shaderStage !== 'compute' ) {
  50951. if ( node.isAtomic === true ) {
  50952. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  50953. return NodeAccess.READ_WRITE;
  50954. }
  50955. return NodeAccess.READ_ONLY;
  50956. }
  50957. return node.access;
  50958. }
  50959. /**
  50960. * Returns A WGSL snippet representing the storage access.
  50961. *
  50962. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50963. * @param {string} shaderStage - The shader stage.
  50964. * @return {string} The WGSL snippet representing the storage access.
  50965. */
  50966. getStorageAccess( node, shaderStage ) {
  50967. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  50968. }
  50969. /**
  50970. * This method is one of the more important ones since it's responsible
  50971. * for generating a matching binding instance for the given uniform node.
  50972. *
  50973. * These bindings are later used in the renderer to create bind groups
  50974. * and layouts.
  50975. *
  50976. * @param {UniformNode} node - The uniform node.
  50977. * @param {string} type - The node data type.
  50978. * @param {string} shaderStage - The shader stage.
  50979. * @param {?string} [name=null] - An optional uniform name.
  50980. * @return {NodeUniform} The node uniform object.
  50981. */
  50982. getUniformFromNode( node, type, shaderStage, name = null ) {
  50983. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  50984. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  50985. if ( nodeData.uniformGPU === undefined ) {
  50986. let uniformGPU;
  50987. const group = node.groupNode;
  50988. const groupName = group.name;
  50989. const bindings = this.getBindGroupArray( groupName, shaderStage );
  50990. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50991. let texture = null;
  50992. const access = this.getNodeAccess( node, shaderStage );
  50993. if ( type === 'texture' || type === 'storageTexture' ) {
  50994. if ( node.value.is3DTexture === true ) {
  50995. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  50996. } else {
  50997. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  50998. }
  50999. } else if ( type === 'cubeTexture' ) {
  51000. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  51001. } else if ( type === 'texture3D' ) {
  51002. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51003. }
  51004. texture.store = node.isStorageTextureNode === true;
  51005. texture.mipLevel = texture.store ? node.mipLevel : 0;
  51006. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51007. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  51008. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  51009. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51010. bindings.push( sampler, texture );
  51011. uniformGPU = [ sampler, texture ];
  51012. } else {
  51013. bindings.push( texture );
  51014. uniformGPU = [ texture ];
  51015. }
  51016. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51017. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  51018. const buffer = new bufferClass( node, group );
  51019. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51020. bindings.push( buffer );
  51021. uniformGPU = buffer;
  51022. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  51023. } else {
  51024. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  51025. let uniformsGroup = uniformsStage[ groupName ];
  51026. if ( uniformsGroup === undefined ) {
  51027. uniformsGroup = new NodeUniformsGroup( groupName, group );
  51028. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51029. uniformsStage[ groupName ] = uniformsGroup;
  51030. bindings.push( uniformsGroup );
  51031. }
  51032. uniformGPU = this.getNodeUniform( uniformNode, type );
  51033. uniformsGroup.addUniform( uniformGPU );
  51034. }
  51035. nodeData.uniformGPU = uniformGPU;
  51036. }
  51037. return uniformNode;
  51038. }
  51039. /**
  51040. * This method should be used whenever builtins are required in nodes.
  51041. * The internal builtins data structure will make sure builtins are
  51042. * defined in the WGSL source.
  51043. *
  51044. * @param {string} name - The builtin name.
  51045. * @param {string} property - The property name.
  51046. * @param {string} type - The node data type.
  51047. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51048. * @return {string} The property name.
  51049. */
  51050. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  51051. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  51052. if ( map.has( name ) === false ) {
  51053. map.set( name, {
  51054. name,
  51055. property,
  51056. type
  51057. } );
  51058. }
  51059. return property;
  51060. }
  51061. /**
  51062. * Returns `true` if the given builtin is defined in the given shader stage.
  51063. *
  51064. * @param {string} name - The builtin name.
  51065. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51066. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  51067. */
  51068. hasBuiltin( name, shaderStage = this.shaderStage ) {
  51069. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  51070. }
  51071. /**
  51072. * Returns the vertex index builtin.
  51073. *
  51074. * @return {string} The vertex index.
  51075. */
  51076. getVertexIndex() {
  51077. if ( this.shaderStage === 'vertex' ) {
  51078. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  51079. }
  51080. return 'vertexIndex';
  51081. }
  51082. /**
  51083. * Builds the given shader node.
  51084. *
  51085. * @param {ShaderNodeInternal} shaderNode - The shader node.
  51086. * @return {string} The WGSL function code.
  51087. */
  51088. buildFunctionCode( shaderNode ) {
  51089. const layout = shaderNode.layout;
  51090. const flowData = this.flowShaderNode( shaderNode );
  51091. const parameters = [];
  51092. for ( const input of layout.inputs ) {
  51093. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  51094. }
  51095. //
  51096. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  51097. ${ flowData.vars }
  51098. ${ flowData.code }
  51099. `;
  51100. if ( flowData.result ) {
  51101. code += `\treturn ${ flowData.result };\n`;
  51102. }
  51103. code += '\n}\n';
  51104. //
  51105. return code;
  51106. }
  51107. /**
  51108. * Contextually returns either the vertex stage instance index builtin
  51109. * or the linearized index of an compute invocation within a grid of workgroups.
  51110. *
  51111. * @return {string} The instance index.
  51112. */
  51113. getInstanceIndex() {
  51114. if ( this.shaderStage === 'vertex' ) {
  51115. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  51116. }
  51117. return 'instanceIndex';
  51118. }
  51119. /**
  51120. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  51121. *
  51122. * @return {string} The invocation local index.
  51123. */
  51124. getInvocationLocalIndex() {
  51125. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  51126. }
  51127. /**
  51128. * Returns a builtin representing the size of a subgroup within the current shader.
  51129. *
  51130. * @return {string} The subgroup size.
  51131. */
  51132. getSubgroupSize() {
  51133. this.enableSubGroups();
  51134. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51135. }
  51136. /**
  51137. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  51138. *
  51139. * @return {string} The invocation subgroup index.
  51140. */
  51141. getInvocationSubgroupIndex() {
  51142. this.enableSubGroups();
  51143. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  51144. }
  51145. /**
  51146. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  51147. *
  51148. * @return {string} The subgroup index.
  51149. */
  51150. getSubgroupIndex() {
  51151. this.enableSubGroups();
  51152. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  51153. }
  51154. /**
  51155. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  51156. *
  51157. * @return {null} Null.
  51158. */
  51159. getDrawIndex() {
  51160. return null;
  51161. }
  51162. /**
  51163. * Returns the front facing builtin.
  51164. *
  51165. * @return {string} The front facing builtin.
  51166. */
  51167. getFrontFacing() {
  51168. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  51169. }
  51170. /**
  51171. * Returns the frag coord builtin.
  51172. *
  51173. * @return {string} The frag coord builtin.
  51174. */
  51175. getFragCoord() {
  51176. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  51177. }
  51178. /**
  51179. * Returns the frag depth builtin.
  51180. *
  51181. * @return {string} The frag depth builtin.
  51182. */
  51183. getFragDepth() {
  51184. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  51185. }
  51186. /**
  51187. * Returns the clip distances builtin.
  51188. *
  51189. * @return {string} The clip distances builtin.
  51190. */
  51191. getClipDistance() {
  51192. return 'varyings.hw_clip_distances';
  51193. }
  51194. /**
  51195. * Whether to flip texture data along its vertical axis or not.
  51196. *
  51197. * @return {boolean} Returns always `false` in context of WGSL.
  51198. */
  51199. isFlipY() {
  51200. return false;
  51201. }
  51202. /**
  51203. * Enables the given directive for the given shader stage.
  51204. *
  51205. * @param {string} name - The directive name.
  51206. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  51207. */
  51208. enableDirective( name, shaderStage = this.shaderStage ) {
  51209. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  51210. stage.add( name );
  51211. }
  51212. /**
  51213. * Returns the directives of the given shader stage as a WGSL string.
  51214. *
  51215. * @param {string} shaderStage - The shader stage.
  51216. * @return {string} A WGSL snippet that enables the directives of the given stage.
  51217. */
  51218. getDirectives( shaderStage ) {
  51219. const snippets = [];
  51220. const directives = this.directives[ shaderStage ];
  51221. if ( directives !== undefined ) {
  51222. for ( const directive of directives ) {
  51223. snippets.push( `enable ${directive};` );
  51224. }
  51225. }
  51226. return snippets.join( '\n' );
  51227. }
  51228. /**
  51229. * Enables the 'subgroups' directive.
  51230. */
  51231. enableSubGroups() {
  51232. this.enableDirective( 'subgroups' );
  51233. }
  51234. /**
  51235. * Enables the 'subgroups-f16' directive.
  51236. */
  51237. enableSubgroupsF16() {
  51238. this.enableDirective( 'subgroups-f16' );
  51239. }
  51240. /**
  51241. * Enables the 'clip_distances' directive.
  51242. */
  51243. enableClipDistances() {
  51244. this.enableDirective( 'clip_distances' );
  51245. }
  51246. /**
  51247. * Enables the 'f16' directive.
  51248. */
  51249. enableShaderF16() {
  51250. this.enableDirective( 'f16' );
  51251. }
  51252. /**
  51253. * Enables the 'dual_source_blending' directive.
  51254. */
  51255. enableDualSourceBlending() {
  51256. this.enableDirective( 'dual_source_blending' );
  51257. }
  51258. /**
  51259. * Enables hardware clipping.
  51260. *
  51261. * @param {string} planeCount - The clipping plane count.
  51262. */
  51263. enableHardwareClipping( planeCount ) {
  51264. this.enableClipDistances();
  51265. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  51266. }
  51267. /**
  51268. * Returns the builtins of the given shader stage as a WGSL string.
  51269. *
  51270. * @param {string} shaderStage - The shader stage.
  51271. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  51272. */
  51273. getBuiltins( shaderStage ) {
  51274. const snippets = [];
  51275. const builtins = this.builtins[ shaderStage ];
  51276. if ( builtins !== undefined ) {
  51277. for ( const { name, property, type } of builtins.values() ) {
  51278. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  51279. }
  51280. }
  51281. return snippets.join( ',\n\t' );
  51282. }
  51283. /**
  51284. * This method should be used when a new scoped buffer is used in context of
  51285. * compute shaders. It adds the array to the internal data structure which is
  51286. * later used to generate the respective WGSL.
  51287. *
  51288. * @param {string} name - The array name.
  51289. * @param {string} scope - The scope.
  51290. * @param {string} bufferType - The buffer type.
  51291. * @param {string} bufferCount - The buffer count.
  51292. * @return {string} The array name.
  51293. */
  51294. getScopedArray( name, scope, bufferType, bufferCount ) {
  51295. if ( this.scopedArrays.has( name ) === false ) {
  51296. this.scopedArrays.set( name, {
  51297. name,
  51298. scope,
  51299. bufferType,
  51300. bufferCount
  51301. } );
  51302. }
  51303. return name;
  51304. }
  51305. /**
  51306. * Returns the scoped arrays of the given shader stage as a WGSL string.
  51307. *
  51308. * @param {string} shaderStage - The shader stage.
  51309. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  51310. * Returns `undefined` when used in the vertex or fragment stage.
  51311. */
  51312. getScopedArrays( shaderStage ) {
  51313. if ( shaderStage !== 'compute' ) {
  51314. return;
  51315. }
  51316. const snippets = [];
  51317. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  51318. const type = this.getType( bufferType );
  51319. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  51320. }
  51321. return snippets.join( '\n' );
  51322. }
  51323. /**
  51324. * Returns the shader attributes of the given shader stage as a WGSL string.
  51325. *
  51326. * @param {string} shaderStage - The shader stage.
  51327. * @return {string} The WGSL snippet that defines the shader attributes.
  51328. */
  51329. getAttributes( shaderStage ) {
  51330. const snippets = [];
  51331. if ( shaderStage === 'compute' ) {
  51332. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  51333. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  51334. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  51335. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  51336. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  51337. this.enableDirective( 'subgroups', shaderStage );
  51338. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51339. }
  51340. }
  51341. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  51342. const builtins = this.getBuiltins( 'attribute' );
  51343. if ( builtins ) snippets.push( builtins );
  51344. const attributes = this.getAttributesArray();
  51345. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  51346. const attribute = attributes[ index ];
  51347. const name = attribute.name;
  51348. const type = this.getType( attribute.type );
  51349. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  51350. }
  51351. }
  51352. return snippets.join( ',\n\t' );
  51353. }
  51354. /**
  51355. * Returns the members of the given struct type node as a WGSL string.
  51356. *
  51357. * @param {StructTypeNode} struct - The struct type node.
  51358. * @return {string} The WGSL snippet that defines the struct members.
  51359. */
  51360. getStructMembers( struct ) {
  51361. const snippets = [];
  51362. for ( const member of struct.members ) {
  51363. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  51364. let type = this.getType( member.type );
  51365. if ( member.atomic ) {
  51366. type = 'atomic< ' + type + ' >';
  51367. }
  51368. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  51369. }
  51370. if ( struct.output ) {
  51371. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  51372. }
  51373. return snippets.join( ',\n' );
  51374. }
  51375. /**
  51376. * Returns the structs of the given shader stage as a WGSL string.
  51377. *
  51378. * @param {string} shaderStage - The shader stage.
  51379. * @return {string} The WGSL snippet that defines the structs.
  51380. */
  51381. getStructs( shaderStage ) {
  51382. let result = '';
  51383. const structs = this.structs[ shaderStage ];
  51384. if ( structs.length > 0 ) {
  51385. const snippets = [];
  51386. for ( const struct of structs ) {
  51387. let snippet = `struct ${ struct.name } {\n`;
  51388. snippet += this.getStructMembers( struct );
  51389. snippet += '\n};';
  51390. snippets.push( snippet );
  51391. }
  51392. result = '\n' + snippets.join( '\n\n' ) + '\n';
  51393. }
  51394. return result;
  51395. }
  51396. /**
  51397. * Returns a WGSL string representing a variable.
  51398. *
  51399. * @param {string} type - The variable's type.
  51400. * @param {string} name - The variable's name.
  51401. * @param {?number} [count=null] - The array length.
  51402. * @return {string} The WGSL snippet that defines a variable.
  51403. */
  51404. getVar( type, name, count = null ) {
  51405. let snippet = `var ${ name } : `;
  51406. if ( count !== null ) {
  51407. snippet += this.generateArrayDeclaration( type, count );
  51408. } else {
  51409. snippet += this.getType( type );
  51410. }
  51411. return snippet;
  51412. }
  51413. /**
  51414. * Returns the variables of the given shader stage as a WGSL string.
  51415. *
  51416. * @param {string} shaderStage - The shader stage.
  51417. * @return {string} The WGSL snippet that defines the variables.
  51418. */
  51419. getVars( shaderStage ) {
  51420. const snippets = [];
  51421. const vars = this.vars[ shaderStage ];
  51422. if ( vars !== undefined ) {
  51423. for ( const variable of vars ) {
  51424. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  51425. }
  51426. }
  51427. return `\n${ snippets.join( '\n' ) }\n`;
  51428. }
  51429. /**
  51430. * Returns the varyings of the given shader stage as a WGSL string.
  51431. *
  51432. * @param {string} shaderStage - The shader stage.
  51433. * @return {string} The WGSL snippet that defines the varyings.
  51434. */
  51435. getVaryings( shaderStage ) {
  51436. const snippets = [];
  51437. if ( shaderStage === 'vertex' ) {
  51438. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  51439. }
  51440. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  51441. const varyings = this.varyings;
  51442. const vars = this.vars[ shaderStage ];
  51443. for ( let index = 0; index < varyings.length; index ++ ) {
  51444. const varying = varyings[ index ];
  51445. if ( varying.needsInterpolation ) {
  51446. let attributesSnippet = `@location( ${index} )`;
  51447. if ( varying.interpolationType ) {
  51448. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  51449. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  51450. // Otherwise, optimize interpolation when sensible
  51451. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  51452. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  51453. }
  51454. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  51455. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  51456. vars.push( varying );
  51457. }
  51458. }
  51459. }
  51460. const builtins = this.getBuiltins( shaderStage );
  51461. if ( builtins ) snippets.push( builtins );
  51462. const code = snippets.join( ',\n\t' );
  51463. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  51464. }
  51465. isCustomStruct( nodeUniform ) {
  51466. const attribute = nodeUniform.value;
  51467. const bufferNode = nodeUniform.node;
  51468. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  51469. const isStructArray =
  51470. ( bufferNode.value && bufferNode.value.array ) &&
  51471. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  51472. return isAttributeStructType && ! isStructArray;
  51473. }
  51474. /**
  51475. * Returns the uniforms of the given shader stage as a WGSL string.
  51476. *
  51477. * @param {string} shaderStage - The shader stage.
  51478. * @return {string} The WGSL snippet that defines the uniforms.
  51479. */
  51480. getUniforms( shaderStage ) {
  51481. const uniforms = this.uniforms[ shaderStage ];
  51482. const bindingSnippets = [];
  51483. const bufferSnippets = [];
  51484. const structSnippets = [];
  51485. const uniformGroups = {};
  51486. for ( const uniform of uniforms ) {
  51487. const groupName = uniform.groupNode.name;
  51488. const uniformIndexes = this.bindingsIndexes[ groupName ];
  51489. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  51490. const texture = uniform.node.value;
  51491. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  51492. if ( this.isSampleCompare( texture ) ) {
  51493. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  51494. } else {
  51495. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  51496. }
  51497. }
  51498. let textureType;
  51499. let multisampled = '';
  51500. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51501. if ( primarySamples > 1 ) {
  51502. multisampled = '_multisampled';
  51503. }
  51504. if ( texture.isCubeTexture === true ) {
  51505. textureType = 'texture_cube<f32>';
  51506. } else if ( texture.isDepthTexture === true ) {
  51507. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  51508. textureType = `texture${ multisampled }_2d<f32>`;
  51509. } else {
  51510. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  51511. }
  51512. } else if ( uniform.node.isStorageTextureNode === true ) {
  51513. const format = getFormat( texture );
  51514. const access = this.getStorageAccess( uniform.node, shaderStage );
  51515. const is3D = uniform.node.value.is3DTexture;
  51516. const isArrayTexture = uniform.node.value.isArrayTexture;
  51517. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  51518. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  51519. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  51520. textureType = 'texture_2d_array<f32>';
  51521. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  51522. textureType = 'texture_3d<f32>';
  51523. } else {
  51524. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  51525. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  51526. }
  51527. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  51528. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  51529. const bufferNode = uniform.node;
  51530. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  51531. const bufferCount = bufferNode.bufferCount;
  51532. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  51533. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  51534. if ( this.isCustomStruct( uniform ) ) {
  51535. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  51536. } else {
  51537. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  51538. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  51539. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  51540. }
  51541. } else {
  51542. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  51543. const groupName = uniform.groupNode.name;
  51544. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  51545. index: uniformIndexes.binding ++,
  51546. id: uniformIndexes.group,
  51547. snippets: []
  51548. } );
  51549. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  51550. }
  51551. }
  51552. for ( const name in uniformGroups ) {
  51553. const group = uniformGroups[ name ];
  51554. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  51555. }
  51556. let code = bindingSnippets.join( '\n' );
  51557. code += bufferSnippets.join( '\n' );
  51558. code += structSnippets.join( '\n' );
  51559. return code;
  51560. }
  51561. /**
  51562. * Controls the code build of the shader stages.
  51563. */
  51564. buildCode() {
  51565. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  51566. this.sortBindingGroups();
  51567. for ( const shaderStage in shadersData ) {
  51568. this.shaderStage = shaderStage;
  51569. const stageData = shadersData[ shaderStage ];
  51570. stageData.uniforms = this.getUniforms( shaderStage );
  51571. stageData.attributes = this.getAttributes( shaderStage );
  51572. stageData.varyings = this.getVaryings( shaderStage );
  51573. stageData.structs = this.getStructs( shaderStage );
  51574. stageData.vars = this.getVars( shaderStage );
  51575. stageData.codes = this.getCodes( shaderStage );
  51576. stageData.directives = this.getDirectives( shaderStage );
  51577. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  51578. //
  51579. let flow = '// code\n\n';
  51580. flow += this.flowCode[ shaderStage ];
  51581. const flowNodes = this.flowNodes[ shaderStage ];
  51582. const mainNode = flowNodes[ flowNodes.length - 1 ];
  51583. const outputNode = mainNode.outputNode;
  51584. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  51585. for ( const node of flowNodes ) {
  51586. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  51587. const slotName = node.name;
  51588. if ( slotName ) {
  51589. if ( flow.length > 0 ) flow += '\n';
  51590. flow += `\t// flow -> ${ slotName }\n`;
  51591. }
  51592. flow += `${ flowSlotData.code }\n\t`;
  51593. if ( node === mainNode && shaderStage !== 'compute' ) {
  51594. flow += '// result\n\n\t';
  51595. if ( shaderStage === 'vertex' ) {
  51596. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  51597. } else if ( shaderStage === 'fragment' ) {
  51598. if ( isOutputStruct ) {
  51599. stageData.returnType = outputNode.getNodeType( this );
  51600. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  51601. flow += `return ${ flowSlotData.result };`;
  51602. } else {
  51603. let structSnippet = '\t@location(0) color: vec4<f32>';
  51604. const builtins = this.getBuiltins( 'output' );
  51605. if ( builtins ) structSnippet += ',\n\t' + builtins;
  51606. stageData.returnType = 'OutputStruct';
  51607. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  51608. stageData.structs += '\nvar<private> output : OutputStruct;';
  51609. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  51610. }
  51611. }
  51612. }
  51613. }
  51614. stageData.flow = flow;
  51615. }
  51616. this.shaderStage = null;
  51617. if ( this.material !== null ) {
  51618. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  51619. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  51620. } else {
  51621. // Early strictly validated in computeNode
  51622. const workgroupSize = this.object.workgroupSize;
  51623. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  51624. }
  51625. }
  51626. /**
  51627. * Returns the native shader method name for a given generic name.
  51628. *
  51629. * @param {string} method - The method name to resolve.
  51630. * @param {?string} [output=null] - An optional output.
  51631. * @return {string} The resolved WGSL method name.
  51632. */
  51633. getMethod( method, output = null ) {
  51634. let wgslMethod;
  51635. if ( output !== null ) {
  51636. wgslMethod = this._getWGSLMethod( method + '_' + output );
  51637. }
  51638. if ( wgslMethod === undefined ) {
  51639. wgslMethod = this._getWGSLMethod( method );
  51640. }
  51641. return wgslMethod || method;
  51642. }
  51643. /**
  51644. * Returns the bitcast method name for a given input and outputType.
  51645. *
  51646. * @param {string} type - The output type to bitcast to.
  51647. * @return {string} The resolved WGSL bitcast invocation.
  51648. */
  51649. getBitcastMethod( type ) {
  51650. const dataType = this.getType( type );
  51651. return `bitcast<${ dataType }>`;
  51652. }
  51653. /**
  51654. * Returns the native snippet for a ternary operation.
  51655. *
  51656. * @param {string} condSnippet - The condition determining which expression gets resolved.
  51657. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  51658. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  51659. * @return {string} The resolved method name.
  51660. */
  51661. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  51662. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  51663. }
  51664. /**
  51665. * Returns the WGSL type of the given node data type.
  51666. *
  51667. * @param {string} type - The node data type.
  51668. * @return {string} The WGSL type.
  51669. */
  51670. getType( type ) {
  51671. return wgslTypeLib[ type ] || type;
  51672. }
  51673. /**
  51674. * Whether the requested feature is available or not.
  51675. *
  51676. * @param {string} name - The requested feature.
  51677. * @return {boolean} Whether the requested feature is supported or not.
  51678. */
  51679. isAvailable( name ) {
  51680. let result = supports[ name ];
  51681. if ( result === undefined ) {
  51682. if ( name === 'float32Filterable' ) {
  51683. result = this.renderer.hasFeature( 'float32-filterable' );
  51684. } else if ( name === 'clipDistance' ) {
  51685. result = this.renderer.hasFeature( 'clip-distances' );
  51686. }
  51687. supports[ name ] = result;
  51688. }
  51689. return result;
  51690. }
  51691. /**
  51692. * Returns the native shader method name for a given generic name.
  51693. *
  51694. * @private
  51695. * @param {string} method - The method name to resolve.
  51696. * @return {string} The resolved WGSL method name.
  51697. */
  51698. _getWGSLMethod( method ) {
  51699. if ( wgslPolyfill[ method ] !== undefined ) {
  51700. this._include( method );
  51701. }
  51702. return wgslMethods[ method ];
  51703. }
  51704. /**
  51705. * Includes the given method name into the current
  51706. * function node.
  51707. *
  51708. * @private
  51709. * @param {string} name - The method name to include.
  51710. * @return {CodeNode} The respective code node.
  51711. */
  51712. _include( name ) {
  51713. const codeNode = wgslPolyfill[ name ];
  51714. codeNode.build( this );
  51715. this.addInclude( codeNode );
  51716. return codeNode;
  51717. }
  51718. /**
  51719. * Returns a WGSL vertex shader based on the given shader data.
  51720. *
  51721. * @private
  51722. * @param {Object} shaderData - The shader data.
  51723. * @return {string} The vertex shader.
  51724. */
  51725. _getWGSLVertexCode( shaderData ) {
  51726. return `${ this.getSignature() }
  51727. // directives
  51728. ${shaderData.directives}
  51729. // structs
  51730. ${shaderData.structs}
  51731. // uniforms
  51732. ${shaderData.uniforms}
  51733. // varyings
  51734. ${shaderData.varyings}
  51735. var<private> varyings : VaryingsStruct;
  51736. // codes
  51737. ${shaderData.codes}
  51738. @vertex
  51739. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  51740. // vars
  51741. ${shaderData.vars}
  51742. // flow
  51743. ${shaderData.flow}
  51744. return varyings;
  51745. }
  51746. `;
  51747. }
  51748. /**
  51749. * Returns a WGSL fragment shader based on the given shader data.
  51750. *
  51751. * @private
  51752. * @param {Object} shaderData - The shader data.
  51753. * @return {string} The vertex shader.
  51754. */
  51755. _getWGSLFragmentCode( shaderData ) {
  51756. return `${ this.getSignature() }
  51757. // global
  51758. ${ diagnostics }
  51759. // structs
  51760. ${shaderData.structs}
  51761. // uniforms
  51762. ${shaderData.uniforms}
  51763. // codes
  51764. ${shaderData.codes}
  51765. @fragment
  51766. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  51767. // vars
  51768. ${shaderData.vars}
  51769. // flow
  51770. ${shaderData.flow}
  51771. }
  51772. `;
  51773. }
  51774. /**
  51775. * Returns a WGSL compute shader based on the given shader data.
  51776. *
  51777. * @private
  51778. * @param {Object} shaderData - The shader data.
  51779. * @param {string} workgroupSize - The workgroup size.
  51780. * @return {string} The vertex shader.
  51781. */
  51782. _getWGSLComputeCode( shaderData, workgroupSize ) {
  51783. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  51784. return `${ this.getSignature() }
  51785. // directives
  51786. ${ shaderData.directives }
  51787. // system
  51788. var<private> instanceIndex : u32;
  51789. // locals
  51790. ${ shaderData.scopedArrays }
  51791. // structs
  51792. ${ shaderData.structs }
  51793. // uniforms
  51794. ${ shaderData.uniforms }
  51795. // codes
  51796. ${ shaderData.codes }
  51797. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  51798. fn main( ${ shaderData.attributes } ) {
  51799. // system
  51800. instanceIndex = globalId.x
  51801. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  51802. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  51803. // vars
  51804. ${ shaderData.vars }
  51805. // flow
  51806. ${ shaderData.flow }
  51807. }
  51808. `;
  51809. }
  51810. /**
  51811. * Returns a WGSL struct based on the given name and variables.
  51812. *
  51813. * @private
  51814. * @param {string} name - The struct name.
  51815. * @param {string} vars - The struct variables.
  51816. * @return {string} The WGSL snippet representing a struct.
  51817. */
  51818. _getWGSLStruct( name, vars ) {
  51819. return `
  51820. struct ${name} {
  51821. ${vars}
  51822. };`;
  51823. }
  51824. /**
  51825. * Returns a WGSL struct binding.
  51826. *
  51827. * @private
  51828. * @param {string} name - The struct name.
  51829. * @param {string} vars - The struct variables.
  51830. * @param {string} access - The access.
  51831. * @param {number} [binding=0] - The binding index.
  51832. * @param {number} [group=0] - The group index.
  51833. * @return {string} The WGSL snippet representing a struct binding.
  51834. */
  51835. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  51836. const structName = name + 'Struct';
  51837. const structSnippet = this._getWGSLStruct( structName, vars );
  51838. return `${structSnippet}
  51839. @binding( ${ binding } ) @group( ${ group } )
  51840. var<${access}> ${ name } : ${ structName };`;
  51841. }
  51842. }
  51843. /**
  51844. * A WebGPU backend utility module with common helpers.
  51845. *
  51846. * @private
  51847. */
  51848. class WebGPUUtils {
  51849. /**
  51850. * Constructs a new utility object.
  51851. *
  51852. * @param {WebGPUBackend} backend - The WebGPU backend.
  51853. */
  51854. constructor( backend ) {
  51855. /**
  51856. * A reference to the WebGPU backend.
  51857. *
  51858. * @type {WebGPUBackend}
  51859. */
  51860. this.backend = backend;
  51861. }
  51862. /**
  51863. * Returns the depth/stencil GPU format for the given render context.
  51864. *
  51865. * @param {RenderContext} renderContext - The render context.
  51866. * @return {string} The depth/stencil GPU texture format.
  51867. */
  51868. getCurrentDepthStencilFormat( renderContext ) {
  51869. let format;
  51870. if ( renderContext.depthTexture !== null ) {
  51871. format = this.getTextureFormatGPU( renderContext.depthTexture );
  51872. } else if ( renderContext.depth && renderContext.stencil ) {
  51873. format = GPUTextureFormat.Depth24PlusStencil8;
  51874. } else if ( renderContext.depth ) {
  51875. format = GPUTextureFormat.Depth24Plus;
  51876. }
  51877. return format;
  51878. }
  51879. /**
  51880. * Returns the GPU format for the given texture.
  51881. *
  51882. * @param {Texture} texture - The texture.
  51883. * @return {string} The GPU texture format.
  51884. */
  51885. getTextureFormatGPU( texture ) {
  51886. return this.backend.get( texture ).format;
  51887. }
  51888. /**
  51889. * Returns an object that defines the multi-sampling state of the given texture.
  51890. *
  51891. * @param {Texture} texture - The texture.
  51892. * @return {Object} The multi-sampling state.
  51893. */
  51894. getTextureSampleData( texture ) {
  51895. let samples;
  51896. if ( texture.isFramebufferTexture ) {
  51897. samples = 1;
  51898. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  51899. const renderer = this.backend.renderer;
  51900. const renderTarget = renderer.getRenderTarget();
  51901. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  51902. } else if ( texture.renderTarget ) {
  51903. samples = texture.renderTarget.samples;
  51904. }
  51905. samples = samples || 1;
  51906. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  51907. const primarySamples = isMSAA ? 1 : samples;
  51908. return { samples, primarySamples, isMSAA };
  51909. }
  51910. /**
  51911. * Returns the default color attachment's GPU format of the current render context.
  51912. *
  51913. * @param {RenderContext} renderContext - The render context.
  51914. * @return {string} The GPU texture format of the default color attachment.
  51915. */
  51916. getCurrentColorFormat( renderContext ) {
  51917. let format;
  51918. if ( renderContext.textures !== null ) {
  51919. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  51920. } else {
  51921. format = this.getPreferredCanvasFormat(); // default context format
  51922. }
  51923. return format;
  51924. }
  51925. /**
  51926. * Returns the GPU formats of all color attachments of the current render context.
  51927. *
  51928. * @param {RenderContext} renderContext - The render context.
  51929. * @return {Array<string>} The GPU texture formats of all color attachments.
  51930. */
  51931. getCurrentColorFormats( renderContext ) {
  51932. if ( renderContext.textures !== null ) {
  51933. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  51934. } else {
  51935. return [ this.getPreferredCanvasFormat() ]; // default context format
  51936. }
  51937. }
  51938. /**
  51939. * Returns the output color space of the current render context.
  51940. *
  51941. * @param {RenderContext} renderContext - The render context.
  51942. * @return {string} The output color space.
  51943. */
  51944. getCurrentColorSpace( renderContext ) {
  51945. if ( renderContext.textures !== null ) {
  51946. return renderContext.textures[ 0 ].colorSpace;
  51947. }
  51948. return this.backend.renderer.outputColorSpace;
  51949. }
  51950. /**
  51951. * Returns GPU primitive topology for the given object and material.
  51952. *
  51953. * @param {Object3D} object - The 3D object.
  51954. * @param {Material} material - The material.
  51955. * @return {string} The GPU primitive topology.
  51956. */
  51957. getPrimitiveTopology( object, material ) {
  51958. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  51959. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  51960. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  51961. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  51962. }
  51963. /**
  51964. * Returns a modified sample count from the given sample count value.
  51965. *
  51966. * That is required since WebGPU only supports either 1 or 4.
  51967. *
  51968. * @param {number} sampleCount - The input sample count.
  51969. * @return {number} The (potentially updated) output sample count.
  51970. */
  51971. getSampleCount( sampleCount ) {
  51972. return sampleCount >= 4 ? 4 : 1;
  51973. }
  51974. /**
  51975. * Returns the sample count of the given render context.
  51976. *
  51977. * @param {RenderContext} renderContext - The render context.
  51978. * @return {number} The sample count.
  51979. */
  51980. getSampleCountRenderContext( renderContext ) {
  51981. if ( renderContext.textures !== null ) {
  51982. return this.getSampleCount( renderContext.sampleCount );
  51983. }
  51984. return this.getSampleCount( this.backend.renderer.currentSamples );
  51985. }
  51986. /**
  51987. * Returns the preferred canvas format.
  51988. *
  51989. * There is a separate method for this so it's possible to
  51990. * honor edge cases for specific devices.
  51991. *
  51992. * @return {string} The GPU texture format of the canvas.
  51993. */
  51994. getPreferredCanvasFormat() {
  51995. const outputType = this.backend.parameters.outputType;
  51996. if ( outputType === undefined ) {
  51997. return navigator.gpu.getPreferredCanvasFormat();
  51998. } else if ( outputType === UnsignedByteType ) {
  51999. return GPUTextureFormat.BGRA8Unorm;
  52000. } else if ( outputType === HalfFloatType ) {
  52001. return GPUTextureFormat.RGBA16Float;
  52002. } else {
  52003. throw new Error( 'Unsupported outputType' );
  52004. }
  52005. }
  52006. }
  52007. const typedArraysToVertexFormatPrefix = new Map( [
  52008. [ Int8Array, [ 'sint8', 'snorm8' ]],
  52009. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  52010. [ Int16Array, [ 'sint16', 'snorm16' ]],
  52011. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  52012. [ Int32Array, [ 'sint32', 'snorm32' ]],
  52013. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  52014. [ Float32Array, [ 'float32', ]],
  52015. ] );
  52016. if ( typeof Float16Array !== 'undefined' ) {
  52017. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  52018. }
  52019. const typedAttributeToVertexFormatPrefix = new Map( [
  52020. [ Float16BufferAttribute, [ 'float16', ]],
  52021. ] );
  52022. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  52023. [ Int32Array, 'sint32' ],
  52024. [ Int16Array, 'sint32' ], // patch for INT16
  52025. [ Uint32Array, 'uint32' ],
  52026. [ Uint16Array, 'uint32' ], // patch for UINT16
  52027. [ Float32Array, 'float32' ]
  52028. ] );
  52029. /**
  52030. * A WebGPU backend utility module for managing shader attributes.
  52031. *
  52032. * @private
  52033. */
  52034. class WebGPUAttributeUtils {
  52035. /**
  52036. * Constructs a new utility object.
  52037. *
  52038. * @param {WebGPUBackend} backend - The WebGPU backend.
  52039. */
  52040. constructor( backend ) {
  52041. /**
  52042. * A reference to the WebGPU backend.
  52043. *
  52044. * @type {WebGPUBackend}
  52045. */
  52046. this.backend = backend;
  52047. }
  52048. /**
  52049. * Creates the GPU buffer for the given buffer attribute.
  52050. *
  52051. * @param {BufferAttribute} attribute - The buffer attribute.
  52052. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  52053. */
  52054. createAttribute( attribute, usage ) {
  52055. const bufferAttribute = this._getBufferAttribute( attribute );
  52056. const backend = this.backend;
  52057. const bufferData = backend.get( bufferAttribute );
  52058. let buffer = bufferData.buffer;
  52059. if ( buffer === undefined ) {
  52060. const device = backend.device;
  52061. let array = bufferAttribute.array;
  52062. // patch for INT16 and UINT16
  52063. if ( attribute.normalized === false ) {
  52064. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  52065. array = new Int32Array( array );
  52066. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  52067. array = new Uint32Array( array );
  52068. if ( usage & GPUBufferUsage.INDEX ) {
  52069. for ( let i = 0; i < array.length; i ++ ) {
  52070. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  52071. }
  52072. }
  52073. }
  52074. }
  52075. bufferAttribute.array = array;
  52076. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  52077. array = new array.constructor( bufferAttribute.count * 4 );
  52078. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52079. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52080. }
  52081. // Update BufferAttribute
  52082. bufferAttribute.itemSize = 4;
  52083. bufferAttribute.array = array;
  52084. bufferData._force3to4BytesAlignment = true;
  52085. }
  52086. // ensure 4 byte alignment
  52087. const byteLength = array.byteLength;
  52088. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  52089. buffer = device.createBuffer( {
  52090. label: bufferAttribute.name,
  52091. size: size,
  52092. usage: usage,
  52093. mappedAtCreation: true
  52094. } );
  52095. new array.constructor( buffer.getMappedRange() ).set( array );
  52096. buffer.unmap();
  52097. bufferData.buffer = buffer;
  52098. }
  52099. }
  52100. /**
  52101. * Updates the GPU buffer of the given buffer attribute.
  52102. *
  52103. * @param {BufferAttribute} attribute - The buffer attribute.
  52104. */
  52105. updateAttribute( attribute ) {
  52106. const bufferAttribute = this._getBufferAttribute( attribute );
  52107. const backend = this.backend;
  52108. const device = backend.device;
  52109. const bufferData = backend.get( bufferAttribute );
  52110. const buffer = backend.get( bufferAttribute ).buffer;
  52111. let array = bufferAttribute.array;
  52112. // if storage buffer ensure 4 byte alignment
  52113. if ( bufferData._force3to4BytesAlignment === true ) {
  52114. array = new array.constructor( bufferAttribute.count * 4 );
  52115. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52116. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52117. }
  52118. bufferAttribute.array = array;
  52119. }
  52120. const isTypedArray = this._isTypedArray( array );
  52121. const updateRanges = bufferAttribute.updateRanges;
  52122. if ( updateRanges.length === 0 ) {
  52123. // Not using update ranges
  52124. device.queue.writeBuffer(
  52125. buffer,
  52126. 0,
  52127. array,
  52128. 0
  52129. );
  52130. } else {
  52131. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  52132. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52133. const range = updateRanges[ i ];
  52134. let dataOffset, size;
  52135. if ( bufferData._force3to4BytesAlignment === true ) {
  52136. const vertexStart = Math.floor( range.start / 3 );
  52137. const vertexCount = Math.ceil( range.count / 3 );
  52138. dataOffset = vertexStart * 4 * byteOffsetFactor;
  52139. size = vertexCount * 4 * byteOffsetFactor;
  52140. } else {
  52141. dataOffset = range.start * byteOffsetFactor;
  52142. size = range.count * byteOffsetFactor;
  52143. }
  52144. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52145. device.queue.writeBuffer(
  52146. buffer,
  52147. bufferOffset,
  52148. array,
  52149. dataOffset,
  52150. size
  52151. );
  52152. }
  52153. bufferAttribute.clearUpdateRanges();
  52154. }
  52155. }
  52156. /**
  52157. * This method creates the vertex buffer layout data which are
  52158. * require when creating a render pipeline for the given render object.
  52159. *
  52160. * @param {RenderObject} renderObject - The render object.
  52161. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  52162. */
  52163. createShaderVertexBuffers( renderObject ) {
  52164. const attributes = renderObject.getAttributes();
  52165. const vertexBuffers = new Map();
  52166. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  52167. const geometryAttribute = attributes[ slot ];
  52168. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  52169. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  52170. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  52171. if ( vertexBufferLayout === undefined ) {
  52172. let arrayStride, stepMode;
  52173. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  52174. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  52175. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52176. } else {
  52177. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  52178. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52179. }
  52180. // patch for INT16 and UINT16
  52181. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  52182. arrayStride = 4;
  52183. }
  52184. vertexBufferLayout = {
  52185. arrayStride,
  52186. attributes: [],
  52187. stepMode
  52188. };
  52189. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  52190. }
  52191. const format = this._getVertexFormat( geometryAttribute );
  52192. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  52193. vertexBufferLayout.attributes.push( {
  52194. shaderLocation: slot,
  52195. offset,
  52196. format
  52197. } );
  52198. }
  52199. return Array.from( vertexBuffers.values() );
  52200. }
  52201. /**
  52202. * Destroys the GPU buffer of the given buffer attribute.
  52203. *
  52204. * @param {BufferAttribute} attribute - The buffer attribute.
  52205. */
  52206. destroyAttribute( attribute ) {
  52207. const backend = this.backend;
  52208. const data = backend.get( this._getBufferAttribute( attribute ) );
  52209. data.buffer.destroy();
  52210. backend.delete( attribute );
  52211. }
  52212. /**
  52213. * This method performs a readback operation by moving buffer data from
  52214. * a storage buffer attribute from the GPU to the CPU.
  52215. *
  52216. * @async
  52217. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52218. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52219. */
  52220. async getArrayBufferAsync( attribute ) {
  52221. const backend = this.backend;
  52222. const device = backend.device;
  52223. const data = backend.get( this._getBufferAttribute( attribute ) );
  52224. const bufferGPU = data.buffer;
  52225. const size = bufferGPU.size;
  52226. const readBufferGPU = device.createBuffer( {
  52227. label: `${ attribute.name }_readback`,
  52228. size,
  52229. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52230. } );
  52231. const cmdEncoder = device.createCommandEncoder( {
  52232. label: `readback_encoder_${ attribute.name }`
  52233. } );
  52234. cmdEncoder.copyBufferToBuffer(
  52235. bufferGPU,
  52236. 0,
  52237. readBufferGPU,
  52238. 0,
  52239. size
  52240. );
  52241. const gpuCommands = cmdEncoder.finish();
  52242. device.queue.submit( [ gpuCommands ] );
  52243. await readBufferGPU.mapAsync( GPUMapMode.READ );
  52244. const arrayBuffer = readBufferGPU.getMappedRange();
  52245. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  52246. readBufferGPU.unmap();
  52247. return dstBuffer.buffer;
  52248. }
  52249. /**
  52250. * Returns the vertex format of the given buffer attribute.
  52251. *
  52252. * @private
  52253. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  52254. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  52255. */
  52256. _getVertexFormat( geometryAttribute ) {
  52257. const { itemSize, normalized } = geometryAttribute;
  52258. const ArrayType = geometryAttribute.array.constructor;
  52259. const AttributeType = geometryAttribute.constructor;
  52260. let format;
  52261. if ( itemSize === 1 ) {
  52262. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  52263. } else {
  52264. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  52265. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  52266. if ( prefix ) {
  52267. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  52268. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  52269. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  52270. if ( paddedItemSize % 1 ) {
  52271. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  52272. }
  52273. format = `${prefix}x${paddedItemSize}`;
  52274. }
  52275. }
  52276. if ( ! format ) {
  52277. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  52278. }
  52279. return format;
  52280. }
  52281. /**
  52282. * Returns `true` if the given array is a typed array.
  52283. *
  52284. * @private
  52285. * @param {any} array - The array.
  52286. * @return {boolean} Whether the given array is a typed array or not.
  52287. */
  52288. _isTypedArray( array ) {
  52289. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  52290. }
  52291. /**
  52292. * Utility method for handling interleaved buffer attributes correctly.
  52293. * To process them, their `InterleavedBuffer` is returned.
  52294. *
  52295. * @private
  52296. * @param {BufferAttribute} attribute - The attribute.
  52297. * @return {BufferAttribute|InterleavedBuffer}
  52298. */
  52299. _getBufferAttribute( attribute ) {
  52300. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  52301. return attribute;
  52302. }
  52303. }
  52304. /**
  52305. * A WebGPU backend utility module for managing bindings.
  52306. *
  52307. * When reading the documentation it's helpful to keep in mind that
  52308. * all class definitions starting with 'GPU*' are modules from the
  52309. * WebGPU API. So for example `BindGroup` is a class from the engine
  52310. * whereas `GPUBindGroup` is a class from WebGPU.
  52311. *
  52312. * @private
  52313. */
  52314. class WebGPUBindingUtils {
  52315. /**
  52316. * Constructs a new utility object.
  52317. *
  52318. * @param {WebGPUBackend} backend - The WebGPU backend.
  52319. */
  52320. constructor( backend ) {
  52321. /**
  52322. * A reference to the WebGPU backend.
  52323. *
  52324. * @type {WebGPUBackend}
  52325. */
  52326. this.backend = backend;
  52327. /**
  52328. * A cache for managing bind group layouts.
  52329. *
  52330. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  52331. */
  52332. this.bindGroupLayoutCache = new WeakMap();
  52333. }
  52334. /**
  52335. * Creates a GPU bind group layout for the given bind group.
  52336. *
  52337. * @param {BindGroup} bindGroup - The bind group.
  52338. * @return {GPUBindGroupLayout} The GPU bind group layout.
  52339. */
  52340. createBindingsLayout( bindGroup ) {
  52341. const backend = this.backend;
  52342. const device = backend.device;
  52343. const entries = [];
  52344. let index = 0;
  52345. for ( const binding of bindGroup.bindings ) {
  52346. const bindingGPU = {
  52347. binding: index ++,
  52348. visibility: binding.visibility
  52349. };
  52350. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  52351. const buffer = {}; // GPUBufferBindingLayout
  52352. if ( binding.isStorageBuffer ) {
  52353. if ( binding.visibility & 4 ) {
  52354. // compute
  52355. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  52356. buffer.type = GPUBufferBindingType.Storage;
  52357. } else {
  52358. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52359. }
  52360. } else {
  52361. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52362. }
  52363. }
  52364. bindingGPU.buffer = buffer;
  52365. } else if ( binding.isSampledTexture && binding.store ) {
  52366. const storageTexture = {}; // GPUStorageTextureBindingLayout
  52367. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  52368. const access = binding.access;
  52369. if ( access === NodeAccess.READ_WRITE ) {
  52370. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  52371. } else if ( access === NodeAccess.WRITE_ONLY ) {
  52372. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  52373. } else {
  52374. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  52375. }
  52376. if ( binding.texture.isArrayTexture ) {
  52377. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52378. } else if ( binding.texture.is3DTexture ) {
  52379. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  52380. }
  52381. bindingGPU.storageTexture = storageTexture;
  52382. } else if ( binding.isSampledTexture ) {
  52383. const texture = {}; // GPUTextureBindingLayout
  52384. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  52385. if ( primarySamples > 1 ) {
  52386. texture.multisampled = true;
  52387. if ( ! binding.texture.isDepthTexture ) {
  52388. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52389. }
  52390. }
  52391. if ( binding.texture.isDepthTexture ) {
  52392. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  52393. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52394. } else {
  52395. texture.sampleType = GPUTextureSampleType.Depth;
  52396. }
  52397. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  52398. const type = binding.texture.type;
  52399. if ( type === IntType ) {
  52400. texture.sampleType = GPUTextureSampleType.SInt;
  52401. } else if ( type === UnsignedIntType ) {
  52402. texture.sampleType = GPUTextureSampleType.UInt;
  52403. } else if ( type === FloatType ) {
  52404. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  52405. texture.sampleType = GPUTextureSampleType.Float;
  52406. } else {
  52407. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52408. }
  52409. }
  52410. }
  52411. if ( binding.isSampledCubeTexture ) {
  52412. texture.viewDimension = GPUTextureViewDimension.Cube;
  52413. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52414. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52415. } else if ( binding.isSampledTexture3D ) {
  52416. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  52417. }
  52418. bindingGPU.texture = texture;
  52419. } else if ( binding.isSampler ) {
  52420. const sampler = {}; // GPUSamplerBindingLayout
  52421. if ( binding.texture.isDepthTexture ) {
  52422. if ( binding.texture.compareFunction !== null ) {
  52423. sampler.type = GPUSamplerBindingType.Comparison;
  52424. } else if ( backend.compatibilityMode ) {
  52425. sampler.type = GPUSamplerBindingType.NonFiltering;
  52426. }
  52427. }
  52428. bindingGPU.sampler = sampler;
  52429. } else {
  52430. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  52431. }
  52432. entries.push( bindingGPU );
  52433. }
  52434. return device.createBindGroupLayout( { entries } );
  52435. }
  52436. /**
  52437. * Creates bindings from the given bind group definition.
  52438. *
  52439. * @param {BindGroup} bindGroup - The bind group.
  52440. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52441. * @param {number} cacheIndex - The cache index.
  52442. * @param {number} version - The version.
  52443. */
  52444. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  52445. const { backend, bindGroupLayoutCache } = this;
  52446. const bindingsData = backend.get( bindGroup );
  52447. // setup (static) binding layout and (dynamic) binding group
  52448. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  52449. if ( bindLayoutGPU === undefined ) {
  52450. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  52451. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  52452. }
  52453. let bindGroupGPU;
  52454. if ( cacheIndex > 0 ) {
  52455. if ( bindingsData.groups === undefined ) {
  52456. bindingsData.groups = [];
  52457. bindingsData.versions = [];
  52458. }
  52459. if ( bindingsData.versions[ cacheIndex ] === version ) {
  52460. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  52461. }
  52462. }
  52463. if ( bindGroupGPU === undefined ) {
  52464. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  52465. if ( cacheIndex > 0 ) {
  52466. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  52467. bindingsData.versions[ cacheIndex ] = version;
  52468. }
  52469. }
  52470. bindingsData.group = bindGroupGPU;
  52471. bindingsData.layout = bindLayoutGPU;
  52472. }
  52473. /**
  52474. * Updates a buffer binding.
  52475. *
  52476. * @param {Buffer} binding - The buffer binding to update.
  52477. */
  52478. updateBinding( binding ) {
  52479. const backend = this.backend;
  52480. const device = backend.device;
  52481. const buffer = binding.buffer;
  52482. const bufferGPU = backend.get( binding ).buffer;
  52483. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  52484. }
  52485. /**
  52486. * Creates a GPU bind group for the camera index.
  52487. *
  52488. * @param {Uint32Array} data - The index data.
  52489. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  52490. * @return {GPUBindGroup} The GPU bind group.
  52491. */
  52492. createBindGroupIndex( data, layout ) {
  52493. const backend = this.backend;
  52494. const device = backend.device;
  52495. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52496. const index = data[ 0 ];
  52497. const buffer = device.createBuffer( {
  52498. label: 'bindingCameraIndex_' + index,
  52499. size: 16, // uint(4) * 4
  52500. usage: usage
  52501. } );
  52502. device.queue.writeBuffer( buffer, 0, data, 0 );
  52503. const entries = [ { binding: 0, resource: { buffer } } ];
  52504. return device.createBindGroup( {
  52505. label: 'bindGroupCameraIndex_' + index,
  52506. layout,
  52507. entries
  52508. } );
  52509. }
  52510. /**
  52511. * Creates a GPU bind group for the given bind group and GPU layout.
  52512. *
  52513. * @param {BindGroup} bindGroup - The bind group.
  52514. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  52515. * @return {GPUBindGroup} The GPU bind group.
  52516. */
  52517. createBindGroup( bindGroup, layoutGPU ) {
  52518. const backend = this.backend;
  52519. const device = backend.device;
  52520. let bindingPoint = 0;
  52521. const entriesGPU = [];
  52522. for ( const binding of bindGroup.bindings ) {
  52523. if ( binding.isUniformBuffer ) {
  52524. const bindingData = backend.get( binding );
  52525. if ( bindingData.buffer === undefined ) {
  52526. const byteLength = binding.byteLength;
  52527. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52528. const bufferGPU = device.createBuffer( {
  52529. label: 'bindingBuffer_' + binding.name,
  52530. size: byteLength,
  52531. usage: usage
  52532. } );
  52533. bindingData.buffer = bufferGPU;
  52534. }
  52535. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52536. } else if ( binding.isStorageBuffer ) {
  52537. const bindingData = backend.get( binding );
  52538. if ( bindingData.buffer === undefined ) {
  52539. const attribute = binding.attribute;
  52540. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  52541. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  52542. bindingData.buffer = backend.get( attribute ).buffer;
  52543. }
  52544. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52545. } else if ( binding.isSampledTexture ) {
  52546. const textureData = backend.get( binding.texture );
  52547. let resourceGPU;
  52548. if ( textureData.externalTexture !== undefined ) {
  52549. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  52550. } else {
  52551. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  52552. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  52553. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  52554. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  52555. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  52556. }
  52557. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  52558. resourceGPU = textureData[ propertyName ];
  52559. if ( resourceGPU === undefined ) {
  52560. const aspectGPU = GPUTextureAspect.All;
  52561. let dimensionViewGPU;
  52562. if ( binding.isSampledCubeTexture ) {
  52563. dimensionViewGPU = GPUTextureViewDimension.Cube;
  52564. } else if ( binding.isSampledTexture3D ) {
  52565. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  52566. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52567. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  52568. } else {
  52569. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  52570. }
  52571. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  52572. }
  52573. }
  52574. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  52575. } else if ( binding.isSampler ) {
  52576. const textureGPU = backend.get( binding.texture );
  52577. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  52578. }
  52579. bindingPoint ++;
  52580. }
  52581. return device.createBindGroup( {
  52582. label: 'bindGroup_' + bindGroup.name,
  52583. layout: layoutGPU,
  52584. entries: entriesGPU
  52585. } );
  52586. }
  52587. }
  52588. /**
  52589. * A WebGPU backend utility module for managing pipelines.
  52590. *
  52591. * @private
  52592. */
  52593. class WebGPUPipelineUtils {
  52594. /**
  52595. * Constructs a new utility object.
  52596. *
  52597. * @param {WebGPUBackend} backend - The WebGPU backend.
  52598. */
  52599. constructor( backend ) {
  52600. /**
  52601. * A reference to the WebGPU backend.
  52602. *
  52603. * @type {WebGPUBackend}
  52604. */
  52605. this.backend = backend;
  52606. /**
  52607. * A Weak Map that tracks the active pipeline for render or compute passes.
  52608. *
  52609. * @private
  52610. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  52611. */
  52612. this._activePipelines = new WeakMap();
  52613. }
  52614. /**
  52615. * Sets the given pipeline for the given pass. The method makes sure to only set the
  52616. * pipeline when necessary.
  52617. *
  52618. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  52619. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  52620. */
  52621. setPipeline( pass, pipeline ) {
  52622. const currentPipeline = this._activePipelines.get( pass );
  52623. if ( currentPipeline !== pipeline ) {
  52624. pass.setPipeline( pipeline );
  52625. this._activePipelines.set( pass, pipeline );
  52626. }
  52627. }
  52628. /**
  52629. * Returns the sample count derived from the given render context.
  52630. *
  52631. * @private
  52632. * @param {RenderContext} renderContext - The render context.
  52633. * @return {number} The sample count.
  52634. */
  52635. _getSampleCount( renderContext ) {
  52636. return this.backend.utils.getSampleCountRenderContext( renderContext );
  52637. }
  52638. /**
  52639. * Creates a render pipeline for the given render object.
  52640. *
  52641. * @param {RenderObject} renderObject - The render object.
  52642. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52643. */
  52644. createRenderPipeline( renderObject, promises ) {
  52645. const { object, material, geometry, pipeline } = renderObject;
  52646. const { vertexProgram, fragmentProgram } = pipeline;
  52647. const backend = this.backend;
  52648. const device = backend.device;
  52649. const utils = backend.utils;
  52650. const pipelineData = backend.get( pipeline );
  52651. // bind group layouts
  52652. const bindGroupLayouts = [];
  52653. for ( const bindGroup of renderObject.getBindings() ) {
  52654. const bindingsData = backend.get( bindGroup );
  52655. bindGroupLayouts.push( bindingsData.layout );
  52656. }
  52657. // vertex buffers
  52658. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  52659. // blending
  52660. let blending;
  52661. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  52662. blending = this._getBlending( material );
  52663. }
  52664. // stencil
  52665. let stencilFront = {};
  52666. if ( material.stencilWrite === true ) {
  52667. stencilFront = {
  52668. compare: this._getStencilCompare( material ),
  52669. failOp: this._getStencilOperation( material.stencilFail ),
  52670. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  52671. passOp: this._getStencilOperation( material.stencilZPass )
  52672. };
  52673. }
  52674. const colorWriteMask = this._getColorWriteMask( material );
  52675. const targets = [];
  52676. if ( renderObject.context.textures !== null ) {
  52677. const textures = renderObject.context.textures;
  52678. for ( let i = 0; i < textures.length; i ++ ) {
  52679. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  52680. targets.push( {
  52681. format: colorFormat,
  52682. blend: blending,
  52683. writeMask: colorWriteMask
  52684. } );
  52685. }
  52686. } else {
  52687. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52688. targets.push( {
  52689. format: colorFormat,
  52690. blend: blending,
  52691. writeMask: colorWriteMask
  52692. } );
  52693. }
  52694. const vertexModule = backend.get( vertexProgram ).module;
  52695. const fragmentModule = backend.get( fragmentProgram ).module;
  52696. const primitiveState = this._getPrimitiveState( object, geometry, material );
  52697. const depthCompare = this._getDepthCompare( material );
  52698. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52699. const sampleCount = this._getSampleCount( renderObject.context );
  52700. const pipelineDescriptor = {
  52701. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  52702. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  52703. fragment: Object.assign( {}, fragmentModule, { targets } ),
  52704. primitive: primitiveState,
  52705. multisample: {
  52706. count: sampleCount,
  52707. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  52708. },
  52709. layout: device.createPipelineLayout( {
  52710. bindGroupLayouts
  52711. } )
  52712. };
  52713. const depthStencil = {};
  52714. const renderDepth = renderObject.context.depth;
  52715. const renderStencil = renderObject.context.stencil;
  52716. if ( renderDepth === true || renderStencil === true ) {
  52717. if ( renderDepth === true ) {
  52718. depthStencil.format = depthStencilFormat;
  52719. depthStencil.depthWriteEnabled = material.depthWrite;
  52720. depthStencil.depthCompare = depthCompare;
  52721. }
  52722. if ( renderStencil === true ) {
  52723. depthStencil.stencilFront = stencilFront;
  52724. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  52725. depthStencil.stencilReadMask = material.stencilFuncMask;
  52726. depthStencil.stencilWriteMask = material.stencilWriteMask;
  52727. }
  52728. if ( material.polygonOffset === true ) {
  52729. depthStencil.depthBias = material.polygonOffsetUnits;
  52730. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  52731. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  52732. }
  52733. pipelineDescriptor.depthStencil = depthStencil;
  52734. }
  52735. if ( promises === null ) {
  52736. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  52737. } else {
  52738. const p = new Promise( ( resolve /*, reject*/ ) => {
  52739. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  52740. pipelineData.pipeline = pipeline;
  52741. resolve();
  52742. } );
  52743. } );
  52744. promises.push( p );
  52745. }
  52746. }
  52747. /**
  52748. * Creates GPU render bundle encoder for the given render context.
  52749. *
  52750. * @param {RenderContext} renderContext - The render context.
  52751. * @param {?string} [label='renderBundleEncoder'] - The label.
  52752. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  52753. */
  52754. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  52755. const backend = this.backend;
  52756. const { utils, device } = backend;
  52757. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  52758. const colorFormats = utils.getCurrentColorFormats( renderContext );
  52759. const sampleCount = this._getSampleCount( renderContext );
  52760. const descriptor = {
  52761. label,
  52762. colorFormats,
  52763. depthStencilFormat,
  52764. sampleCount
  52765. };
  52766. return device.createRenderBundleEncoder( descriptor );
  52767. }
  52768. /**
  52769. * Creates a compute pipeline for the given compute node.
  52770. *
  52771. * @param {ComputePipeline} pipeline - The compute pipeline.
  52772. * @param {Array<BindGroup>} bindings - The bindings.
  52773. */
  52774. createComputePipeline( pipeline, bindings ) {
  52775. const backend = this.backend;
  52776. const device = backend.device;
  52777. const computeProgram = backend.get( pipeline.computeProgram ).module;
  52778. const pipelineGPU = backend.get( pipeline );
  52779. // bind group layouts
  52780. const bindGroupLayouts = [];
  52781. for ( const bindingsGroup of bindings ) {
  52782. const bindingsData = backend.get( bindingsGroup );
  52783. bindGroupLayouts.push( bindingsData.layout );
  52784. }
  52785. pipelineGPU.pipeline = device.createComputePipeline( {
  52786. compute: computeProgram,
  52787. layout: device.createPipelineLayout( {
  52788. bindGroupLayouts
  52789. } )
  52790. } );
  52791. }
  52792. /**
  52793. * Returns the blending state as a descriptor object required
  52794. * for the pipeline creation.
  52795. *
  52796. * @private
  52797. * @param {Material} material - The material.
  52798. * @return {Object} The blending state.
  52799. */
  52800. _getBlending( material ) {
  52801. let color, alpha;
  52802. const blending = material.blending;
  52803. const blendSrc = material.blendSrc;
  52804. const blendDst = material.blendDst;
  52805. const blendEquation = material.blendEquation;
  52806. if ( blending === CustomBlending ) {
  52807. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  52808. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  52809. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  52810. color = {
  52811. srcFactor: this._getBlendFactor( blendSrc ),
  52812. dstFactor: this._getBlendFactor( blendDst ),
  52813. operation: this._getBlendOperation( blendEquation )
  52814. };
  52815. alpha = {
  52816. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  52817. dstFactor: this._getBlendFactor( blendDstAlpha ),
  52818. operation: this._getBlendOperation( blendEquationAlpha )
  52819. };
  52820. } else {
  52821. const premultipliedAlpha = material.premultipliedAlpha;
  52822. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  52823. color = {
  52824. srcFactor: srcRGB,
  52825. dstFactor: dstRGB,
  52826. operation: GPUBlendOperation.Add
  52827. };
  52828. alpha = {
  52829. srcFactor: srcAlpha,
  52830. dstFactor: dstAlpha,
  52831. operation: GPUBlendOperation.Add
  52832. };
  52833. };
  52834. if ( premultipliedAlpha ) {
  52835. switch ( blending ) {
  52836. case NormalBlending:
  52837. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52838. break;
  52839. case AdditiveBlending:
  52840. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52841. break;
  52842. case SubtractiveBlending:
  52843. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52844. break;
  52845. case MultiplyBlending:
  52846. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52847. break;
  52848. }
  52849. } else {
  52850. switch ( blending ) {
  52851. case NormalBlending:
  52852. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52853. break;
  52854. case AdditiveBlending:
  52855. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52856. break;
  52857. case SubtractiveBlending:
  52858. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  52859. break;
  52860. case MultiplyBlending:
  52861. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  52862. break;
  52863. }
  52864. }
  52865. }
  52866. if ( color !== undefined && alpha !== undefined ) {
  52867. return { color, alpha };
  52868. } else {
  52869. error( 'WebGPURenderer: Invalid blending: ', blending );
  52870. }
  52871. }
  52872. /**
  52873. * Returns the GPU blend factor which is required for the pipeline creation.
  52874. *
  52875. * @private
  52876. * @param {number} blend - The blend factor as a three.js constant.
  52877. * @return {string} The GPU blend factor.
  52878. */
  52879. _getBlendFactor( blend ) {
  52880. let blendFactor;
  52881. switch ( blend ) {
  52882. case ZeroFactor:
  52883. blendFactor = GPUBlendFactor.Zero;
  52884. break;
  52885. case OneFactor:
  52886. blendFactor = GPUBlendFactor.One;
  52887. break;
  52888. case SrcColorFactor:
  52889. blendFactor = GPUBlendFactor.Src;
  52890. break;
  52891. case OneMinusSrcColorFactor:
  52892. blendFactor = GPUBlendFactor.OneMinusSrc;
  52893. break;
  52894. case SrcAlphaFactor:
  52895. blendFactor = GPUBlendFactor.SrcAlpha;
  52896. break;
  52897. case OneMinusSrcAlphaFactor:
  52898. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  52899. break;
  52900. case DstColorFactor:
  52901. blendFactor = GPUBlendFactor.Dst;
  52902. break;
  52903. case OneMinusDstColorFactor:
  52904. blendFactor = GPUBlendFactor.OneMinusDst;
  52905. break;
  52906. case DstAlphaFactor:
  52907. blendFactor = GPUBlendFactor.DstAlpha;
  52908. break;
  52909. case OneMinusDstAlphaFactor:
  52910. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  52911. break;
  52912. case SrcAlphaSaturateFactor:
  52913. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  52914. break;
  52915. case BlendColorFactor:
  52916. blendFactor = GPUBlendFactor.Constant;
  52917. break;
  52918. case OneMinusBlendColorFactor:
  52919. blendFactor = GPUBlendFactor.OneMinusConstant;
  52920. break;
  52921. default:
  52922. error( 'WebGPURenderer: Blend factor not supported.', blend );
  52923. }
  52924. return blendFactor;
  52925. }
  52926. /**
  52927. * Returns the GPU stencil compare function which is required for the pipeline creation.
  52928. *
  52929. * @private
  52930. * @param {Material} material - The material.
  52931. * @return {string} The GPU stencil compare function.
  52932. */
  52933. _getStencilCompare( material ) {
  52934. let stencilCompare;
  52935. const stencilFunc = material.stencilFunc;
  52936. switch ( stencilFunc ) {
  52937. case NeverStencilFunc:
  52938. stencilCompare = GPUCompareFunction.Never;
  52939. break;
  52940. case AlwaysStencilFunc:
  52941. stencilCompare = GPUCompareFunction.Always;
  52942. break;
  52943. case LessStencilFunc:
  52944. stencilCompare = GPUCompareFunction.Less;
  52945. break;
  52946. case LessEqualStencilFunc:
  52947. stencilCompare = GPUCompareFunction.LessEqual;
  52948. break;
  52949. case EqualStencilFunc:
  52950. stencilCompare = GPUCompareFunction.Equal;
  52951. break;
  52952. case GreaterEqualStencilFunc:
  52953. stencilCompare = GPUCompareFunction.GreaterEqual;
  52954. break;
  52955. case GreaterStencilFunc:
  52956. stencilCompare = GPUCompareFunction.Greater;
  52957. break;
  52958. case NotEqualStencilFunc:
  52959. stencilCompare = GPUCompareFunction.NotEqual;
  52960. break;
  52961. default:
  52962. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  52963. }
  52964. return stencilCompare;
  52965. }
  52966. /**
  52967. * Returns the GPU stencil operation which is required for the pipeline creation.
  52968. *
  52969. * @private
  52970. * @param {number} op - A three.js constant defining the stencil operation.
  52971. * @return {string} The GPU stencil operation.
  52972. */
  52973. _getStencilOperation( op ) {
  52974. let stencilOperation;
  52975. switch ( op ) {
  52976. case KeepStencilOp:
  52977. stencilOperation = GPUStencilOperation.Keep;
  52978. break;
  52979. case ZeroStencilOp:
  52980. stencilOperation = GPUStencilOperation.Zero;
  52981. break;
  52982. case ReplaceStencilOp:
  52983. stencilOperation = GPUStencilOperation.Replace;
  52984. break;
  52985. case InvertStencilOp:
  52986. stencilOperation = GPUStencilOperation.Invert;
  52987. break;
  52988. case IncrementStencilOp:
  52989. stencilOperation = GPUStencilOperation.IncrementClamp;
  52990. break;
  52991. case DecrementStencilOp:
  52992. stencilOperation = GPUStencilOperation.DecrementClamp;
  52993. break;
  52994. case IncrementWrapStencilOp:
  52995. stencilOperation = GPUStencilOperation.IncrementWrap;
  52996. break;
  52997. case DecrementWrapStencilOp:
  52998. stencilOperation = GPUStencilOperation.DecrementWrap;
  52999. break;
  53000. default:
  53001. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  53002. }
  53003. return stencilOperation;
  53004. }
  53005. /**
  53006. * Returns the GPU blend operation which is required for the pipeline creation.
  53007. *
  53008. * @private
  53009. * @param {number} blendEquation - A three.js constant defining the blend equation.
  53010. * @return {string} The GPU blend operation.
  53011. */
  53012. _getBlendOperation( blendEquation ) {
  53013. let blendOperation;
  53014. switch ( blendEquation ) {
  53015. case AddEquation:
  53016. blendOperation = GPUBlendOperation.Add;
  53017. break;
  53018. case SubtractEquation:
  53019. blendOperation = GPUBlendOperation.Subtract;
  53020. break;
  53021. case ReverseSubtractEquation:
  53022. blendOperation = GPUBlendOperation.ReverseSubtract;
  53023. break;
  53024. case MinEquation:
  53025. blendOperation = GPUBlendOperation.Min;
  53026. break;
  53027. case MaxEquation:
  53028. blendOperation = GPUBlendOperation.Max;
  53029. break;
  53030. default:
  53031. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  53032. }
  53033. return blendOperation;
  53034. }
  53035. /**
  53036. * Returns the primitive state as a descriptor object required
  53037. * for the pipeline creation.
  53038. *
  53039. * @private
  53040. * @param {Object3D} object - The 3D object.
  53041. * @param {BufferGeometry} geometry - The geometry.
  53042. * @param {Material} material - The material.
  53043. * @return {Object} The primitive state.
  53044. */
  53045. _getPrimitiveState( object, geometry, material ) {
  53046. const descriptor = {};
  53047. const utils = this.backend.utils;
  53048. //
  53049. descriptor.topology = utils.getPrimitiveTopology( object, material );
  53050. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  53051. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53052. }
  53053. //
  53054. let flipSided = ( material.side === BackSide );
  53055. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  53056. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  53057. //
  53058. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  53059. return descriptor;
  53060. }
  53061. /**
  53062. * Returns the GPU color write mask which is required for the pipeline creation.
  53063. *
  53064. * @private
  53065. * @param {Material} material - The material.
  53066. * @return {number} The GPU color write mask.
  53067. */
  53068. _getColorWriteMask( material ) {
  53069. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  53070. }
  53071. /**
  53072. * Returns the GPU depth compare function which is required for the pipeline creation.
  53073. *
  53074. * @private
  53075. * @param {Material} material - The material.
  53076. * @return {string} The GPU depth compare function.
  53077. */
  53078. _getDepthCompare( material ) {
  53079. let depthCompare;
  53080. if ( material.depthTest === false ) {
  53081. depthCompare = GPUCompareFunction.Always;
  53082. } else {
  53083. const depthFunc = material.depthFunc;
  53084. switch ( depthFunc ) {
  53085. case NeverDepth:
  53086. depthCompare = GPUCompareFunction.Never;
  53087. break;
  53088. case AlwaysDepth:
  53089. depthCompare = GPUCompareFunction.Always;
  53090. break;
  53091. case LessDepth:
  53092. depthCompare = GPUCompareFunction.Less;
  53093. break;
  53094. case LessEqualDepth:
  53095. depthCompare = GPUCompareFunction.LessEqual;
  53096. break;
  53097. case EqualDepth:
  53098. depthCompare = GPUCompareFunction.Equal;
  53099. break;
  53100. case GreaterEqualDepth:
  53101. depthCompare = GPUCompareFunction.GreaterEqual;
  53102. break;
  53103. case GreaterDepth:
  53104. depthCompare = GPUCompareFunction.Greater;
  53105. break;
  53106. case NotEqualDepth:
  53107. depthCompare = GPUCompareFunction.NotEqual;
  53108. break;
  53109. default:
  53110. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  53111. }
  53112. }
  53113. return depthCompare;
  53114. }
  53115. }
  53116. /**
  53117. * Manages a pool of WebGPU timestamp queries for performance measurement.
  53118. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  53119. *
  53120. * @augments TimestampQueryPool
  53121. */
  53122. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  53123. /**
  53124. * Creates a new WebGPU timestamp query pool.
  53125. *
  53126. * @param {GPUDevice} device - The WebGPU device to create queries on.
  53127. * @param {string} type - The type identifier for this query pool.
  53128. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  53129. */
  53130. constructor( device, type, maxQueries = 2048 ) {
  53131. super( maxQueries );
  53132. this.device = device;
  53133. this.type = type;
  53134. this.querySet = this.device.createQuerySet( {
  53135. type: 'timestamp',
  53136. count: this.maxQueries,
  53137. label: `queryset_global_timestamp_${type}`
  53138. } );
  53139. const bufferSize = this.maxQueries * 8;
  53140. this.resolveBuffer = this.device.createBuffer( {
  53141. label: `buffer_timestamp_resolve_${type}`,
  53142. size: bufferSize,
  53143. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53144. } );
  53145. this.resultBuffer = this.device.createBuffer( {
  53146. label: `buffer_timestamp_result_${type}`,
  53147. size: bufferSize,
  53148. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53149. } );
  53150. }
  53151. /**
  53152. * Allocates a pair of queries for a given render context.
  53153. *
  53154. * @param {string} uid - A unique identifier for the render context.
  53155. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  53156. */
  53157. allocateQueriesForContext( uid ) {
  53158. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  53159. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  53160. 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() } ).` );
  53161. return null;
  53162. }
  53163. const baseOffset = this.currentQueryIndex;
  53164. this.currentQueryIndex += 2;
  53165. this.queryOffsets.set( uid, baseOffset );
  53166. return baseOffset;
  53167. }
  53168. /**
  53169. * Asynchronously resolves all pending queries and returns the total duration.
  53170. * If there's already a pending resolve operation, returns that promise instead.
  53171. *
  53172. * @async
  53173. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  53174. */
  53175. async resolveQueriesAsync() {
  53176. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  53177. return this.lastValue;
  53178. }
  53179. if ( this.pendingResolve ) {
  53180. return this.pendingResolve;
  53181. }
  53182. this.pendingResolve = this._resolveQueries();
  53183. try {
  53184. const result = await this.pendingResolve;
  53185. return result;
  53186. } finally {
  53187. this.pendingResolve = null;
  53188. }
  53189. }
  53190. /**
  53191. * Internal method to resolve queries and calculate total duration.
  53192. *
  53193. * @async
  53194. * @private
  53195. * @returns {Promise<number>} The total duration in milliseconds.
  53196. */
  53197. async _resolveQueries() {
  53198. if ( this.isDisposed ) {
  53199. return this.lastValue;
  53200. }
  53201. try {
  53202. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53203. return this.lastValue;
  53204. }
  53205. const currentOffsets = new Map( this.queryOffsets );
  53206. const queryCount = this.currentQueryIndex;
  53207. const bytesUsed = queryCount * 8;
  53208. // Reset state before GPU work
  53209. this.currentQueryIndex = 0;
  53210. this.queryOffsets.clear();
  53211. const commandEncoder = this.device.createCommandEncoder();
  53212. commandEncoder.resolveQuerySet(
  53213. this.querySet,
  53214. 0,
  53215. queryCount,
  53216. this.resolveBuffer,
  53217. 0
  53218. );
  53219. commandEncoder.copyBufferToBuffer(
  53220. this.resolveBuffer,
  53221. 0,
  53222. this.resultBuffer,
  53223. 0,
  53224. bytesUsed
  53225. );
  53226. const commandBuffer = commandEncoder.finish();
  53227. this.device.queue.submit( [ commandBuffer ] );
  53228. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53229. return this.lastValue;
  53230. }
  53231. // Create and track the mapping operation
  53232. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  53233. if ( this.isDisposed ) {
  53234. if ( this.resultBuffer.mapState === 'mapped' ) {
  53235. this.resultBuffer.unmap();
  53236. }
  53237. return this.lastValue;
  53238. }
  53239. //
  53240. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  53241. const framesDuration = {};
  53242. const frames = [];
  53243. for ( const [ uid, baseOffset ] of currentOffsets ) {
  53244. const match = uid.match( /^(.*):f(\d+)$/ );
  53245. const frame = parseInt( match[ 2 ] );
  53246. if ( frames.includes( frame ) === false ) {
  53247. frames.push( frame );
  53248. }
  53249. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  53250. const startTime = times[ baseOffset ];
  53251. const endTime = times[ baseOffset + 1 ];
  53252. const duration = Number( endTime - startTime ) / 1e6;
  53253. this.timestamps.set( uid, duration );
  53254. framesDuration[ frame ] += duration;
  53255. }
  53256. // Return the total duration of the last frame
  53257. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  53258. this.resultBuffer.unmap();
  53259. this.lastValue = totalDuration;
  53260. this.frames = frames;
  53261. return totalDuration;
  53262. } catch ( error ) {
  53263. error( 'Error resolving queries:', error );
  53264. if ( this.resultBuffer.mapState === 'mapped' ) {
  53265. this.resultBuffer.unmap();
  53266. }
  53267. return this.lastValue;
  53268. }
  53269. }
  53270. /**
  53271. * Dispose of the query pool.
  53272. *
  53273. * @async
  53274. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  53275. */
  53276. async dispose() {
  53277. if ( this.isDisposed ) {
  53278. return;
  53279. }
  53280. this.isDisposed = true;
  53281. // Wait for pending resolve operation
  53282. if ( this.pendingResolve ) {
  53283. try {
  53284. await this.pendingResolve;
  53285. } catch ( error ) {
  53286. error( 'Error waiting for pending resolve:', error );
  53287. }
  53288. }
  53289. // Ensure buffer is unmapped before destroying
  53290. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  53291. try {
  53292. this.resultBuffer.unmap();
  53293. } catch ( error ) {
  53294. error( 'Error unmapping buffer:', error );
  53295. }
  53296. }
  53297. // Destroy resources
  53298. if ( this.querySet ) {
  53299. this.querySet.destroy();
  53300. this.querySet = null;
  53301. }
  53302. if ( this.resolveBuffer ) {
  53303. this.resolveBuffer.destroy();
  53304. this.resolveBuffer = null;
  53305. }
  53306. if ( this.resultBuffer ) {
  53307. this.resultBuffer.destroy();
  53308. this.resultBuffer = null;
  53309. }
  53310. this.queryOffsets.clear();
  53311. this.pendingResolve = null;
  53312. }
  53313. }
  53314. /*// debugger tools
  53315. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  53316. //*/
  53317. /**
  53318. * A backend implementation targeting WebGPU.
  53319. *
  53320. * @private
  53321. * @augments Backend
  53322. */
  53323. class WebGPUBackend extends Backend {
  53324. /**
  53325. * WebGPUBackend options.
  53326. *
  53327. * @typedef {Object} WebGPUBackend~Options
  53328. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53329. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53330. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  53331. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53332. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53333. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53334. * @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.
  53335. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53336. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  53337. * @property {string} [powerPreference=undefined] - The power preference.
  53338. * @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.
  53339. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  53340. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53341. */
  53342. /**
  53343. * Constructs a new WebGPU backend.
  53344. *
  53345. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  53346. */
  53347. constructor( parameters = {} ) {
  53348. super( parameters );
  53349. /**
  53350. * This flag can be used for type testing.
  53351. *
  53352. * @type {boolean}
  53353. * @readonly
  53354. * @default true
  53355. */
  53356. this.isWebGPUBackend = true;
  53357. // some parameters require default values other than "undefined"
  53358. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  53359. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  53360. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  53361. /**
  53362. * Indicates whether the backend is in compatibility mode or not.
  53363. * @type {boolean}
  53364. * @default false
  53365. */
  53366. this.compatibilityMode = this.parameters.compatibilityMode;
  53367. /**
  53368. * A reference to the device.
  53369. *
  53370. * @type {?GPUDevice}
  53371. * @default null
  53372. */
  53373. this.device = null;
  53374. /**
  53375. * A reference to the default render pass descriptor.
  53376. *
  53377. * @type {?Object}
  53378. * @default null
  53379. */
  53380. this.defaultRenderPassdescriptor = null;
  53381. /**
  53382. * A reference to a backend module holding common utility functions.
  53383. *
  53384. * @type {WebGPUUtils}
  53385. */
  53386. this.utils = new WebGPUUtils( this );
  53387. /**
  53388. * A reference to a backend module holding shader attribute-related
  53389. * utility functions.
  53390. *
  53391. * @type {WebGPUAttributeUtils}
  53392. */
  53393. this.attributeUtils = new WebGPUAttributeUtils( this );
  53394. /**
  53395. * A reference to a backend module holding shader binding-related
  53396. * utility functions.
  53397. *
  53398. * @type {WebGPUBindingUtils}
  53399. */
  53400. this.bindingUtils = new WebGPUBindingUtils( this );
  53401. /**
  53402. * A reference to a backend module holding shader pipeline-related
  53403. * utility functions.
  53404. *
  53405. * @type {WebGPUPipelineUtils}
  53406. */
  53407. this.pipelineUtils = new WebGPUPipelineUtils( this );
  53408. /**
  53409. * A reference to a backend module holding shader texture-related
  53410. * utility functions.
  53411. *
  53412. * @type {WebGPUTextureUtils}
  53413. */
  53414. this.textureUtils = new WebGPUTextureUtils( this );
  53415. /**
  53416. * A map that manages the resolve buffers for occlusion queries.
  53417. *
  53418. * @type {Map<number,GPUBuffer>}
  53419. */
  53420. this.occludedResolveCache = new Map();
  53421. }
  53422. /**
  53423. * Initializes the backend so it is ready for usage.
  53424. *
  53425. * @async
  53426. * @param {Renderer} renderer - The renderer.
  53427. * @return {Promise} A Promise that resolves when the backend has been initialized.
  53428. */
  53429. async init( renderer ) {
  53430. await super.init( renderer );
  53431. //
  53432. const parameters = this.parameters;
  53433. // create the device if it is not passed with parameters
  53434. let device;
  53435. if ( parameters.device === undefined ) {
  53436. const adapterOptions = {
  53437. powerPreference: parameters.powerPreference,
  53438. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  53439. };
  53440. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  53441. if ( adapter === null ) {
  53442. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  53443. }
  53444. // feature support
  53445. const features = Object.values( GPUFeatureName );
  53446. const supportedFeatures = [];
  53447. for ( const name of features ) {
  53448. if ( adapter.features.has( name ) ) {
  53449. supportedFeatures.push( name );
  53450. }
  53451. }
  53452. const deviceDescriptor = {
  53453. requiredFeatures: supportedFeatures,
  53454. requiredLimits: parameters.requiredLimits
  53455. };
  53456. device = await adapter.requestDevice( deviceDescriptor );
  53457. } else {
  53458. device = parameters.device;
  53459. }
  53460. device.lost.then( ( info ) => {
  53461. const deviceLossInfo = {
  53462. api: 'WebGPU',
  53463. message: info.message || 'Unknown reason',
  53464. reason: info.reason || null,
  53465. originalEvent: info
  53466. };
  53467. renderer.onDeviceLost( deviceLossInfo );
  53468. } );
  53469. this.device = device;
  53470. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  53471. this.updateSize();
  53472. }
  53473. /**
  53474. * A reference to the context.
  53475. *
  53476. * @type {?GPUCanvasContext}
  53477. * @default null
  53478. */
  53479. get context() {
  53480. const canvasTarget = this.renderer.getCanvasTarget();
  53481. const canvasData = this.get( canvasTarget );
  53482. let context = canvasData.context;
  53483. if ( context === undefined ) {
  53484. const parameters = this.parameters;
  53485. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  53486. context = parameters.context;
  53487. } else {
  53488. context = canvasTarget.domElement.getContext( 'webgpu' );
  53489. }
  53490. // OffscreenCanvas does not have setAttribute, see #22811
  53491. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  53492. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  53493. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  53494. context.configure( {
  53495. device: this.device,
  53496. format: this.utils.getPreferredCanvasFormat(),
  53497. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  53498. alphaMode: alphaMode,
  53499. toneMapping: {
  53500. mode: toneMappingMode
  53501. }
  53502. } );
  53503. canvasData.context = context;
  53504. }
  53505. return context;
  53506. }
  53507. /**
  53508. * The coordinate system of the backend.
  53509. *
  53510. * @type {number}
  53511. * @readonly
  53512. */
  53513. get coordinateSystem() {
  53514. return WebGPUCoordinateSystem;
  53515. }
  53516. /**
  53517. * This method performs a readback operation by moving buffer data from
  53518. * a storage buffer attribute from the GPU to the CPU.
  53519. *
  53520. * @async
  53521. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53522. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53523. */
  53524. async getArrayBufferAsync( attribute ) {
  53525. return await this.attributeUtils.getArrayBufferAsync( attribute );
  53526. }
  53527. /**
  53528. * Returns the backend's rendering context.
  53529. *
  53530. * @return {GPUCanvasContext} The rendering context.
  53531. */
  53532. getContext() {
  53533. return this.context;
  53534. }
  53535. /**
  53536. * Returns the default render pass descriptor.
  53537. *
  53538. * In WebGPU, the default framebuffer must be configured
  53539. * like custom framebuffers so the backend needs a render
  53540. * pass descriptor even when rendering directly to screen.
  53541. *
  53542. * @private
  53543. * @return {Object} The render pass descriptor.
  53544. */
  53545. _getDefaultRenderPassDescriptor() {
  53546. const renderer = this.renderer;
  53547. const canvasTarget = renderer.getCanvasTarget();
  53548. const canvasData = this.get( canvasTarget );
  53549. const samples = renderer.currentSamples;
  53550. let descriptor = canvasData.descriptor;
  53551. if ( descriptor === undefined || canvasData.samples !== samples ) {
  53552. descriptor = {
  53553. colorAttachments: [ {
  53554. view: null
  53555. } ]
  53556. };
  53557. if ( renderer.depth === true || renderer.stencil === true ) {
  53558. descriptor.depthStencilAttachment = {
  53559. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  53560. };
  53561. }
  53562. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53563. if ( samples > 0 ) {
  53564. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  53565. } else {
  53566. colorAttachment.resolveTarget = undefined;
  53567. }
  53568. canvasData.descriptor = descriptor;
  53569. canvasData.samples = samples;
  53570. }
  53571. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53572. if ( samples > 0 ) {
  53573. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  53574. } else {
  53575. colorAttachment.view = this.context.getCurrentTexture().createView();
  53576. }
  53577. return descriptor;
  53578. }
  53579. /**
  53580. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  53581. *
  53582. * @param {RenderContext} renderContext - The render context.
  53583. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  53584. *
  53585. * @private
  53586. */
  53587. _isRenderCameraDepthArray( renderContext ) {
  53588. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  53589. }
  53590. /**
  53591. * Returns the render pass descriptor for the given render context.
  53592. *
  53593. * @private
  53594. * @param {RenderContext} renderContext - The render context.
  53595. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  53596. * @return {Object} The render pass descriptor.
  53597. */
  53598. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  53599. const renderTarget = renderContext.renderTarget;
  53600. const renderTargetData = this.get( renderTarget );
  53601. let descriptors = renderTargetData.descriptors;
  53602. if ( descriptors === undefined ||
  53603. renderTargetData.width !== renderTarget.width ||
  53604. renderTargetData.height !== renderTarget.height ||
  53605. renderTargetData.samples !== renderTarget.samples
  53606. ) {
  53607. descriptors = {};
  53608. renderTargetData.descriptors = descriptors;
  53609. }
  53610. const cacheKey = renderContext.getCacheKey();
  53611. let descriptorBase = descriptors[ cacheKey ];
  53612. if ( descriptorBase === undefined ) {
  53613. const textures = renderContext.textures;
  53614. const textureViews = [];
  53615. let sliceIndex;
  53616. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  53617. for ( let i = 0; i < textures.length; i ++ ) {
  53618. const textureData = this.get( textures[ i ] );
  53619. const viewDescriptor = {
  53620. label: `colorAttachment_${ i }`,
  53621. baseMipLevel: renderContext.activeMipmapLevel,
  53622. mipLevelCount: 1,
  53623. baseArrayLayer: renderContext.activeCubeFace,
  53624. arrayLayerCount: 1,
  53625. dimension: GPUTextureViewDimension.TwoD
  53626. };
  53627. if ( renderTarget.isRenderTarget3D ) {
  53628. sliceIndex = renderContext.activeCubeFace;
  53629. viewDescriptor.baseArrayLayer = 0;
  53630. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  53631. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53632. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  53633. if ( isRenderCameraDepthArray === true ) {
  53634. const cameras = renderContext.camera.cameras;
  53635. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  53636. const layerViewDescriptor = {
  53637. ...viewDescriptor,
  53638. baseArrayLayer: layer,
  53639. arrayLayerCount: 1,
  53640. dimension: GPUTextureViewDimension.TwoD
  53641. };
  53642. const textureView = textureData.texture.createView( layerViewDescriptor );
  53643. textureViews.push( {
  53644. view: textureView,
  53645. resolveTarget: undefined,
  53646. depthSlice: undefined
  53647. } );
  53648. }
  53649. } else {
  53650. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  53651. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53652. }
  53653. }
  53654. if ( isRenderCameraDepthArray !== true ) {
  53655. const textureView = textureData.texture.createView( viewDescriptor );
  53656. let view, resolveTarget;
  53657. if ( textureData.msaaTexture !== undefined ) {
  53658. view = textureData.msaaTexture.createView();
  53659. resolveTarget = textureView;
  53660. } else {
  53661. view = textureView;
  53662. resolveTarget = undefined;
  53663. }
  53664. textureViews.push( {
  53665. view,
  53666. resolveTarget,
  53667. depthSlice: sliceIndex
  53668. } );
  53669. }
  53670. }
  53671. descriptorBase = { textureViews };
  53672. if ( renderContext.depth ) {
  53673. const depthTextureData = this.get( renderContext.depthTexture );
  53674. const options = {};
  53675. if ( renderContext.depthTexture.isArrayTexture ) {
  53676. options.dimension = GPUTextureViewDimension.TwoD;
  53677. options.arrayLayerCount = 1;
  53678. options.baseArrayLayer = renderContext.activeCubeFace;
  53679. }
  53680. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  53681. }
  53682. descriptors[ cacheKey ] = descriptorBase;
  53683. renderTargetData.width = renderTarget.width;
  53684. renderTargetData.height = renderTarget.height;
  53685. renderTargetData.samples = renderTarget.samples;
  53686. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  53687. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  53688. }
  53689. const descriptor = {
  53690. colorAttachments: []
  53691. };
  53692. // Apply dynamic properties to cached views
  53693. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  53694. const viewInfo = descriptorBase.textureViews[ i ];
  53695. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  53696. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  53697. clearValue = colorAttachmentsConfig.clearValue;
  53698. }
  53699. descriptor.colorAttachments.push( {
  53700. view: viewInfo.view,
  53701. depthSlice: viewInfo.depthSlice,
  53702. resolveTarget: viewInfo.resolveTarget,
  53703. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  53704. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  53705. clearValue: clearValue
  53706. } );
  53707. }
  53708. if ( descriptorBase.depthStencilView ) {
  53709. descriptor.depthStencilAttachment = {
  53710. view: descriptorBase.depthStencilView
  53711. };
  53712. }
  53713. return descriptor;
  53714. }
  53715. /**
  53716. * This method is executed at the beginning of a render call and prepares
  53717. * the WebGPU state for upcoming render calls
  53718. *
  53719. * @param {RenderContext} renderContext - The render context.
  53720. */
  53721. beginRender( renderContext ) {
  53722. const renderContextData = this.get( renderContext );
  53723. //
  53724. const device = this.device;
  53725. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53726. let occlusionQuerySet;
  53727. if ( occlusionQueryCount > 0 ) {
  53728. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  53729. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  53730. // Get a reference to the array of objects with queries. The renderContextData property
  53731. // can be changed by another render pass before the buffer.mapAsyc() completes.
  53732. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  53733. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  53734. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  53735. //
  53736. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  53737. renderContextData.occlusionQuerySet = occlusionQuerySet;
  53738. renderContextData.occlusionQueryIndex = 0;
  53739. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  53740. renderContextData.lastOcclusionObject = null;
  53741. }
  53742. let descriptor;
  53743. if ( renderContext.textures === null ) {
  53744. descriptor = this._getDefaultRenderPassDescriptor();
  53745. } else {
  53746. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  53747. }
  53748. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  53749. descriptor.occlusionQuerySet = occlusionQuerySet;
  53750. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53751. if ( renderContext.textures !== null ) {
  53752. const colorAttachments = descriptor.colorAttachments;
  53753. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  53754. const colorAttachment = colorAttachments[ i ];
  53755. if ( renderContext.clearColor ) {
  53756. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  53757. colorAttachment.loadOp = GPULoadOp.Clear;
  53758. } else {
  53759. colorAttachment.loadOp = GPULoadOp.Load;
  53760. }
  53761. colorAttachment.storeOp = GPUStoreOp.Store;
  53762. }
  53763. } else {
  53764. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53765. if ( renderContext.clearColor ) {
  53766. colorAttachment.clearValue = renderContext.clearColorValue;
  53767. colorAttachment.loadOp = GPULoadOp.Clear;
  53768. } else {
  53769. colorAttachment.loadOp = GPULoadOp.Load;
  53770. }
  53771. colorAttachment.storeOp = GPUStoreOp.Store;
  53772. }
  53773. //
  53774. if ( renderContext.depth ) {
  53775. if ( renderContext.clearDepth ) {
  53776. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  53777. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  53778. } else {
  53779. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53780. }
  53781. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53782. }
  53783. if ( renderContext.stencil ) {
  53784. if ( renderContext.clearStencil ) {
  53785. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  53786. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  53787. } else {
  53788. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53789. }
  53790. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53791. }
  53792. //
  53793. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  53794. // shadow arrays - prepare bundle encoders for each camera in an array camera
  53795. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53796. const cameras = renderContext.camera.cameras;
  53797. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  53798. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  53799. } else {
  53800. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  53801. }
  53802. // Create bundle encoders for each layer
  53803. renderContextData.bundleEncoders = [];
  53804. renderContextData.bundleSets = [];
  53805. // Create separate bundle encoders for each camera in the array
  53806. for ( let i = 0; i < cameras.length; i ++ ) {
  53807. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  53808. renderContext,
  53809. 'renderBundleArrayCamera_' + i
  53810. );
  53811. // Initialize state tracking for this bundle
  53812. const bundleSets = {
  53813. attributes: {},
  53814. bindingGroups: [],
  53815. pipeline: null,
  53816. index: null
  53817. };
  53818. renderContextData.bundleEncoders.push( bundleEncoder );
  53819. renderContextData.bundleSets.push( bundleSets );
  53820. }
  53821. // We'll complete the bundles in finishRender
  53822. renderContextData.currentPass = null;
  53823. } else {
  53824. const currentPass = encoder.beginRenderPass( descriptor );
  53825. renderContextData.currentPass = currentPass;
  53826. if ( renderContext.viewport ) {
  53827. this.updateViewport( renderContext );
  53828. }
  53829. if ( renderContext.scissor ) {
  53830. const { x, y, width, height } = renderContext.scissorValue;
  53831. currentPass.setScissorRect( x, y, width, height );
  53832. }
  53833. }
  53834. //
  53835. renderContextData.descriptor = descriptor;
  53836. renderContextData.encoder = encoder;
  53837. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53838. renderContextData.renderBundles = [];
  53839. }
  53840. /**
  53841. * This method creates layer descriptors for each camera in an array camera
  53842. * to prepare for rendering to a depth array texture.
  53843. *
  53844. * @param {RenderContext} renderContext - The render context.
  53845. * @param {Object} renderContextData - The render context data.
  53846. * @param {Object} descriptor - The render pass descriptor.
  53847. * @param {ArrayCamera} cameras - The array camera.
  53848. *
  53849. * @private
  53850. */
  53851. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  53852. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53853. renderContextData.layerDescriptors = [];
  53854. const depthTextureData = this.get( renderContext.depthTexture );
  53855. if ( ! depthTextureData.viewCache ) {
  53856. depthTextureData.viewCache = [];
  53857. }
  53858. for ( let i = 0; i < cameras.length; i ++ ) {
  53859. const layerDescriptor = {
  53860. ...descriptor,
  53861. colorAttachments: [ {
  53862. ...descriptor.colorAttachments[ 0 ],
  53863. view: descriptor.colorAttachments[ i ].view
  53864. } ]
  53865. };
  53866. if ( descriptor.depthStencilAttachment ) {
  53867. const layerIndex = i;
  53868. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  53869. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  53870. dimension: GPUTextureViewDimension.TwoD,
  53871. baseArrayLayer: i,
  53872. arrayLayerCount: 1
  53873. } );
  53874. }
  53875. layerDescriptor.depthStencilAttachment = {
  53876. view: depthTextureData.viewCache[ layerIndex ],
  53877. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  53878. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  53879. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  53880. };
  53881. if ( renderContext.stencil ) {
  53882. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  53883. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  53884. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  53885. }
  53886. } else {
  53887. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  53888. }
  53889. renderContextData.layerDescriptors.push( layerDescriptor );
  53890. }
  53891. }
  53892. /**
  53893. * This method updates the layer descriptors for each camera in an array camera
  53894. * to prepare for rendering to a depth array texture.
  53895. *
  53896. * @param {RenderContext} renderContext - The render context.
  53897. * @param {Object} renderContextData - The render context data.
  53898. * @param {ArrayCamera} cameras - The array camera.
  53899. *
  53900. */
  53901. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  53902. for ( let i = 0; i < cameras.length; i ++ ) {
  53903. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53904. if ( layerDescriptor.depthStencilAttachment ) {
  53905. const depthAttachment = layerDescriptor.depthStencilAttachment;
  53906. if ( renderContext.depth ) {
  53907. if ( renderContext.clearDepth ) {
  53908. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  53909. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  53910. } else {
  53911. depthAttachment.depthLoadOp = GPULoadOp.Load;
  53912. }
  53913. }
  53914. if ( renderContext.stencil ) {
  53915. if ( renderContext.clearStencil ) {
  53916. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  53917. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  53918. } else {
  53919. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  53920. }
  53921. }
  53922. }
  53923. }
  53924. }
  53925. /**
  53926. * This method is executed at the end of a render call and finalizes work
  53927. * after draw calls.
  53928. *
  53929. * @param {RenderContext} renderContext - The render context.
  53930. */
  53931. finishRender( renderContext ) {
  53932. const renderContextData = this.get( renderContext );
  53933. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53934. if ( renderContextData.renderBundles.length > 0 ) {
  53935. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  53936. }
  53937. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  53938. renderContextData.currentPass.endOcclusionQuery();
  53939. }
  53940. // shadow arrays - Execute bundles for each layer
  53941. const encoder = renderContextData.encoder;
  53942. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53943. const bundles = [];
  53944. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  53945. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  53946. bundles.push( bundleEncoder.finish() );
  53947. }
  53948. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  53949. if ( i < bundles.length ) {
  53950. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53951. const renderPass = encoder.beginRenderPass( layerDescriptor );
  53952. if ( renderContext.viewport ) {
  53953. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  53954. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  53955. }
  53956. if ( renderContext.scissor ) {
  53957. const { x, y, width, height } = renderContext.scissorValue;
  53958. renderPass.setScissorRect( x, y, width, height );
  53959. }
  53960. renderPass.executeBundles( [ bundles[ i ] ] );
  53961. renderPass.end();
  53962. }
  53963. }
  53964. } else if ( renderContextData.currentPass ) {
  53965. renderContextData.currentPass.end();
  53966. }
  53967. if ( occlusionQueryCount > 0 ) {
  53968. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  53969. //
  53970. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  53971. if ( queryResolveBuffer === undefined ) {
  53972. queryResolveBuffer = this.device.createBuffer(
  53973. {
  53974. size: bufferSize,
  53975. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53976. }
  53977. );
  53978. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  53979. }
  53980. //
  53981. const readBuffer = this.device.createBuffer(
  53982. {
  53983. size: bufferSize,
  53984. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53985. }
  53986. );
  53987. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  53988. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  53989. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  53990. renderContextData.occlusionQueryBuffer = readBuffer;
  53991. //
  53992. this.resolveOccludedAsync( renderContext );
  53993. }
  53994. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  53995. //
  53996. if ( renderContext.textures !== null ) {
  53997. const textures = renderContext.textures;
  53998. for ( let i = 0; i < textures.length; i ++ ) {
  53999. const texture = textures[ i ];
  54000. if ( texture.generateMipmaps === true ) {
  54001. this.textureUtils.generateMipmaps( texture );
  54002. }
  54003. }
  54004. }
  54005. }
  54006. /**
  54007. * Returns `true` if the given 3D object is fully occluded by other
  54008. * 3D objects in the scene.
  54009. *
  54010. * @param {RenderContext} renderContext - The render context.
  54011. * @param {Object3D} object - The 3D object to test.
  54012. * @return {boolean} Whether the 3D object is fully occluded or not.
  54013. */
  54014. isOccluded( renderContext, object ) {
  54015. const renderContextData = this.get( renderContext );
  54016. return renderContextData.occluded && renderContextData.occluded.has( object );
  54017. }
  54018. /**
  54019. * This method processes the result of occlusion queries and writes it
  54020. * into render context data.
  54021. *
  54022. * @async
  54023. * @param {RenderContext} renderContext - The render context.
  54024. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  54025. */
  54026. async resolveOccludedAsync( renderContext ) {
  54027. const renderContextData = this.get( renderContext );
  54028. // handle occlusion query results
  54029. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  54030. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  54031. const occluded = new WeakSet();
  54032. renderContextData.currentOcclusionQueryObjects = null;
  54033. renderContextData.currentOcclusionQueryBuffer = null;
  54034. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  54035. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  54036. const results = new BigUint64Array( buffer );
  54037. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  54038. if ( results[ i ] === BigInt( 0 ) ) {
  54039. occluded.add( currentOcclusionQueryObjects[ i ] );
  54040. }
  54041. }
  54042. currentOcclusionQueryBuffer.destroy();
  54043. renderContextData.occluded = occluded;
  54044. }
  54045. }
  54046. /**
  54047. * Updates the viewport with the values from the given render context.
  54048. *
  54049. * @param {RenderContext} renderContext - The render context.
  54050. */
  54051. updateViewport( renderContext ) {
  54052. const { currentPass } = this.get( renderContext );
  54053. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54054. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54055. }
  54056. /**
  54057. * Returns the clear color and alpha into a single
  54058. * color object.
  54059. *
  54060. * @return {Color4} The clear color.
  54061. */
  54062. getClearColor() {
  54063. const clearColor = super.getClearColor();
  54064. // only premultiply alpha when alphaMode is "premultiplied"
  54065. if ( this.renderer.alpha === true ) {
  54066. clearColor.r *= clearColor.a;
  54067. clearColor.g *= clearColor.a;
  54068. clearColor.b *= clearColor.a;
  54069. }
  54070. return clearColor;
  54071. }
  54072. /**
  54073. * Performs a clear operation.
  54074. *
  54075. * @param {boolean} color - Whether the color buffer should be cleared or not.
  54076. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  54077. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  54078. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  54079. */
  54080. clear( color, depth, stencil, renderTargetContext = null ) {
  54081. const device = this.device;
  54082. const renderer = this.renderer;
  54083. let colorAttachments = [];
  54084. let depthStencilAttachment;
  54085. let clearValue;
  54086. let supportsDepth;
  54087. let supportsStencil;
  54088. if ( color ) {
  54089. const clearColor = this.getClearColor();
  54090. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  54091. }
  54092. if ( renderTargetContext === null ) {
  54093. supportsDepth = renderer.depth;
  54094. supportsStencil = renderer.stencil;
  54095. const descriptor = this._getDefaultRenderPassDescriptor();
  54096. if ( color ) {
  54097. colorAttachments = descriptor.colorAttachments;
  54098. const colorAttachment = colorAttachments[ 0 ];
  54099. colorAttachment.clearValue = clearValue;
  54100. colorAttachment.loadOp = GPULoadOp.Clear;
  54101. colorAttachment.storeOp = GPUStoreOp.Store;
  54102. }
  54103. if ( supportsDepth || supportsStencil ) {
  54104. depthStencilAttachment = descriptor.depthStencilAttachment;
  54105. }
  54106. } else {
  54107. supportsDepth = renderTargetContext.depth;
  54108. supportsStencil = renderTargetContext.stencil;
  54109. const clearConfig = {
  54110. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  54111. clearValue: color ? clearValue : undefined
  54112. };
  54113. if ( supportsDepth ) {
  54114. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  54115. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  54116. clearConfig.depthStoreOp = GPUStoreOp.Store;
  54117. }
  54118. if ( supportsStencil ) {
  54119. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  54120. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  54121. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  54122. }
  54123. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  54124. colorAttachments = descriptor.colorAttachments;
  54125. depthStencilAttachment = descriptor.depthStencilAttachment;
  54126. }
  54127. if ( supportsDepth && depthStencilAttachment ) {
  54128. if ( depth ) {
  54129. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54130. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  54131. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54132. } else {
  54133. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54134. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54135. }
  54136. }
  54137. //
  54138. if ( supportsStencil && depthStencilAttachment ) {
  54139. if ( stencil ) {
  54140. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54141. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  54142. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54143. } else {
  54144. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54145. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54146. }
  54147. }
  54148. //
  54149. const encoder = device.createCommandEncoder( { label: 'clear' } );
  54150. const currentPass = encoder.beginRenderPass( {
  54151. colorAttachments,
  54152. depthStencilAttachment
  54153. } );
  54154. currentPass.end();
  54155. device.queue.submit( [ encoder.finish() ] );
  54156. }
  54157. // compute
  54158. /**
  54159. * This method is executed at the beginning of a compute call and
  54160. * prepares the state for upcoming compute tasks.
  54161. *
  54162. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54163. */
  54164. beginCompute( computeGroup ) {
  54165. const groupGPU = this.get( computeGroup );
  54166. //
  54167. const descriptor = {
  54168. label: 'computeGroup_' + computeGroup.id
  54169. };
  54170. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  54171. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  54172. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  54173. }
  54174. /**
  54175. * Executes a compute command for the given compute node.
  54176. *
  54177. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  54178. * @param {Node} computeNode - The compute node.
  54179. * @param {Array<BindGroup>} bindings - The bindings.
  54180. * @param {ComputePipeline} pipeline - The compute pipeline.
  54181. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  54182. */
  54183. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  54184. const computeNodeData = this.get( computeNode );
  54185. const { passEncoderGPU } = this.get( computeGroup );
  54186. // pipeline
  54187. const pipelineGPU = this.get( pipeline ).pipeline;
  54188. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54189. // bind groups
  54190. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54191. const bindGroup = bindings[ i ];
  54192. const bindingsData = this.get( bindGroup );
  54193. passEncoderGPU.setBindGroup( i, bindingsData.group );
  54194. }
  54195. let dispatchSize;
  54196. if ( dispatchSizeOrCount === null ) {
  54197. dispatchSizeOrCount = computeNode.count;
  54198. }
  54199. if ( typeof dispatchSizeOrCount === 'number' ) {
  54200. // If a single number is given, we calculate the dispatch size based on the workgroup size
  54201. const count = dispatchSizeOrCount;
  54202. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  54203. // cache dispatch size to avoid recalculating it every time
  54204. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  54205. computeNodeData.count = count;
  54206. const workgroupSize = computeNode.workgroupSize;
  54207. let size = workgroupSize[ 0 ];
  54208. for ( let i = 1; i < workgroupSize.length; i ++ )
  54209. size *= workgroupSize[ i ];
  54210. const dispatchCount = Math.ceil( count / size );
  54211. //
  54212. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  54213. dispatchSize = [ dispatchCount, 1, 1 ];
  54214. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  54215. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  54216. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  54217. }
  54218. computeNodeData.dispatchSize = dispatchSize;
  54219. }
  54220. dispatchSize = computeNodeData.dispatchSize;
  54221. } else {
  54222. dispatchSize = dispatchSizeOrCount;
  54223. }
  54224. //
  54225. passEncoderGPU.dispatchWorkgroups(
  54226. dispatchSize[ 0 ],
  54227. dispatchSize[ 1 ] || 1,
  54228. dispatchSize[ 2 ] || 1
  54229. );
  54230. }
  54231. /**
  54232. * This method is executed at the end of a compute call and
  54233. * finalizes work after compute tasks.
  54234. *
  54235. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54236. */
  54237. finishCompute( computeGroup ) {
  54238. const groupData = this.get( computeGroup );
  54239. groupData.passEncoderGPU.end();
  54240. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  54241. }
  54242. // render object
  54243. /**
  54244. * Executes a draw command for the given render object.
  54245. *
  54246. * @param {RenderObject} renderObject - The render object to draw.
  54247. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  54248. */
  54249. draw( renderObject, info ) {
  54250. const { object, material, context, pipeline } = renderObject;
  54251. const bindings = renderObject.getBindings();
  54252. const renderContextData = this.get( context );
  54253. const pipelineGPU = this.get( pipeline ).pipeline;
  54254. const index = renderObject.getIndex();
  54255. const hasIndex = ( index !== null );
  54256. const drawParams = renderObject.getDrawParameters();
  54257. if ( drawParams === null ) return;
  54258. // pipeline
  54259. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  54260. // pipeline
  54261. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54262. currentSets.pipeline = pipelineGPU;
  54263. // bind groups
  54264. const currentBindingGroups = currentSets.bindingGroups;
  54265. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54266. const bindGroup = bindings[ i ];
  54267. const bindingsData = this.get( bindGroup );
  54268. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  54269. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  54270. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  54271. }
  54272. }
  54273. // attributes
  54274. // index
  54275. if ( hasIndex === true ) {
  54276. if ( currentSets.index !== index ) {
  54277. const buffer = this.get( index ).buffer;
  54278. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54279. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  54280. currentSets.index = index;
  54281. }
  54282. }
  54283. // vertex buffers
  54284. const vertexBuffers = renderObject.getVertexBuffers();
  54285. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  54286. const vertexBuffer = vertexBuffers[ i ];
  54287. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  54288. const buffer = this.get( vertexBuffer ).buffer;
  54289. passEncoderGPU.setVertexBuffer( i, buffer );
  54290. currentSets.attributes[ i ] = vertexBuffer;
  54291. }
  54292. }
  54293. // stencil
  54294. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  54295. passEncoderGPU.setStencilReference( material.stencilRef );
  54296. renderContextData.currentStencilRef = material.stencilRef;
  54297. }
  54298. };
  54299. // Define draw function
  54300. const draw = ( passEncoderGPU, currentSets ) => {
  54301. setPipelineAndBindings( passEncoderGPU, currentSets );
  54302. if ( object.isBatchedMesh === true ) {
  54303. const starts = object._multiDrawStarts;
  54304. const counts = object._multiDrawCounts;
  54305. const drawCount = object._multiDrawCount;
  54306. const drawInstances = object._multiDrawInstances;
  54307. if ( drawInstances !== null ) {
  54308. // @deprecated, r174
  54309. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  54310. }
  54311. for ( let i = 0; i < drawCount; i ++ ) {
  54312. const count = drawInstances ? drawInstances[ i ] : 1;
  54313. const firstInstance = count > 1 ? 0 : i;
  54314. if ( hasIndex === true ) {
  54315. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  54316. } else {
  54317. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  54318. }
  54319. info.update( object, counts[ i ], count );
  54320. }
  54321. } else if ( hasIndex === true ) {
  54322. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  54323. const indirect = renderObject.getIndirect();
  54324. if ( indirect !== null ) {
  54325. const buffer = this.get( indirect ).buffer;
  54326. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  54327. } else {
  54328. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  54329. }
  54330. info.update( object, indexCount, instanceCount );
  54331. } else {
  54332. const { vertexCount, instanceCount, firstVertex } = drawParams;
  54333. const indirect = renderObject.getIndirect();
  54334. if ( indirect !== null ) {
  54335. const buffer = this.get( indirect ).buffer;
  54336. passEncoderGPU.drawIndirect( buffer, 0 );
  54337. } else {
  54338. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  54339. }
  54340. info.update( object, vertexCount, instanceCount );
  54341. }
  54342. };
  54343. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  54344. const cameraData = this.get( renderObject.camera );
  54345. const cameras = renderObject.camera.cameras;
  54346. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  54347. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  54348. const bindingsData = this.get( cameraIndex );
  54349. const indexesGPU = [];
  54350. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  54351. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54352. data[ 0 ] = i;
  54353. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  54354. indexesGPU.push( bindGroupIndex );
  54355. }
  54356. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  54357. }
  54358. const pixelRatio = this.renderer.getPixelRatio();
  54359. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54360. const subCamera = cameras[ i ];
  54361. if ( object.layers.test( subCamera.layers ) ) {
  54362. const vp = subCamera.viewport;
  54363. let pass = renderContextData.currentPass;
  54364. let sets = renderContextData.currentSets;
  54365. if ( renderContextData.bundleEncoders ) {
  54366. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54367. const bundleSets = renderContextData.bundleSets[ i ];
  54368. pass = bundleEncoder;
  54369. sets = bundleSets;
  54370. }
  54371. if ( vp ) {
  54372. pass.setViewport(
  54373. Math.floor( vp.x * pixelRatio ),
  54374. Math.floor( vp.y * pixelRatio ),
  54375. Math.floor( vp.width * pixelRatio ),
  54376. Math.floor( vp.height * pixelRatio ),
  54377. context.viewportValue.minDepth,
  54378. context.viewportValue.maxDepth
  54379. );
  54380. }
  54381. // Set camera index binding for this layer
  54382. if ( cameraIndex && cameraData.indexesGPU ) {
  54383. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  54384. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  54385. }
  54386. draw( pass, sets );
  54387. }
  54388. }
  54389. } else {
  54390. // Regular single camera rendering
  54391. if ( renderContextData.currentPass ) {
  54392. // Handle occlusion queries
  54393. if ( renderContextData.occlusionQuerySet !== undefined ) {
  54394. const lastObject = renderContextData.lastOcclusionObject;
  54395. if ( lastObject !== object ) {
  54396. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  54397. renderContextData.currentPass.endOcclusionQuery();
  54398. renderContextData.occlusionQueryIndex ++;
  54399. }
  54400. if ( object.occlusionTest === true ) {
  54401. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  54402. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  54403. }
  54404. renderContextData.lastOcclusionObject = object;
  54405. }
  54406. }
  54407. draw( renderContextData.currentPass, renderContextData.currentSets );
  54408. }
  54409. }
  54410. }
  54411. // cache key
  54412. /**
  54413. * Returns `true` if the render pipeline requires an update.
  54414. *
  54415. * @param {RenderObject} renderObject - The render object.
  54416. * @return {boolean} Whether the render pipeline requires an update or not.
  54417. */
  54418. needsRenderUpdate( renderObject ) {
  54419. const data = this.get( renderObject );
  54420. const { object, material } = renderObject;
  54421. const utils = this.utils;
  54422. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  54423. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  54424. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54425. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54426. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  54427. let needsUpdate = false;
  54428. if ( data.material !== material || data.materialVersion !== material.version ||
  54429. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  54430. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  54431. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  54432. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  54433. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  54434. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  54435. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  54436. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  54437. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  54438. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  54439. data.primitiveTopology !== primitiveTopology ||
  54440. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  54441. ) {
  54442. data.material = material; data.materialVersion = material.version;
  54443. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  54444. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  54445. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  54446. data.colorWrite = material.colorWrite;
  54447. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  54448. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  54449. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  54450. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  54451. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  54452. data.sampleCount = sampleCount;
  54453. data.colorSpace = colorSpace;
  54454. data.colorFormat = colorFormat;
  54455. data.depthStencilFormat = depthStencilFormat;
  54456. data.primitiveTopology = primitiveTopology;
  54457. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  54458. needsUpdate = true;
  54459. }
  54460. return needsUpdate;
  54461. }
  54462. /**
  54463. * Returns a cache key that is used to identify render pipelines.
  54464. *
  54465. * @param {RenderObject} renderObject - The render object.
  54466. * @return {string} The cache key.
  54467. */
  54468. getRenderCacheKey( renderObject ) {
  54469. const { object, material } = renderObject;
  54470. const utils = this.utils;
  54471. const renderContext = renderObject.context;
  54472. // meshes with negative scale have a different frontFace render pipeline
  54473. // descriptor value so the following must be honored in the cache key
  54474. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  54475. return [
  54476. material.transparent, material.blending, material.premultipliedAlpha,
  54477. material.blendSrc, material.blendDst, material.blendEquation,
  54478. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  54479. material.colorWrite,
  54480. material.depthWrite, material.depthTest, material.depthFunc,
  54481. material.stencilWrite, material.stencilFunc,
  54482. material.stencilFail, material.stencilZFail, material.stencilZPass,
  54483. material.stencilFuncMask, material.stencilWriteMask,
  54484. material.side,
  54485. frontFaceCW,
  54486. utils.getSampleCountRenderContext( renderContext ),
  54487. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  54488. utils.getPrimitiveTopology( object, material ),
  54489. renderObject.getGeometryCacheKey(),
  54490. renderObject.clippingContextCacheKey
  54491. ].join();
  54492. }
  54493. // textures
  54494. /**
  54495. * Updates a GPU sampler for the given texture.
  54496. *
  54497. * @param {Texture} texture - The texture to update the sampler for.
  54498. * @return {string} The current sampler key.
  54499. */
  54500. updateSampler( texture ) {
  54501. return this.textureUtils.updateSampler( texture );
  54502. }
  54503. /**
  54504. * Creates a default texture for the given texture that can be used
  54505. * as a placeholder until the actual texture is ready for usage.
  54506. *
  54507. * @param {Texture} texture - The texture to create a default texture for.
  54508. * @return {boolean} Whether the sampler has been updated or not.
  54509. */
  54510. createDefaultTexture( texture ) {
  54511. return this.textureUtils.createDefaultTexture( texture );
  54512. }
  54513. /**
  54514. * Defines a texture on the GPU for the given texture object.
  54515. *
  54516. * @param {Texture} texture - The texture.
  54517. * @param {Object} [options={}] - Optional configuration parameter.
  54518. */
  54519. createTexture( texture, options ) {
  54520. this.textureUtils.createTexture( texture, options );
  54521. }
  54522. /**
  54523. * Uploads the updated texture data to the GPU.
  54524. *
  54525. * @param {Texture} texture - The texture.
  54526. * @param {Object} [options={}] - Optional configuration parameter.
  54527. */
  54528. updateTexture( texture, options ) {
  54529. this.textureUtils.updateTexture( texture, options );
  54530. }
  54531. /**
  54532. * Generates mipmaps for the given texture.
  54533. *
  54534. * @param {Texture} texture - The texture.
  54535. */
  54536. generateMipmaps( texture ) {
  54537. this.textureUtils.generateMipmaps( texture );
  54538. }
  54539. /**
  54540. * Destroys the GPU data for the given texture object.
  54541. *
  54542. * @param {Texture} texture - The texture.
  54543. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54544. */
  54545. destroyTexture( texture, isDefaultTexture = false ) {
  54546. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  54547. }
  54548. /**
  54549. * Returns texture data as a typed array.
  54550. *
  54551. * @async
  54552. * @param {Texture} texture - The texture to copy.
  54553. * @param {number} x - The x coordinate of the copy origin.
  54554. * @param {number} y - The y coordinate of the copy origin.
  54555. * @param {number} width - The width of the copy.
  54556. * @param {number} height - The height of the copy.
  54557. * @param {number} faceIndex - The face index.
  54558. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54559. */
  54560. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  54561. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  54562. }
  54563. /**
  54564. * Inits a time stamp query for the given render context.
  54565. *
  54566. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  54567. * @param {number} uid - Unique id for the context (e.g. render context id).
  54568. * @param {Object} descriptor - The query descriptor.
  54569. */
  54570. initTimestampQuery( type, uid, descriptor ) {
  54571. if ( ! this.trackTimestamp ) return;
  54572. if ( ! this.timestampQueryPool[ type ] ) {
  54573. // TODO: Variable maxQueries?
  54574. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  54575. }
  54576. const timestampQueryPool = this.timestampQueryPool[ type ];
  54577. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  54578. descriptor.timestampWrites = {
  54579. querySet: timestampQueryPool.querySet,
  54580. beginningOfPassWriteIndex: baseOffset,
  54581. endOfPassWriteIndex: baseOffset + 1,
  54582. };
  54583. }
  54584. // node builder
  54585. /**
  54586. * Returns a node builder for the given render object.
  54587. *
  54588. * @param {RenderObject} object - The render object.
  54589. * @param {Renderer} renderer - The renderer.
  54590. * @return {WGSLNodeBuilder} The node builder.
  54591. */
  54592. createNodeBuilder( object, renderer ) {
  54593. return new WGSLNodeBuilder( object, renderer );
  54594. }
  54595. // program
  54596. /**
  54597. * Creates a shader program from the given programmable stage.
  54598. *
  54599. * @param {ProgrammableStage} program - The programmable stage.
  54600. */
  54601. createProgram( program ) {
  54602. const programGPU = this.get( program );
  54603. programGPU.module = {
  54604. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  54605. entryPoint: 'main'
  54606. };
  54607. }
  54608. /**
  54609. * Destroys the shader program of the given programmable stage.
  54610. *
  54611. * @param {ProgrammableStage} program - The programmable stage.
  54612. */
  54613. destroyProgram( program ) {
  54614. this.delete( program );
  54615. }
  54616. // pipelines
  54617. /**
  54618. * Creates a render pipeline for the given render object.
  54619. *
  54620. * @param {RenderObject} renderObject - The render object.
  54621. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54622. */
  54623. createRenderPipeline( renderObject, promises ) {
  54624. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  54625. }
  54626. /**
  54627. * Creates a compute pipeline for the given compute node.
  54628. *
  54629. * @param {ComputePipeline} computePipeline - The compute pipeline.
  54630. * @param {Array<BindGroup>} bindings - The bindings.
  54631. */
  54632. createComputePipeline( computePipeline, bindings ) {
  54633. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  54634. }
  54635. /**
  54636. * Prepares the state for encoding render bundles.
  54637. *
  54638. * @param {RenderContext} renderContext - The render context.
  54639. */
  54640. beginBundle( renderContext ) {
  54641. const renderContextData = this.get( renderContext );
  54642. renderContextData._currentPass = renderContextData.currentPass;
  54643. renderContextData._currentSets = renderContextData.currentSets;
  54644. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54645. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  54646. }
  54647. /**
  54648. * After processing render bundles this method finalizes related work.
  54649. *
  54650. * @param {RenderContext} renderContext - The render context.
  54651. * @param {RenderBundle} bundle - The render bundle.
  54652. */
  54653. finishBundle( renderContext, bundle ) {
  54654. const renderContextData = this.get( renderContext );
  54655. const bundleEncoder = renderContextData.currentPass;
  54656. const bundleGPU = bundleEncoder.finish();
  54657. this.get( bundle ).bundleGPU = bundleGPU;
  54658. // restore render pass state
  54659. renderContextData.currentSets = renderContextData._currentSets;
  54660. renderContextData.currentPass = renderContextData._currentPass;
  54661. }
  54662. /**
  54663. * Adds a render bundle to the render context data.
  54664. *
  54665. * @param {RenderContext} renderContext - The render context.
  54666. * @param {RenderBundle} bundle - The render bundle to add.
  54667. */
  54668. addBundle( renderContext, bundle ) {
  54669. const renderContextData = this.get( renderContext );
  54670. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  54671. }
  54672. // bindings
  54673. /**
  54674. * Creates bindings from the given bind group definition.
  54675. *
  54676. * @param {BindGroup} bindGroup - The bind group.
  54677. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54678. * @param {number} cacheIndex - The cache index.
  54679. * @param {number} version - The version.
  54680. */
  54681. createBindings( bindGroup, bindings, cacheIndex, version ) {
  54682. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54683. }
  54684. /**
  54685. * Updates the given bind group definition.
  54686. *
  54687. * @param {BindGroup} bindGroup - The bind group.
  54688. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54689. * @param {number} cacheIndex - The cache index.
  54690. * @param {number} version - The version.
  54691. */
  54692. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  54693. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54694. }
  54695. /**
  54696. * Updates a buffer binding.
  54697. *
  54698. * @param {Buffer} binding - The buffer binding to update.
  54699. */
  54700. updateBinding( binding ) {
  54701. this.bindingUtils.updateBinding( binding );
  54702. }
  54703. // attributes
  54704. /**
  54705. * Creates the buffer of an indexed shader attribute.
  54706. *
  54707. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  54708. */
  54709. createIndexAttribute( attribute ) {
  54710. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  54711. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  54712. usage |= GPUBufferUsage.STORAGE;
  54713. }
  54714. this.attributeUtils.createAttribute( attribute, usage );
  54715. }
  54716. /**
  54717. * Creates the GPU buffer of a shader attribute.
  54718. *
  54719. * @param {BufferAttribute} attribute - The buffer attribute.
  54720. */
  54721. createAttribute( attribute ) {
  54722. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54723. }
  54724. /**
  54725. * Creates the GPU buffer of a storage attribute.
  54726. *
  54727. * @param {BufferAttribute} attribute - The buffer attribute.
  54728. */
  54729. createStorageAttribute( attribute ) {
  54730. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54731. }
  54732. /**
  54733. * Creates the GPU buffer of an indirect storage attribute.
  54734. *
  54735. * @param {BufferAttribute} attribute - The buffer attribute.
  54736. */
  54737. createIndirectStorageAttribute( attribute ) {
  54738. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54739. }
  54740. /**
  54741. * Updates the GPU buffer of a shader attribute.
  54742. *
  54743. * @param {BufferAttribute} attribute - The buffer attribute to update.
  54744. */
  54745. updateAttribute( attribute ) {
  54746. this.attributeUtils.updateAttribute( attribute );
  54747. }
  54748. /**
  54749. * Destroys the GPU buffer of a shader attribute.
  54750. *
  54751. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  54752. */
  54753. destroyAttribute( attribute ) {
  54754. this.attributeUtils.destroyAttribute( attribute );
  54755. }
  54756. // canvas
  54757. /**
  54758. * Triggers an update of the default render pass descriptor.
  54759. */
  54760. updateSize() {
  54761. this.delete( this.renderer.getCanvasTarget() );
  54762. }
  54763. // utils public
  54764. /**
  54765. * Returns the maximum anisotropy texture filtering value.
  54766. *
  54767. * @return {number} The maximum anisotropy texture filtering value.
  54768. */
  54769. getMaxAnisotropy() {
  54770. return 16;
  54771. }
  54772. /**
  54773. * Checks if the given feature is supported by the backend.
  54774. *
  54775. * @param {string} name - The feature's name.
  54776. * @return {boolean} Whether the feature is supported or not.
  54777. */
  54778. hasFeature( name ) {
  54779. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  54780. return this.device.features.has( name );
  54781. }
  54782. /**
  54783. * Copies data of the given source texture to the given destination texture.
  54784. *
  54785. * @param {Texture} srcTexture - The source texture.
  54786. * @param {Texture} dstTexture - The destination texture.
  54787. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  54788. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  54789. * @param {number} [srcLevel=0] - The mipmap level to copy.
  54790. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  54791. */
  54792. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54793. let dstX = 0;
  54794. let dstY = 0;
  54795. let dstZ = 0;
  54796. let srcX = 0;
  54797. let srcY = 0;
  54798. let srcZ = 0;
  54799. let srcWidth = srcTexture.image.width;
  54800. let srcHeight = srcTexture.image.height;
  54801. let srcDepth = 1;
  54802. if ( srcRegion !== null ) {
  54803. if ( srcRegion.isBox3 === true ) {
  54804. srcX = srcRegion.min.x;
  54805. srcY = srcRegion.min.y;
  54806. srcZ = srcRegion.min.z;
  54807. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54808. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54809. srcDepth = srcRegion.max.z - srcRegion.min.z;
  54810. } else {
  54811. // Assume it's a Box2
  54812. srcX = srcRegion.min.x;
  54813. srcY = srcRegion.min.y;
  54814. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54815. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54816. srcDepth = 1;
  54817. }
  54818. }
  54819. if ( dstPosition !== null ) {
  54820. dstX = dstPosition.x;
  54821. dstY = dstPosition.y;
  54822. dstZ = dstPosition.z || 0;
  54823. }
  54824. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  54825. const sourceGPU = this.get( srcTexture ).texture;
  54826. const destinationGPU = this.get( dstTexture ).texture;
  54827. encoder.copyTextureToTexture(
  54828. {
  54829. texture: sourceGPU,
  54830. mipLevel: srcLevel,
  54831. origin: { x: srcX, y: srcY, z: srcZ }
  54832. },
  54833. {
  54834. texture: destinationGPU,
  54835. mipLevel: dstLevel,
  54836. origin: { x: dstX, y: dstY, z: dstZ }
  54837. },
  54838. [
  54839. srcWidth,
  54840. srcHeight,
  54841. srcDepth
  54842. ]
  54843. );
  54844. this.device.queue.submit( [ encoder.finish() ] );
  54845. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54846. this.textureUtils.generateMipmaps( dstTexture );
  54847. }
  54848. }
  54849. /**
  54850. * Copies the current bound framebuffer to the given texture.
  54851. *
  54852. * @param {Texture} texture - The destination texture.
  54853. * @param {RenderContext} renderContext - The render context.
  54854. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  54855. */
  54856. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  54857. const renderContextData = this.get( renderContext );
  54858. let sourceGPU = null;
  54859. if ( renderContext.renderTarget ) {
  54860. if ( texture.isDepthTexture ) {
  54861. sourceGPU = this.get( renderContext.depthTexture ).texture;
  54862. } else {
  54863. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  54864. }
  54865. } else {
  54866. if ( texture.isDepthTexture ) {
  54867. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  54868. } else {
  54869. sourceGPU = this.context.getCurrentTexture();
  54870. }
  54871. }
  54872. const destinationGPU = this.get( texture ).texture;
  54873. if ( sourceGPU.format !== destinationGPU.format ) {
  54874. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  54875. return;
  54876. }
  54877. let encoder;
  54878. if ( renderContextData.currentPass ) {
  54879. renderContextData.currentPass.end();
  54880. encoder = renderContextData.encoder;
  54881. } else {
  54882. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  54883. }
  54884. encoder.copyTextureToTexture(
  54885. {
  54886. texture: sourceGPU,
  54887. origin: [ rectangle.x, rectangle.y, 0 ],
  54888. },
  54889. {
  54890. texture: destinationGPU
  54891. },
  54892. [
  54893. rectangle.z,
  54894. rectangle.w
  54895. ]
  54896. );
  54897. if ( renderContextData.currentPass ) {
  54898. const { descriptor } = renderContextData;
  54899. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  54900. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  54901. }
  54902. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54903. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54904. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  54905. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54906. if ( renderContext.viewport ) {
  54907. this.updateViewport( renderContext );
  54908. }
  54909. if ( renderContext.scissor ) {
  54910. const { x, y, width, height } = renderContext.scissorValue;
  54911. renderContextData.currentPass.setScissorRect( x, y, width, height );
  54912. }
  54913. } else {
  54914. this.device.queue.submit( [ encoder.finish() ] );
  54915. }
  54916. if ( texture.generateMipmaps ) {
  54917. this.textureUtils.generateMipmaps( texture );
  54918. }
  54919. }
  54920. dispose() {
  54921. this.textureUtils.dispose();
  54922. }
  54923. }
  54924. /**
  54925. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54926. *
  54927. * @augments SpotLight
  54928. */
  54929. class IESSpotLight extends SpotLight {
  54930. /**
  54931. * Constructs a new IES spot light.
  54932. *
  54933. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54934. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54935. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54936. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54937. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54938. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54939. */
  54940. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54941. super( color, intensity, distance, angle, penumbra, decay );
  54942. /**
  54943. * TODO
  54944. *
  54945. * @type {?Texture}
  54946. * @default null
  54947. */
  54948. this.iesMap = null;
  54949. }
  54950. copy( source, recursive ) {
  54951. super.copy( source, recursive );
  54952. this.iesMap = source.iesMap;
  54953. return this;
  54954. }
  54955. }
  54956. /**
  54957. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54958. *
  54959. * @augments SpotLight
  54960. */
  54961. class ProjectorLight extends SpotLight {
  54962. /**
  54963. * Constructs a new projector light.
  54964. *
  54965. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54966. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54967. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54968. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54969. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54970. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54971. */
  54972. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54973. super( color, intensity, distance, angle, penumbra, decay );
  54974. /**
  54975. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  54976. *
  54977. * @type {?number}
  54978. * @default null
  54979. */
  54980. this.aspect = null;
  54981. }
  54982. copy( source, recursive ) {
  54983. super.copy( source, recursive );
  54984. this.aspect = source.aspect;
  54985. return this;
  54986. }
  54987. }
  54988. /**
  54989. * This version of a node library represents the standard version
  54990. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  54991. * techniques and materials to node-based implementations.
  54992. *
  54993. * @private
  54994. * @augments NodeLibrary
  54995. */
  54996. class StandardNodeLibrary extends NodeLibrary {
  54997. /**
  54998. * Constructs a new standard node library.
  54999. */
  55000. constructor() {
  55001. super();
  55002. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  55003. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  55004. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  55005. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  55006. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  55007. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  55008. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  55009. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  55010. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  55011. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  55012. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  55013. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  55014. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  55015. this.addLight( PointLightNode, PointLight );
  55016. this.addLight( DirectionalLightNode, DirectionalLight );
  55017. this.addLight( RectAreaLightNode, RectAreaLight );
  55018. this.addLight( SpotLightNode, SpotLight );
  55019. this.addLight( AmbientLightNode, AmbientLight );
  55020. this.addLight( HemisphereLightNode, HemisphereLight );
  55021. this.addLight( LightProbeNode, LightProbe );
  55022. this.addLight( IESSpotLightNode, IESSpotLight );
  55023. this.addLight( ProjectorLightNode, ProjectorLight );
  55024. this.addToneMapping( linearToneMapping, LinearToneMapping );
  55025. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  55026. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  55027. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  55028. this.addToneMapping( agxToneMapping, AgXToneMapping );
  55029. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  55030. }
  55031. }
  55032. /*
  55033. const debugHandler = {
  55034. get: function ( target, name ) {
  55035. // Add |update
  55036. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  55037. return target[ name ];
  55038. }
  55039. };
  55040. */
  55041. /**
  55042. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  55043. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  55044. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  55045. *
  55046. * @augments Renderer
  55047. */
  55048. class WebGPURenderer extends Renderer {
  55049. /**
  55050. * WebGPURenderer options.
  55051. *
  55052. * @typedef {Object} WebGPURenderer~Options
  55053. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55054. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55055. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55056. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55057. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55058. * @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.
  55059. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55060. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  55061. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55062. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  55063. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  55064. */
  55065. /**
  55066. * Constructs a new WebGPU renderer.
  55067. *
  55068. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  55069. */
  55070. constructor( parameters = {} ) {
  55071. let BackendClass;
  55072. if ( parameters.forceWebGL ) {
  55073. BackendClass = WebGLBackend;
  55074. } else {
  55075. BackendClass = WebGPUBackend;
  55076. parameters.getFallback = () => {
  55077. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  55078. return new WebGLBackend( parameters );
  55079. };
  55080. }
  55081. const backend = new BackendClass( parameters );
  55082. //super( new Proxy( backend, debugHandler ) );
  55083. super( backend, parameters );
  55084. /**
  55085. * The generic default value is overwritten with the
  55086. * standard node library for type mapping.
  55087. *
  55088. * @type {StandardNodeLibrary}
  55089. */
  55090. this.library = new StandardNodeLibrary();
  55091. /**
  55092. * This flag can be used for type testing.
  55093. *
  55094. * @type {boolean}
  55095. * @readonly
  55096. * @default true
  55097. */
  55098. this.isWebGPURenderer = true;
  55099. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  55100. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  55101. }
  55102. }
  55103. }
  55104. /**
  55105. * A specialized group which enables applications access to the
  55106. * Render Bundle API of WebGPU. The group with all its descendant nodes
  55107. * are considered as one render bundle and processed as such by
  55108. * the renderer.
  55109. *
  55110. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  55111. * With a WebGL backend, the group can technically be rendered but without
  55112. * any performance improvements.
  55113. *
  55114. * @augments Group
  55115. */
  55116. class BundleGroup extends Group {
  55117. /**
  55118. * Constructs a new bundle group.
  55119. */
  55120. constructor() {
  55121. super();
  55122. /**
  55123. * This flag can be used for type testing.
  55124. *
  55125. * @type {boolean}
  55126. * @readonly
  55127. * @default true
  55128. */
  55129. this.isBundleGroup = true;
  55130. /**
  55131. * This property is only relevant for detecting types
  55132. * during serialization/deserialization. It should always
  55133. * match the class name.
  55134. *
  55135. * @type {string}
  55136. * @readonly
  55137. * @default 'BundleGroup'
  55138. */
  55139. this.type = 'BundleGroup';
  55140. /**
  55141. * Whether the bundle is static or not. When set to `true`, the structure
  55142. * is assumed to be static and does not change. E.g. no new objects are
  55143. * added to the group
  55144. *
  55145. * If a change is required, an update can still be forced by setting the
  55146. * `needsUpdate` flag to `true`.
  55147. *
  55148. * @type {boolean}
  55149. * @default true
  55150. */
  55151. this.static = true;
  55152. /**
  55153. * The bundle group's version.
  55154. *
  55155. * @type {number}
  55156. * @readonly
  55157. * @default 0
  55158. */
  55159. this.version = 0;
  55160. }
  55161. /**
  55162. * Set this property to `true` when the bundle group has changed.
  55163. *
  55164. * @type {boolean}
  55165. * @default false
  55166. * @param {boolean} value
  55167. */
  55168. set needsUpdate( value ) {
  55169. if ( value === true ) this.version ++;
  55170. }
  55171. }
  55172. /**
  55173. * This module is responsible to manage the post processing setups in apps.
  55174. * You usually create a single instance of this class and use it to define
  55175. * the output of your post processing effect chain.
  55176. * ```js
  55177. * const postProcessing = new PostProcessing( renderer );
  55178. *
  55179. * const scenePass = pass( scene, camera );
  55180. *
  55181. * postProcessing.outputNode = scenePass;
  55182. * ```
  55183. *
  55184. * Note: This module can only be used with `WebGPURenderer`.
  55185. */
  55186. class PostProcessing {
  55187. /**
  55188. * Constructs a new post processing management module.
  55189. *
  55190. * @param {Renderer} renderer - A reference to the renderer.
  55191. * @param {Node<vec4>} outputNode - An optional output node.
  55192. */
  55193. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  55194. /**
  55195. * A reference to the renderer.
  55196. *
  55197. * @type {Renderer}
  55198. */
  55199. this.renderer = renderer;
  55200. /**
  55201. * A node which defines the final output of the post
  55202. * processing. This is usually the last node in a chain
  55203. * of effect nodes.
  55204. *
  55205. * @type {Node<vec4>}
  55206. */
  55207. this.outputNode = outputNode;
  55208. /**
  55209. * Whether the default output tone mapping and color
  55210. * space transformation should be enabled or not.
  55211. *
  55212. * It is enabled by default by it must be disabled when
  55213. * effects must be executed after tone mapping and color
  55214. * space conversion. A typical example is FXAA which
  55215. * requires sRGB input.
  55216. *
  55217. * When set to `false`, the app must control the output
  55218. * transformation with `RenderOutputNode`.
  55219. *
  55220. * ```js
  55221. * const outputPass = renderOutput( scenePass );
  55222. * ```
  55223. *
  55224. * @type {boolean}
  55225. */
  55226. this.outputColorTransform = true;
  55227. /**
  55228. * Must be set to `true` when the output node changes.
  55229. *
  55230. * @type {Node<vec4>}
  55231. */
  55232. this.needsUpdate = true;
  55233. const material = new NodeMaterial();
  55234. material.name = 'PostProcessing';
  55235. /**
  55236. * The full screen quad that is used to render
  55237. * the effects.
  55238. *
  55239. * @private
  55240. * @type {QuadMesh}
  55241. */
  55242. this._quadMesh = new QuadMesh( material );
  55243. this._quadMesh.name = 'Post-Processing';
  55244. /**
  55245. * The context of the post processing stack.
  55246. *
  55247. * @private
  55248. * @type {?Object}
  55249. * @default null
  55250. */
  55251. this._context = null;
  55252. }
  55253. /**
  55254. * When `PostProcessing` is used to apply post processing effects,
  55255. * the application must use this version of `render()` inside
  55256. * its animation loop (not the one from the renderer).
  55257. */
  55258. render() {
  55259. const renderer = this.renderer;
  55260. this._update();
  55261. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55262. const toneMapping = renderer.toneMapping;
  55263. const outputColorSpace = renderer.outputColorSpace;
  55264. renderer.toneMapping = NoToneMapping;
  55265. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55266. //
  55267. const currentXR = renderer.xr.enabled;
  55268. renderer.xr.enabled = false;
  55269. this._quadMesh.render( renderer );
  55270. renderer.xr.enabled = currentXR;
  55271. //
  55272. renderer.toneMapping = toneMapping;
  55273. renderer.outputColorSpace = outputColorSpace;
  55274. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55275. }
  55276. /**
  55277. * Returns the current context of the post processing stack.
  55278. *
  55279. * @readonly
  55280. * @type {?Object}
  55281. */
  55282. get context() {
  55283. return this._context;
  55284. }
  55285. /**
  55286. * Frees internal resources.
  55287. */
  55288. dispose() {
  55289. this._quadMesh.material.dispose();
  55290. }
  55291. /**
  55292. * Updates the state of the module.
  55293. *
  55294. * @private
  55295. */
  55296. _update() {
  55297. if ( this.needsUpdate === true ) {
  55298. const renderer = this.renderer;
  55299. const toneMapping = renderer.toneMapping;
  55300. const outputColorSpace = renderer.outputColorSpace;
  55301. const context = {
  55302. postProcessing: this,
  55303. onBeforePostProcessing: null,
  55304. onAfterPostProcessing: null
  55305. };
  55306. let outputNode = this.outputNode;
  55307. if ( this.outputColorTransform === true ) {
  55308. outputNode = outputNode.context( context );
  55309. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  55310. } else {
  55311. context.toneMapping = toneMapping;
  55312. context.outputColorSpace = outputColorSpace;
  55313. outputNode = outputNode.context( context );
  55314. }
  55315. this._context = context;
  55316. this._quadMesh.material.fragmentNode = outputNode;
  55317. this._quadMesh.material.needsUpdate = true;
  55318. this.needsUpdate = false;
  55319. }
  55320. }
  55321. /**
  55322. * When `PostProcessing` is used to apply post processing effects,
  55323. * the application must use this version of `renderAsync()` inside
  55324. * its animation loop (not the one from the renderer).
  55325. *
  55326. * @async
  55327. * @deprecated
  55328. * @return {Promise} A Promise that resolves when the render has been finished.
  55329. */
  55330. async renderAsync() {
  55331. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  55332. await this.renderer.init();
  55333. this.render();
  55334. }
  55335. }
  55336. /**
  55337. * This special type of texture is intended for compute shaders.
  55338. * It can be used to compute the data of a texture with a compute shader.
  55339. *
  55340. * Note: This type of texture can only be used with `WebGPURenderer`
  55341. * and a WebGPU backend.
  55342. *
  55343. * @augments Texture
  55344. */
  55345. class StorageTexture extends Texture {
  55346. /**
  55347. * Constructs a new storage texture.
  55348. *
  55349. * @param {number} [width=1] - The storage texture's width.
  55350. * @param {number} [height=1] - The storage texture's height.
  55351. */
  55352. constructor( width = 1, height = 1 ) {
  55353. super();
  55354. /**
  55355. * The image object which just represents the texture's dimension.
  55356. *
  55357. * @type {{width: number, height: number}}
  55358. */
  55359. this.image = { width, height };
  55360. /**
  55361. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55362. *
  55363. * @type {number}
  55364. */
  55365. this.magFilter = LinearFilter;
  55366. /**
  55367. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55368. *
  55369. * @type {number}
  55370. */
  55371. this.minFilter = LinearFilter;
  55372. /**
  55373. * This flag can be used for type testing.
  55374. *
  55375. * @type {boolean}
  55376. * @readonly
  55377. * @default true
  55378. */
  55379. this.isStorageTexture = true;
  55380. /**
  55381. * When `true`, mipmaps will be auto-generated after compute writes.
  55382. * When `false`, mipmaps must be written manually via compute shaders.
  55383. *
  55384. * @type {boolean}
  55385. * @default true
  55386. */
  55387. this.mipmapsAutoUpdate = true;
  55388. }
  55389. /**
  55390. * Sets the size of the storage texture.
  55391. *
  55392. * @param {number} width - The new width of the storage texture.
  55393. * @param {number} height - The new height of the storage texture.
  55394. */
  55395. setSize( width, height ) {
  55396. if ( this.image.width !== width || this.image.height !== height ) {
  55397. this.image.width = width;
  55398. this.image.height = height;
  55399. this.dispose();
  55400. }
  55401. }
  55402. }
  55403. /**
  55404. * This special type of texture is intended for compute shaders.
  55405. * It can be used to compute the data of a texture with a compute shader.
  55406. *
  55407. * Note: This type of texture can only be used with `WebGPURenderer`
  55408. * and a WebGPU backend.
  55409. *
  55410. * @augments Texture
  55411. */
  55412. class Storage3DTexture extends Texture {
  55413. /**
  55414. * Constructs a new storage texture.
  55415. *
  55416. * @param {number} [width=1] - The storage texture's width.
  55417. * @param {number} [height=1] - The storage texture's height.
  55418. * @param {number} [depth=1] - The storage texture's depth.
  55419. */
  55420. constructor( width = 1, height = 1, depth = 1 ) {
  55421. super();
  55422. //inherited from texture. Must be false for 3DTexture
  55423. this.isArrayTexture = false;
  55424. /**
  55425. * The image object which just represents the texture's dimension.
  55426. *
  55427. * @type {{width: number, height: number, depth: number}}
  55428. */
  55429. this.image = { width, height, depth };
  55430. /**
  55431. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55432. *
  55433. * @type {number}
  55434. */
  55435. this.magFilter = LinearFilter;
  55436. /**
  55437. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55438. *
  55439. * @type {number}
  55440. */
  55441. this.minFilter = LinearFilter;
  55442. /**
  55443. * This defines how the texture is wrapped in the depth direction and corresponds to
  55444. * *W* in UVW mapping.
  55445. *
  55446. * @type {number}
  55447. */
  55448. this.wrapR = ClampToEdgeWrapping;
  55449. /**
  55450. * This flag can be used for type testing.
  55451. *
  55452. * @type {boolean}
  55453. * @readonly
  55454. * @default true
  55455. */
  55456. this.isStorageTexture = true;
  55457. /**
  55458. * Indicates whether this texture is a 3D texture.
  55459. *
  55460. * @type {boolean}
  55461. *
  55462. */
  55463. this.is3DTexture = true;
  55464. }
  55465. /**
  55466. * Sets the size of the storage 3d texture.
  55467. *
  55468. * @param {number} width - The new width of the storage texture.
  55469. * @param {number} height - The new height of the storage texture.
  55470. * @param {number} depth - The new depth of the storage texture.
  55471. */
  55472. setSize( width, height, depth ) {
  55473. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55474. this.image.width = width;
  55475. this.image.height = height;
  55476. this.image.depth = depth;
  55477. this.dispose();
  55478. }
  55479. }
  55480. }
  55481. /**
  55482. * This special type of texture is intended for compute shaders.
  55483. * It can be used to compute the data of a texture with a compute shader.
  55484. *
  55485. * Note: This type of texture can only be used with `WebGPURenderer`
  55486. * and a WebGPU backend.
  55487. *
  55488. * @augments Texture
  55489. */
  55490. class StorageArrayTexture extends Texture {
  55491. /**
  55492. * Constructs a new storage texture.
  55493. *
  55494. * @param {number} [width=1] - The storage texture's width.
  55495. * @param {number} [height=1] - The storage texture's height.
  55496. * @param {number} [depth=1] - The storage texture's depth.
  55497. */
  55498. constructor( width = 1, height = 1, depth = 1 ) {
  55499. super();
  55500. //inherited from texture
  55501. this.isArrayTexture = true;
  55502. /**
  55503. * The image object which just represents the texture's dimension.
  55504. *
  55505. * @type {{width: number, height: number, depth: number}}
  55506. */
  55507. this.image = { width, height, depth };
  55508. /**
  55509. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55510. *
  55511. * @type {number}
  55512. */
  55513. this.magFilter = LinearFilter;
  55514. /**
  55515. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55516. *
  55517. * @type {number}
  55518. */
  55519. this.minFilter = LinearFilter;
  55520. /**
  55521. * This flag can be used for type testing.
  55522. *
  55523. * @type {boolean}
  55524. * @readonly
  55525. * @default true
  55526. */
  55527. this.isStorageTexture = true;
  55528. }
  55529. /**
  55530. * Sets the size of the storage array texture.
  55531. *
  55532. * @param {number} width - The new width of the storage texture.
  55533. * @param {number} height - The new height of the storage texture.
  55534. * @param {number} depth - The new depth of the storage texture.
  55535. */
  55536. setSize( width, height, depth ) {
  55537. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55538. this.image.width = width;
  55539. this.image.height = height;
  55540. this.image.depth = depth;
  55541. this.dispose();
  55542. }
  55543. }
  55544. }
  55545. /**
  55546. * This special type of buffer attribute is intended for compute shaders.
  55547. * It can be used to encode draw parameters for indirect draw calls.
  55548. *
  55549. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  55550. * and a WebGPU backend.
  55551. *
  55552. * @augments StorageBufferAttribute
  55553. */
  55554. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  55555. /**
  55556. * Constructs a new storage buffer attribute.
  55557. *
  55558. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  55559. * The subsequent parameter is then obsolete.
  55560. * @param {number} itemSize - The item size.
  55561. */
  55562. constructor( count, itemSize ) {
  55563. super( count, itemSize, Uint32Array );
  55564. /**
  55565. * This flag can be used for type testing.
  55566. *
  55567. * @type {boolean}
  55568. * @readonly
  55569. * @default true
  55570. */
  55571. this.isIndirectStorageBufferAttribute = true;
  55572. }
  55573. }
  55574. /**
  55575. * A loader for loading node objects in the three.js JSON Object/Scene format.
  55576. *
  55577. * @augments Loader
  55578. */
  55579. class NodeLoader extends Loader {
  55580. /**
  55581. * Constructs a new node loader.
  55582. *
  55583. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55584. */
  55585. constructor( manager ) {
  55586. super( manager );
  55587. /**
  55588. * Represents a dictionary of textures.
  55589. *
  55590. * @type {Object<string,Texture>}
  55591. */
  55592. this.textures = {};
  55593. /**
  55594. * Represents a dictionary of node types.
  55595. *
  55596. * @type {Object<string,Node.constructor>}
  55597. */
  55598. this.nodes = {};
  55599. }
  55600. /**
  55601. * Loads the node definitions from the given URL.
  55602. *
  55603. * @param {string} url - The path/URL of the file to be loaded.
  55604. * @param {Function} onLoad - Will be called when load completes.
  55605. * @param {Function} onProgress - Will be called while load progresses.
  55606. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  55607. */
  55608. load( url, onLoad, onProgress, onError ) {
  55609. const loader = new FileLoader( this.manager );
  55610. loader.setPath( this.path );
  55611. loader.setRequestHeader( this.requestHeader );
  55612. loader.setWithCredentials( this.withCredentials );
  55613. loader.load( url, ( text ) => {
  55614. try {
  55615. onLoad( this.parse( JSON.parse( text ) ) );
  55616. } catch ( e ) {
  55617. if ( onError ) {
  55618. onError( e );
  55619. } else {
  55620. error( e );
  55621. }
  55622. this.manager.itemError( url );
  55623. }
  55624. }, onProgress, onError );
  55625. }
  55626. /**
  55627. * Parse the node dependencies for the loaded node.
  55628. *
  55629. * @param {Array<Object>} [json] - The JSON definition
  55630. * @return {Object<string,Node>} A dictionary with node dependencies.
  55631. */
  55632. parseNodes( json ) {
  55633. const nodes = {};
  55634. if ( json !== undefined ) {
  55635. for ( const nodeJSON of json ) {
  55636. const { uuid, type } = nodeJSON;
  55637. nodes[ uuid ] = this.createNodeFromType( type );
  55638. nodes[ uuid ].uuid = uuid;
  55639. }
  55640. const meta = { nodes, textures: this.textures };
  55641. for ( const nodeJSON of json ) {
  55642. nodeJSON.meta = meta;
  55643. const node = nodes[ nodeJSON.uuid ];
  55644. node.deserialize( nodeJSON );
  55645. delete nodeJSON.meta;
  55646. }
  55647. }
  55648. return nodes;
  55649. }
  55650. /**
  55651. * Parses the node from the given JSON.
  55652. *
  55653. * @param {Object} json - The JSON definition
  55654. * @param {string} json.type - The node type.
  55655. * @param {string} json.uuid - The node UUID.
  55656. * @param {Array<Object>} [json.nodes] - The node dependencies.
  55657. * @param {Object} [json.meta] - The meta data.
  55658. * @return {Node} The parsed node.
  55659. */
  55660. parse( json ) {
  55661. const node = this.createNodeFromType( json.type );
  55662. node.uuid = json.uuid;
  55663. const nodes = this.parseNodes( json.nodes );
  55664. const meta = { nodes, textures: this.textures };
  55665. json.meta = meta;
  55666. node.deserialize( json );
  55667. delete json.meta;
  55668. return node;
  55669. }
  55670. /**
  55671. * Defines the dictionary of textures.
  55672. *
  55673. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  55674. * @return {NodeLoader} A reference to this loader.
  55675. */
  55676. setTextures( value ) {
  55677. this.textures = value;
  55678. return this;
  55679. }
  55680. /**
  55681. * Defines the dictionary of node types.
  55682. *
  55683. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55684. * @return {NodeLoader} A reference to this loader.
  55685. */
  55686. setNodes( value ) {
  55687. this.nodes = value;
  55688. return this;
  55689. }
  55690. /**
  55691. * Creates a node object from the given type.
  55692. *
  55693. * @param {string} type - The node type.
  55694. * @return {Node} The created node instance.
  55695. */
  55696. createNodeFromType( type ) {
  55697. if ( this.nodes[ type ] === undefined ) {
  55698. error( 'NodeLoader: Node type not found:', type );
  55699. return float();
  55700. }
  55701. return nodeObject( new this.nodes[ type ]() );
  55702. }
  55703. }
  55704. /**
  55705. * A special type of material loader for loading node materials.
  55706. *
  55707. * @augments MaterialLoader
  55708. */
  55709. class NodeMaterialLoader extends MaterialLoader {
  55710. /**
  55711. * Constructs a new node material loader.
  55712. *
  55713. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55714. */
  55715. constructor( manager ) {
  55716. super( manager );
  55717. /**
  55718. * Represents a dictionary of node types.
  55719. *
  55720. * @type {Object<string,Node.constructor>}
  55721. */
  55722. this.nodes = {};
  55723. /**
  55724. * Represents a dictionary of node material types.
  55725. *
  55726. * @type {Object<string,NodeMaterial.constructor>}
  55727. */
  55728. this.nodeMaterials = {};
  55729. }
  55730. /**
  55731. * Parses the node material from the given JSON.
  55732. *
  55733. * @param {Object} json - The JSON definition
  55734. * @return {NodeMaterial}. The parsed material.
  55735. */
  55736. parse( json ) {
  55737. const material = super.parse( json );
  55738. const nodes = this.nodes;
  55739. const inputNodes = json.inputNodes;
  55740. for ( const property in inputNodes ) {
  55741. const uuid = inputNodes[ property ];
  55742. material[ property ] = nodes[ uuid ];
  55743. }
  55744. return material;
  55745. }
  55746. /**
  55747. * Defines the dictionary of node types.
  55748. *
  55749. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55750. * @return {NodeLoader} A reference to this loader.
  55751. */
  55752. setNodes( value ) {
  55753. this.nodes = value;
  55754. return this;
  55755. }
  55756. /**
  55757. * Defines the dictionary of node material types.
  55758. *
  55759. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55760. * @return {NodeLoader} A reference to this loader.
  55761. */
  55762. setNodeMaterials( value ) {
  55763. this.nodeMaterials = value;
  55764. return this;
  55765. }
  55766. /**
  55767. * Creates a node material from the given type.
  55768. *
  55769. * @param {string} type - The node material type.
  55770. * @return {Node} The created node material instance.
  55771. */
  55772. createMaterialFromType( type ) {
  55773. const materialClass = this.nodeMaterials[ type ];
  55774. if ( materialClass !== undefined ) {
  55775. return new materialClass();
  55776. }
  55777. return super.createMaterialFromType( type );
  55778. }
  55779. }
  55780. /**
  55781. * A special type of object loader for loading 3D objects using
  55782. * node materials.
  55783. *
  55784. * @augments ObjectLoader
  55785. */
  55786. class NodeObjectLoader extends ObjectLoader {
  55787. /**
  55788. * Constructs a new node object loader.
  55789. *
  55790. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55791. */
  55792. constructor( manager ) {
  55793. super( manager );
  55794. /**
  55795. * Represents a dictionary of node types.
  55796. *
  55797. * @type {Object<string,Node.constructor>}
  55798. */
  55799. this.nodes = {};
  55800. /**
  55801. * Represents a dictionary of node material types.
  55802. *
  55803. * @type {Object<string,NodeMaterial.constructor>}
  55804. */
  55805. this.nodeMaterials = {};
  55806. /**
  55807. * A reference to hold the `nodes` JSON property.
  55808. *
  55809. * @private
  55810. * @type {?Object[]}
  55811. */
  55812. this._nodesJSON = null;
  55813. }
  55814. /**
  55815. * Defines the dictionary of node types.
  55816. *
  55817. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55818. * @return {NodeObjectLoader} A reference to this loader.
  55819. */
  55820. setNodes( value ) {
  55821. this.nodes = value;
  55822. return this;
  55823. }
  55824. /**
  55825. * Defines the dictionary of node material types.
  55826. *
  55827. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55828. * @return {NodeObjectLoader} A reference to this loader.
  55829. */
  55830. setNodeMaterials( value ) {
  55831. this.nodeMaterials = value;
  55832. return this;
  55833. }
  55834. /**
  55835. * Parses the node objects from the given JSON.
  55836. *
  55837. * @param {Object} json - The JSON definition
  55838. * @param {Function} onLoad - The onLoad callback function.
  55839. * @return {Object3D}. The parsed 3D object.
  55840. */
  55841. parse( json, onLoad ) {
  55842. this._nodesJSON = json.nodes;
  55843. const data = super.parse( json, onLoad );
  55844. this._nodesJSON = null; // dispose
  55845. return data;
  55846. }
  55847. /**
  55848. * Parses the node objects from the given JSON and textures.
  55849. *
  55850. * @param {Object[]} json - The JSON definition
  55851. * @param {Object<string,Texture>} textures - The texture library.
  55852. * @return {Object<string,Node>}. The parsed nodes.
  55853. */
  55854. parseNodes( json, textures ) {
  55855. if ( json !== undefined ) {
  55856. const loader = new NodeLoader();
  55857. loader.setNodes( this.nodes );
  55858. loader.setTextures( textures );
  55859. return loader.parseNodes( json );
  55860. }
  55861. return {};
  55862. }
  55863. /**
  55864. * Parses the node objects from the given JSON and textures.
  55865. *
  55866. * @param {Object} json - The JSON definition
  55867. * @param {Object<string,Texture>} textures - The texture library.
  55868. * @return {Object<string,NodeMaterial>}. The parsed materials.
  55869. */
  55870. parseMaterials( json, textures ) {
  55871. const materials = {};
  55872. if ( json !== undefined ) {
  55873. const nodes = this.parseNodes( this._nodesJSON, textures );
  55874. const loader = new NodeMaterialLoader();
  55875. loader.setTextures( textures );
  55876. loader.setNodes( nodes );
  55877. loader.setNodeMaterials( this.nodeMaterials );
  55878. for ( let i = 0, l = json.length; i < l; i ++ ) {
  55879. const data = json[ i ];
  55880. materials[ data.uuid ] = loader.parse( data );
  55881. }
  55882. }
  55883. return materials;
  55884. }
  55885. }
  55886. /**
  55887. * In earlier three.js versions, clipping was defined globally
  55888. * on the renderer or on material level. This special version of
  55889. * `THREE.Group` allows to encode the clipping state into the scene
  55890. * graph. Meaning if you create an instance of this group, all
  55891. * descendant 3D objects will be affected by the respective clipping
  55892. * planes.
  55893. *
  55894. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  55895. *
  55896. * @augments Group
  55897. */
  55898. class ClippingGroup extends Group {
  55899. /**
  55900. * Constructs a new clipping group.
  55901. */
  55902. constructor() {
  55903. super();
  55904. /**
  55905. * This flag can be used for type testing.
  55906. *
  55907. * @type {boolean}
  55908. * @readonly
  55909. * @default true
  55910. */
  55911. this.isClippingGroup = true;
  55912. /**
  55913. * An array with clipping planes.
  55914. *
  55915. * @type {Array<Plane>}
  55916. */
  55917. this.clippingPlanes = [];
  55918. /**
  55919. * Whether clipping should be enabled or not.
  55920. *
  55921. * @type {boolean}
  55922. * @default true
  55923. */
  55924. this.enabled = true;
  55925. /**
  55926. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  55927. *
  55928. * @type {boolean}
  55929. * @default false
  55930. */
  55931. this.clipIntersection = false;
  55932. /**
  55933. * Whether shadows should be clipped or not.
  55934. *
  55935. * @type {boolean}
  55936. * @default false
  55937. */
  55938. this.clipShadows = false;
  55939. }
  55940. }
  55941. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BitcastNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Camera, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InspectorBase, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号